'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
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 TeamLadderRow from '@/components/teams/TeamLadderRow';
import { getGetAllTeamsQuery, getGetTeamMembersQuery, getDriverStats } from '@/lib/di-container';
import type { Team } from '@gridpilot/racing';

type TeamLadderItem = {
  team: Team;
  memberCount: number;
  rating: number | null;
  totalWins: number;
  totalRaces: number;
};

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');
  const [memberCounts, setMemberCounts] = useState<Record<string, number>>({});
  const [teamStats, setTeamStats] = useState<Record<string, Omit<TeamLadderItem, 'team' | 'memberCount'>>>({});

  const loadTeams = async () => {
    const allTeamsQuery = getGetAllTeamsQuery();
    const teamMembersQuery = getGetTeamMembersQuery();

    const allTeams = await allTeamsQuery.execute();
    setTeams(allTeams);

    const counts: Record<string, number> = {};
    const stats: Record<string, Omit<TeamLadderItem, 'team' | 'memberCount'>> = {};

    await Promise.all(
      allTeams.map(async (team) => {
        const memberships = await teamMembersQuery.execute({ teamId: team.id });
        counts[team.id] = memberships.length;

        const memberDriverIds = memberships.map((m) => m.driverId);

        let ratingSum = 0;
        let ratingCount = 0;
        let totalWins = 0;
        let totalRaces = 0;

        for (const driverId of memberDriverIds) {
          const statsForDriver = getDriverStats(driverId);
          if (!statsForDriver) continue;

          if (typeof statsForDriver.rating === 'number') {
            ratingSum += statsForDriver.rating;
            ratingCount += 1;
          }

          totalWins += statsForDriver.wins ?? 0;
          totalRaces += statsForDriver.totalRaces ?? 0;
        }

        const averageRating =
          ratingCount > 0 ? ratingSum / ratingCount : null;

        stats[team.id] = {
          rating: averageRating,
          totalWins,
          totalRaces,
        };
      }),
    );

    setMemberCounts(counts);
    setTeamStats(stats);
  };

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

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

  const filteredTeams = teams.filter((team) => {
    const memberCount = memberCounts[team.id] ?? 0;

    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 sortedTeams = [...filteredTeams].sort((a, b) => {
    const statsA = teamStats[a.id];
    const statsB = teamStats[b.id];

    const ratingA = statsA?.rating ?? null;
    const ratingB = statsB?.rating ?? null;

    const ratingValA = ratingA === null ? Number.NEGATIVE_INFINITY : ratingA;
    const ratingValB = ratingB === null ? Number.NEGATIVE_INFINITY : ratingB;

    if (ratingValA !== ratingValB) {
      return ratingValB - ratingValA;
    }

    const winsA = statsA?.totalWins ?? 0;
    const winsB = statsB?.totalWins ?? 0;

    if (winsA !== winsB) {
      return winsB - winsA;
    }

    return a.name.localeCompare(b.name);
  });

  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 flex items-center justify-between">
        <p className="text-sm text-gray-400">
          {sortedTeams.length} {sortedTeams.length === 1 ? 'team' : 'teams'} found
        </p>
      </div>

      {sortedTeams.length > 0 && (
        <Card>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-charcoal-outline">
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">#</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">Team</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">Rating</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">Wins</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">Races</th>
                  <th className="text-left py-3 px-4 font-semibold text-gray-400">Members</th>
                </tr>
              </thead>
              <tbody>
                {sortedTeams.map((team, index) => {
                  const memberCount = memberCounts[team.id] ?? 0;
                  const statsForTeam = teamStats[team.id];

                  const rating = statsForTeam?.rating ?? null;
                  const totalWins = statsForTeam?.totalWins ?? 0;
                  const totalRaces = statsForTeam?.totalRaces ?? 0;
                  const rank = index + 1;

                  return (
                    <TeamLadderRow
                      key={team.id}
                      rank={rank}
                      teamId={team.id}
                      teamName={team.name}
                      memberCount={memberCount}
                      teamRating={rating}
                      totalWins={totalWins}
                      totalRaces={totalRaces}
                    />
                  );
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}

      {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>
  );
}