'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { LogOut, Star } from 'lucide-react';
import { useAuth } from '@/lib/auth/AuthContext';
import {
  getDriverStats,
  getLeagueRankings,
  getAllDriverRankings,
  getDriverRepository,
  getImageService,
} from '@/lib/di-container';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappers';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';

export default function UserPill() {
  const { session, login } = useAuth();
  const [driver, setDriver] = useState<DriverDTO | null>(null);
  const [isMenuOpen, setIsMenuOpen] = useState(false);

  const user = session?.user as
    | {
        id: string;
        displayName?: string;
        primaryDriverId?: string | null;
        avatarUrl?: string | null;
      }
    | undefined;

  const primaryDriverId = useEffectiveDriverId();

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

    async function loadDriver() {
      if (!primaryDriverId) {
        if (!cancelled) {
          setDriver(null);
        }
        return;
      }

      const repo = getDriverRepository();
      const entity = await repo.findById(primaryDriverId);
      if (!cancelled) {
        setDriver(EntityMappers.toDriverDTO(entity));
      }
    }

    loadDriver();

    return () => {
      cancelled = true;
    };
  }, [primaryDriverId]);

  const data = useMemo(() => {
    if (!session?.user || !primaryDriverId || !driver) {
      return null;
    }

    const driverStats = getDriverStats(primaryDriverId);
    const allRankings = getAllDriverRankings();

    let rating: number | null = driverStats?.rating ?? null;
    let rank: number | null = null;
    let totalDrivers: number | null = null;

    if (driverStats) {
      totalDrivers = allRankings.length || null;

      if (typeof driverStats.overallRank === 'number' && driverStats.overallRank > 0) {
        rank = driverStats.overallRank;
      } else {
        const indexInGlobal = allRankings.findIndex(
          (stat) => stat.driverId === driverStats.driverId,
        );
        if (indexInGlobal !== -1) {
          rank = indexInGlobal + 1;
        }
      }

      if (rating === null) {
        const globalEntry = allRankings.find(
          (stat) => stat.driverId === driverStats.driverId,
        );
        if (globalEntry) {
          rating = globalEntry.rating;
        }
      }
    }

    const avatarSrc = getImageService().getDriverAvatar(primaryDriverId);

    return {
      driver,
      avatarSrc,
      rating,
      rank,
    };
  }, [session, driver, primaryDriverId]);

  if (!session) {
    const loginHref = '/auth/iracing/start?returnTo=/dashboard';

    return (
      <div className="flex items-center">
        <Link
          href={loginHref}
          className="inline-flex items-center gap-2 rounded-full bg-primary-blue px-4 py-1.5 text-xs font-semibold text-white shadow-[0_0_12px_rgba(25,140,255,0.5)] hover:bg-primary-blue/90 hover:shadow-[0_0_18px_rgba(25,140,255,0.8)] transition-all"
        >
          <span className="inline-flex h-4 w-4 items-center justify-center rounded-full bg-white/10">
            <Star className="h-3 w-3 text-amber-300" />
          </span>
          <span>Authenticate with iRacing</span>
        </Link>
      </div>
    );
  }

  if (!data) {
    return null;
  }

  return (
    <div className="relative inline-flex items-center">
      <DriverSummaryPill
        driver={data.driver}
        rating={data.rating}
        rank={data.rank}
        avatarSrc={data.avatarSrc}
        onClick={() => setIsMenuOpen((open) => !open)}
      />

      {isMenuOpen && (
        <div className="absolute right-0 top-full mt-2 w-48 rounded-lg bg-deep-graphite border border-charcoal-outline shadow-lg z-50">
          <div className="py-1 text-sm text-gray-200">
            <Link
              href="/profile"
              className="block px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
              onClick={() => setIsMenuOpen(false)}
            >
              Profile
            </Link>
            <Link
              href="/profile/leagues"
              className="block px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
              onClick={() => setIsMenuOpen(false)}
            >
              Manage leagues
            </Link>
          </div>
          <div className="border-t border-charcoal-outline">
            <form action="/auth/logout" method="POST">
              <button
                type="submit"
                className="flex w-full items-center justify-between px-3 py-2 text-sm text-gray-400 hover:text-red-400 hover:bg-red-500/10 transition-colors"
              >
                <span>Logout</span>
                <LogOut className="h-4 w-4" />
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}