'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { LogOut, Settings, Star, Paintbrush, Building2, BarChart3, Megaphone, CreditCard, Handshake } 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 '@core/racing/application/dto/DriverDTO';
import { EntityMappers } from '@core/racing/application/mappers/EntityMappers';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';

// Hook to detect sponsor mode
function useSponsorMode(): boolean {
  const [isSponsor, setIsSponsor] = useState(false);
  useEffect(() => {
    const cookie = document.cookie
      .split('; ')
      .find(row => row.startsWith('gridpilot_demo_mode='));
    if (cookie) {
      const value = cookie.split('=')[1];
      setIsSponsor(value === 'sponsor');
    }
  }, []);
  return isSponsor;
}

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

  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]);

  // Sponsor mode UI - check BEFORE session check so sponsors without auth still see sponsor UI
  if (isSponsorMode) {
    return (
      <div className="relative inline-flex items-center">
        <button
          onClick={() => setIsMenuOpen((open) => !open)}
          className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-performance-green/10 border border-performance-green/30 hover:bg-performance-green/20 transition-colors"
        >
          <div className="w-8 h-8 rounded-full bg-performance-green/20 flex items-center justify-center">
            <Building2 className="w-4 h-4 text-performance-green" />
          </div>
          <span className="text-sm font-semibold text-performance-green">Sponsor</span>
        </button>

        {isMenuOpen && (
          <div className="absolute right-0 top-full mt-2 w-56 rounded-lg bg-deep-graphite border border-charcoal-outline shadow-lg z-50">
            <div className="p-3 border-b border-charcoal-outline">
              <p className="text-xs text-gray-500 uppercase tracking-wide">Demo Sponsor Account</p>
              <p className="text-sm font-semibold text-white mt-1">Acme Racing Co.</p>
            </div>
            <div className="py-1 text-sm text-gray-200">
              <Link
                href="/sponsor"
                className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
                onClick={() => setIsMenuOpen(false)}
              >
                <BarChart3 className="h-4 w-4 text-performance-green" />
                <span>Dashboard</span>
              </Link>
              <Link
                href="/sponsor/campaigns"
                className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
                onClick={() => setIsMenuOpen(false)}
              >
                <Megaphone className="h-4 w-4 text-primary-blue" />
                <span>My Sponsorships</span>
              </Link>
              <Link
                href="/sponsor/billing"
                className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
                onClick={() => setIsMenuOpen(false)}
              >
                <CreditCard className="h-4 w-4 text-warning-amber" />
                <span>Billing</span>
              </Link>
              <Link
                href="/sponsor/settings"
                className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
                onClick={() => setIsMenuOpen(false)}
              >
                <Settings className="h-4 w-4" />
                <span>Settings</span>
              </Link>
            </div>
            <div className="border-t border-charcoal-outline">
              <button
                type="button"
                onClick={() => {
                  document.cookie = 'gridpilot_demo_mode=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
                  window.location.reload();
                }}
                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>Exit Sponsor Mode</span>
                <LogOut className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}
      </div>
    );
  }

  if (!session) {
    return (
      <div className="flex items-center gap-2">
        <Link
          href="/auth/login"
          className="inline-flex items-center gap-2 rounded-full bg-iron-gray border border-charcoal-outline px-4 py-1.5 text-xs font-medium text-gray-300 hover:text-white hover:border-gray-500 transition-all"
        >
          Sign In
        </Link>
        <Link
          href="/auth/signup"
          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"
        >
          Get Started
        </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>
            <Link
              href="/profile/liveries"
              className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
              onClick={() => setIsMenuOpen(false)}
            >
              <Paintbrush className="h-4 w-4" />
              <span>Liveries</span>
            </Link>
            <Link
              href="/profile/sponsorship-requests"
              className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
              onClick={() => setIsMenuOpen(false)}
            >
              <Handshake className="h-4 w-4 text-performance-green" />
              <span>Sponsorship Requests</span>
            </Link>
            <Link
              href="/profile/settings"
              className="flex items-center gap-2 px-3 py-2 hover:bg-charcoal-outline/80 transition-colors"
              onClick={() => setIsMenuOpen(false)}
            >
              <Settings className="h-4 w-4" />
              <span>Settings</span>
            </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>
  );
}