'use client';

import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { useServices } from '@/lib/services/ServiceProvider';
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';
import Link from 'next/link';
import { useEffect, useState } from 'react';

interface LeagueWithRole {
  league: LeagueSummaryViewModel;
  membership: LeagueMembership;
}

export default function ManageLeaguesPage() {
  const [ownedLeagues, setOwnedLeagues] = useState<LeagueWithRole[]>([]);
  const [memberLeagues, setMemberLeagues] = useState<LeagueWithRole[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const effectiveDriverId = useEffectiveDriverId();
  const { leagueService, leagueMembershipService } = useServices();

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      setLoading(true);
      try {
        const leagues = await leagueService.getAllLeagues();

        const memberships = await Promise.all(
          leagues.map(async (league) => {
            await leagueMembershipService.fetchLeagueMemberships(league.id);
            const membership = leagueMembershipService.getMembership(league.id, effectiveDriverId);
            return { league, membership };
          }),
        );

        if (cancelled) {
          return;
        }

        const owned: LeagueWithRole[] = [];
        const member: LeagueWithRole[] = [];

        for (const entry of memberships) {
          if (!entry.membership || entry.membership.status !== 'active') {
            continue;
          }

          if (entry.membership.role === 'owner') {
            owned.push(entry as LeagueWithRole);
          } else {
            member.push(entry as LeagueWithRole);
          }
        }

        setOwnedLeagues(owned);
        setMemberLeagues(member);
        setError(null);
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : 'Failed to load leagues');
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void load();

    return () => {
      cancelled = true;
    };
  }, [effectiveDriverId, leagueService, leagueMembershipService]);

  if (loading) {
    return (
      <div className="max-w-6xl mx-auto">
        <div className="text-center text-gray-400">Loading your leagues...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-6xl mx-auto">
        <Card>
          <div className="text-center py-8 text-red-400">{error}</div>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-8">
      <div>
        <h1 className="text-3xl font-bold text-white mb-2">Manage leagues</h1>
        <p className="text-gray-400 text-sm">
          View leagues you own and participate in, and jump into league admin tools.
        </p>
      </div>

      <Card>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-white">Leagues you own</h2>
          {ownedLeagues.length > 0 && (
            <span className="text-xs text-gray-400">
              {ownedLeagues.length} {ownedLeagues.length === 1 ? 'league' : 'leagues'}
            </span>
          )}
        </div>

        {ownedLeagues.length === 0 ? (
          <p className="text-sm text-gray-400">
            You don't own any leagues yet in this session.
          </p>
        ) : (
          <div className="space-y-3">
            {ownedLeagues.map(({ league }) => (
              <div
                key={league.id}
                className="flex items-center justify-between p-4 rounded-lg bg-deep-graphite border border-charcoal-outline"
              >
                <div>
                  <h3 className="text-white font-medium">{league.name}</h3>
                  <p className="text-xs text-gray-400 mt-1 line-clamp-2">
                    {league.description}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <Link
                    href={`/leagues/${league.id}`}
                    className="text-sm text-gray-300 hover:text-white underline-offset-2 hover:underline"
                  >
                    View
                  </Link>
                  <Link href={`/leagues/${league.id}?tab=admin`}>
                    <Button variant="primary" className="text-xs px-3 py-1.5">
                      Manage
                    </Button>
                  </Link>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold text-white">Leagues you're in</h2>
          {memberLeagues.length > 0 && (
            <span className="text-xs text-gray-400">
              {memberLeagues.length} {memberLeagues.length === 1 ? 'league' : 'leagues'}
            </span>
          )}
        </div>

        {memberLeagues.length === 0 ? (
          <p className="text-sm text-gray-400">
            You're not a member of any other leagues yet.
          </p>
        ) : (
          <div className="space-y-3">
            {memberLeagues.map(({ league, membership }) => (
              <div
                key={league.id}
                className="flex items-center justify-between p-4 rounded-lg bg-deep-graphite border border-charcoal-outline"
              >
                <div>
                  <h3 className="text-white font-medium">{league.name}</h3>
                  <p className="text-xs text-gray-400 mt-1 line-clamp-2">
                    {league.description}
                  </p>
                  <p className="text-xs text-gray-500 mt-1">
                    Your role:{' '}
                    {membership.role.charAt(0).toUpperCase() + membership.role.slice(1)}
                  </p>
                </div>
                <Link
                  href={`/leagues/${league.id}`}
                  className="text-sm text-gray-300 hover:text-white underline-offset-2 hover:underline"
                >
                  View league
                </Link>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}