'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import TeamCard from '@/components/teams/TeamCard';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Card from '@/components/ui/Card';
import CreateTeamForm from '@/components/teams/CreateTeamForm';
import { getAllTeams, getTeamMembers, type Team } from '@gridpilot/racing/application';

export default function TeamsPage() {
  const router = useRouter();
  const [teams, setTeams] = useState<Team[]>([]);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [memberFilter, setMemberFilter] = useState('all');

  useEffect(() => {
    loadTeams();
  }, []);

  const loadTeams = () => {
    const allTeams = getAllTeams();
    setTeams(allTeams);
  };

  const handleCreateSuccess = (teamId: string) => {
    setShowCreateForm(false);
    loadTeams();
    router.push(`/teams/${teamId}`);
  };

  const filteredTeams = teams.filter((team) => {
    const memberCount = getTeamMembers(team.id).length;
    
    const matchesSearch = team.name.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesMemberCount =
      memberFilter === 'all' ||
      (memberFilter === 'small' && memberCount < 5) ||
      (memberFilter === 'medium' && memberCount >= 5 && memberCount < 10) ||
      (memberFilter === 'large' && memberCount >= 10);

    return matchesSearch && matchesMemberCount;
  });

  const handleTeamClick = (teamId: string) => {
    router.push(`/teams/${teamId}`);
  };

  if (showCreateForm) {
    return (
      <div className="max-w-4xl mx-auto">
        
        <div className="mb-6">
          <Button
            variant="secondary"
            onClick={() => setShowCreateForm(false)}
          >
            ← Back to Teams
          </Button>
        </div>

        <Card>
          <h2 className="text-2xl font-bold text-white mb-6">Create New Team</h2>
          <CreateTeamForm
            onCancel={() => setShowCreateForm(false)}
            onSuccess={handleCreateSuccess}
          />
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto">      
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Teams</h1>
          <p className="text-gray-400">
            Browse and join racing teams
          </p>
        </div>
        <Button variant="primary" onClick={() => setShowCreateForm(true)}>
          Create Team
        </Button>
      </div>

      <Card className="mb-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-400 mb-2">
              Search Teams
            </label>
            <Input
              type="text"
              placeholder="Search by name..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-400 mb-2">
              Team Size
            </label>
            <select
              className="w-full px-3 py-3 bg-iron-gray border-0 rounded-md text-white ring-1 ring-inset ring-charcoal-outline focus:ring-2 focus:ring-primary-blue transition-all duration-150 text-sm"
              value={memberFilter}
              onChange={(e) => setMemberFilter(e.target.value)}
            >
              <option value="all">All Sizes</option>
              <option value="small">Small (&lt;5)</option>
              <option value="medium">Medium (5-9)</option>
              <option value="large">Large (10+)</option>
            </select>
          </div>
        </div>
      </Card>

      <div className="mb-4">
        <p className="text-sm text-gray-400">
          {filteredTeams.length} {filteredTeams.length === 1 ? 'team' : 'teams'} found
        </p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {filteredTeams.map((team) => {
          const memberCount = getTeamMembers(team.id).length;
          return (
            <TeamCard
              key={team.id}
              id={team.id}
              name={team.name}
              memberCount={memberCount}
              leagues={team.leagues}
              onClick={() => handleTeamClick(team.id)}
            />
          );
        })}
      </div>

      {filteredTeams.length === 0 && (
        <Card className="text-center py-12">
          <div className="text-gray-400">
            <svg
              className="mx-auto h-12 w-12 text-gray-600 mb-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              aria-hidden="true"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
              />
            </svg>
            <h3 className="text-lg font-medium text-white mb-2">
              {teams.length === 0 ? 'No teams yet' : 'No teams found'}
            </h3>
            <p className="text-sm mb-4">
              {teams.length === 0
                ? 'Create your first team to start racing together.'
                : 'Try adjusting your search or filters.'}
            </p>
            {teams.length === 0 && (
              <Button
                variant="primary"
                onClick={() => setShowCreateForm(true)}
              >
                Create Your First Team
              </Button>
            )}
          </div>
        </Card>
      )}
    </div>
  );
}