'use client';

import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import Card from '../ui/Card';
import ProfileHeader from '../profile/ProfileHeader';
import ProfileStats from './ProfileStats';
import CareerHighlights from './CareerHighlights';
import DriverRankings from './DriverRankings';
import PerformanceMetrics from './PerformanceMetrics';
import { useEffect, useState } from 'react';
import { getDriverStats, getLeagueRankings, getGetDriverTeamQuery, getAllDriverRankings } from '@/lib/di-container';
import { getPrimaryLeagueIdForDriver } from '@/lib/leagueMembership';
import type { GetDriverTeamQueryResultDTO } from '@gridpilot/racing/application/dto/TeamCommandAndQueryDTO';

interface DriverProfileProps {
  driver: DriverDTO;
  isOwnProfile?: boolean;
  onEditClick?: () => void;
}
 
export default function DriverProfile({ driver, isOwnProfile = false, onEditClick }: DriverProfileProps) {
  const driverStats = getDriverStats(driver.id);
  const primaryLeagueId = getPrimaryLeagueIdForDriver(driver.id);
  const leagueRank = primaryLeagueId
    ? getLeagueRankings(driver.id, primaryLeagueId)
    : { rank: 0, totalDrivers: 0, percentile: 0 };
  const allRankings = getAllDriverRankings();
  const [teamData, setTeamData] = useState<GetDriverTeamQueryResultDTO | null>(null);

  useEffect(() => {
    const load = async () => {
      const query = getGetDriverTeamQuery();
      const result = await query.execute({ driverId: driver.id });
      setTeamData(result);
    };
    void load();
  }, [driver.id]);

  const performanceStats = driverStats ? {
    winRate: (driverStats.wins / driverStats.totalRaces) * 100,
    podiumRate: (driverStats.podiums / driverStats.totalRaces) * 100,
    dnfRate: (driverStats.dnfs / driverStats.totalRaces) * 100,
    avgFinish: driverStats.avgFinish,
    consistency: driverStats.consistency,
    bestFinish: driverStats.bestFinish,
    worstFinish: driverStats.worstFinish,
  } : null;

  const rankings = driverStats ? [
    {
      type: 'overall' as const,
      name: 'Overall Ranking',
      rank: driverStats.overallRank,
      totalDrivers: allRankings.length,
      percentile: driverStats.percentile,
      rating: driverStats.rating,
    },
    {
      type: 'league' as const,
      name: 'Primary League',
      rank: leagueRank.rank,
      totalDrivers: leagueRank.totalDrivers,
      percentile: leagueRank.percentile,
      rating: driverStats.rating,
    },
  ] : [];

  return (
    <div className="space-y-6">
      <Card>
        <ProfileHeader
          driver={driver}
          rating={driverStats?.rating ?? null}
          rank={driverStats?.overallRank ?? null}
          isOwnProfile={isOwnProfile}
          onEditClick={isOwnProfile ? onEditClick : undefined}
          teamName={teamData?.team.name ?? null}
          teamTag={teamData?.team.tag ?? null}
        />
      </Card>

      {driver.bio && (
        <Card>
          <h3 className="text-lg font-semibold text-white mb-4">About</h3>
          <p className="text-gray-300 leading-relaxed">{driver.bio}</p>
        </Card>
      )}

      {driverStats && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            <Card>
              <h3 className="text-lg font-semibold text-white mb-4">Career Statistics</h3>
              <div className="grid grid-cols-2 gap-4">
                <StatCard label="Rating" value={driverStats.rating.toString()} color="text-primary-blue" />
                <StatCard label="Total Races" value={driverStats.totalRaces.toString()} color="text-white" />
                <StatCard label="Wins" value={driverStats.wins.toString()} color="text-green-400" />
                <StatCard label="Podiums" value={driverStats.podiums.toString()} color="text-warning-amber" />
              </div>
            </Card>

            {performanceStats && <PerformanceMetrics stats={performanceStats} />}
          </div>

          <DriverRankings rankings={rankings} />
        </div>
      )}

      {!driverStats && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <Card className="lg:col-span-3">
            <h3 className="text-lg font-semibold text-white mb-4">Career Statistics</h3>
            <p className="text-gray-400 text-sm">
              No statistics available yet. Compete in races to start building your record.
            </p>
          </Card>
        </div>
      )}

      <Card>
        <h3 className="text-lg font-semibold text-white mb-4">Performance by Class</h3>
        <ProfileStats stats={driverStats ? {
          totalRaces: driverStats.totalRaces,
          wins: driverStats.wins,
          podiums: driverStats.podiums,
          dnfs: driverStats.dnfs,
          avgFinish: driverStats.avgFinish,
          completionRate: ((driverStats.totalRaces - driverStats.dnfs) / driverStats.totalRaces) * 100
        } : undefined} />
      </Card>

      <CareerHighlights />

      <Card className="bg-charcoal-200/50 border-primary-blue/30">
        <div className="flex items-center gap-3 mb-3">
          <div className="text-2xl">🔒</div>
          <h3 className="text-lg font-semibold text-white">Private Information</h3>
        </div>
        <p className="text-gray-400 text-sm">
          Detailed race history, settings, and preferences are only visible to the driver.
        </p>
      </Card>

      <Card className="bg-charcoal-200/50 border-primary-blue/30">
        <div className="flex items-center gap-3 mb-3">
          <div className="text-2xl">📊</div>
          <h3 className="text-lg font-semibold text-white">Coming Soon</h3>
        </div>
        <p className="text-gray-400 text-sm">
          Per-car statistics, per-track performance, and head-to-head comparisons will be available in production.
        </p>
      </Card>
    </div>
  );
}

function StatCard({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <div className="text-center p-4 rounded bg-deep-graphite border border-charcoal-outline">
      <div className="text-sm text-gray-400 mb-1">{label}</div>
      <div className={`text-2xl font-bold ${color}`}>{value}</div>
    </div>
  );
}