'use client';

import { useState, useEffect } from 'react';
import { getDriverRepository } from '@/lib/di-container';
import { Driver, EntityMappers, type DriverDTO } from '@gridpilot/racing';
import CreateDriverForm from '@/components/drivers/CreateDriverForm';
import Card from '@/components/ui/Card';
import DriverProfile from '@/components/drivers/DriverProfile';
import ProfileRaceHistory from '@/components/drivers/ProfileRaceHistory';
import ProfileSettings from '@/components/drivers/ProfileSettings';
import { useEffectiveDriverId } from '@/lib/currentDriver';

export default function ProfilePage() {
  const [driver, setDriver] = useState<DriverDTO | null>(null);
  const [loading, setLoading] = useState(true);
 
  const effectiveDriverId = useEffectiveDriverId();

  useEffect(() => {
    const loadDriver = async () => {
      const driverRepo = getDriverRepository();
      const currentDriverId = effectiveDriverId;
      const currentDriver = await driverRepo.findById(currentDriverId);
      const driverData = EntityMappers.toDriverDTO(currentDriver);
      setDriver(driverData);
      setLoading(false);
    };
    void loadDriver();
  }, [effectiveDriverId]);

  const handleSaveSettings = async (updates: Partial<DriverDTO>) => {
    if (!driver) return;
    
    const driverRepo = getDriverRepository();
    const drivers = await driverRepo.findAll();
    const currentDriver = drivers[0];
    
    if (currentDriver) {
      const updatedDriver: Driver = currentDriver.update({
        bio: updates.bio ?? currentDriver.bio,
        country: updates.country ?? currentDriver.country,
      });
      const persistedDriver = await driverRepo.update(updatedDriver);
      
      const updatedDto = EntityMappers.toDriverDTO(persistedDriver);
      setDriver(updatedDto);
    }
  };

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

  if (!driver) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-white mb-2">Driver Profile</h1>
          <p className="text-gray-400">
            Create your GridPilot profile to get started
          </p>
        </div>

        <Card className="max-w-2xl mx-auto">
          <div className="mb-6">
            <h2 className="text-xl font-semibold text-white mb-2">Create Your Profile</h2>
            <p className="text-gray-400 text-sm">
              Create your driver profile. Alpha data resets on reload, so test freely.
            </p>
          </div>
          <CreateDriverForm />
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      <DriverProfile driver={driver} isOwnProfile />
      <Card>
        <ProfileSettings driver={driver} onSave={handleSaveSettings} />
      </Card>
      <Card>
        <ProfileRaceHistory />
      </Card>
    </div>
  );
}