'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ArrowLeft, Zap, Trophy, Users, Clock, Calendar } from 'lucide-react';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Breadcrumbs from '@/components/layout/Breadcrumbs';
import ResultsTable from '@/components/races/ResultsTable';
import ImportResultsForm from '@/components/races/ImportResultsForm';
import QuickPenaltyModal from '@/components/leagues/QuickPenaltyModal';
import { raceResultsService } from '@/lib/services/races/RaceResultsService';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
import type { RaceResultsDetailViewModel } from '@/lib/view-models';

export default function RaceResultsPage() {
  const router = useRouter();
  const params = useParams();
  const raceId = params.id as string;
  const currentDriverId = useEffectiveDriverId();

  const [raceData, setRaceData] = useState<RaceResultsDetailViewModel | null>(null);
  const [raceSOF, setRaceSOF] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [importing, setImporting] = useState(false);
  const [importSuccess, setImportSuccess] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [showQuickPenaltyModal, setShowQuickPenaltyModal] = useState(false);
  const [preSelectedDriver, setPreSelectedDriver] = useState<{ id: string; name: string } | undefined>(undefined);

  const loadData = async () => {
    try {
      const raceData = await raceResultsService.getResultsDetail(raceId, currentDriverId);
      setRaceData(raceData);
      setError(null);

      try {
        const sofData = await raceResultsService.getWithSOF(raceId);
        setRaceSOF(sofData.strengthOfField);
      } catch (sofErr) {
        console.error('Failed to load SOF:', sofErr);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load race data');
      setRaceData(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [raceId]);

  useEffect(() => {
    if (raceData?.league?.id && currentDriverId) {
      const checkAdmin = async () => {
        // For now, assume admin check - this might need to be updated based on API
        setIsAdmin(true); // TODO: Implement proper admin check via API
      };
      checkAdmin();
    }
  }, [raceData?.league?.id, currentDriverId]);

  const handleImportSuccess = async (importedResults: any[]) => {
    setImporting(true);
    setError(null);

    try {
      await raceResultsService.importRaceResults(raceId, {
        resultsFileContent: JSON.stringify(importedResults), // Assuming the API expects JSON string
      });

      setImportSuccess(true);
      await loadData();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to import results');
    } finally {
      setImporting(false);
    }
  };

  const handleImportError = (errorMessage: string) => {
    setError(errorMessage);
  };

  const handlePenaltyClick = (driver: { id: string; name: string }) => {
    setPreSelectedDriver(driver);
    setShowQuickPenaltyModal(true);
  };

  const handleCloseQuickPenaltyModal = () => {
    setShowQuickPenaltyModal(false);
    setPreSelectedDriver(undefined);
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <div className="text-center text-gray-400">Loading results...</div>
        </div>
      </div>
    );
  }

  if (error && !raceData) {
    return (
      <div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-6xl mx-auto">
          <Card className="text-center py-12">
            <div className="text-warning-amber mb-4">
              {error || 'Race not found'}
            </div>
            <Button
              variant="secondary"
              onClick={() => router.push('/races')}
            >
              Back to Races
            </Button>
          </Card>

          {showQuickPenaltyModal && (
            <QuickPenaltyModal
              {...({
                raceId,
                drivers: raceData?.drivers as any,
                onClose: handleCloseQuickPenaltyModal,
                preSelectedDriver: preSelectedDriver as any,
                adminId: currentDriverId,
                races: undefined,
              } as any)}
            />
          )}
        </div>
      </div>
    );
  }

  const hasResults = raceData?.results.length ?? 0 > 0;

  const breadcrumbItems = [
    { label: 'Races', href: '/races' },
    ...(raceData?.league ? [{ label: raceData.league.name, href: `/leagues/${raceData.league.id}` }] : []),
    ...(raceData?.race ? [{ label: raceData.race.track, href: `/races/${raceData.race.id}` }] : []),
    { label: 'Results' },
  ];

  return (
    <div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto space-y-6">
        <div className="flex items-center justify-between">
          <Breadcrumbs items={breadcrumbItems} className="text-sm text-gray-400" />
          <Button
            variant="secondary"
            onClick={() => router.back()}
            className="flex items-center gap-2 text-sm"
          >
            <ArrowLeft className="w-4 h-4" />
            Back
          </Button>
        </div>

        <div className="relative overflow-hidden rounded-2xl bg-gray-500/10 border border-gray-500/30 p-6 sm:p-8">
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl" />

          <div className="relative z-10">
            <div className="flex items-center gap-3 mb-4">
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-performance-green/10 border border-performance-green/30">
                <Trophy className="w-4 h-4 text-performance-green" />
                <span className="text-sm font-semibold text-performance-green">
                  Final Results
                </span>
              </div>
              {raceSOF && (
                <span className="flex items-center gap-1.5 text-warning-amber text-sm">
                  <Zap className="w-4 h-4" />
                  SOF {raceSOF}
                </span>
              )}
            </div>

            <h1 className="text-2xl sm:text-3xl font-bold text-white mb-2">
              {raceData?.race?.track ?? 'Race'} Results
            </h1>

            <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-gray-400">
              {raceData?.race && (
                <>
                  <span className="flex items-center gap-2">
                    <Calendar className="w-4 h-4" />
                    {new Date(raceData.race.scheduledAt).toLocaleDateString('en-US', {
                      weekday: 'short',
                      month: 'short',
                      day: 'numeric',
                    })}
                  </span>
                  <span className="flex items-center gap-2">
                    <Users className="w-4 h-4" />
                    {raceData.stats.totalDrivers} drivers classified
                  </span>
                </>
              )}
              {raceData?.league && <span className="text-primary-blue">{raceData.league.name}</span>}
            </div>
          </div>
        </div>

        {importSuccess && (
          <div className="p-4 bg-performance-green/10 border border-performance-green/30 rounded-lg text-performance-green">
            <strong>Success!</strong> Results imported and standings updated.
          </div>
        )}

        {error && (
          <div className="p-4 bg-warning-amber/10 border border-warning-amber/30 rounded-lg text-warning-amber">
            <strong>Error:</strong> {error}
          </div>
        )}

        <Card>
          {hasResults && raceData ? (
            <ResultsTable
              results={raceData.resultsByPosition}
              drivers={raceData.drivers}
              pointsSystem={raceData.pointsSystem ?? {}}
              fastestLapTime={raceData.fastestLapTime ?? 0}
              penalties={raceData.penalties}
              currentDriverId={raceData.currentDriverId ?? ''}
              isAdmin={isAdmin}
              onPenaltyClick={handlePenaltyClick}
            />
          ) : (
            <>
              <h2 className="text-xl font-semibold text-white mb-6">Import Results</h2>
              <p className="text-gray-400 text-sm mb-6">
                No results imported. Upload CSV to test the standings system.
              </p>
              {importing ? (
                <div className="text-center py-8 text-gray-400">
                  Importing results and updating standings...
                </div>
              ) : (
                <ImportResultsForm
                  raceId={raceId}
                  onSuccess={handleImportSuccess}
                  onError={handleImportError}
                />
              )}
            </>
          )}
        </Card>
      </div>
    </div>
  );
}