'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
import { useServices } from '@/lib/services/ServiceProvider';
import SponsorInsightsCard, { useSponsorMode, MetricBuilders, SlotTemplates } from '@/components/sponsors/SponsorInsightsCard';

// Shared state components
import { useDataFetching } from '@/components/shared/hooks/useDataFetching';
import { StateContainer } from '@/components/shared/state/StateContainer';
import { Car } from 'lucide-react';

interface Team {
  id: string;
  name: string;
}

interface TeamMembershipInfo {
  team: Team;
  role: string;
  joinedAt: Date;
}

export function DriverProfileInteractive() {
  const router = useRouter();
  const params = useParams();
  const driverId = params.id as string;
  const { driverService, teamService } = useServices();

  const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
  const [friendRequestSent, setFriendRequestSent] = useState(false);

  const isSponsorMode = useSponsorMode();

  // Fetch driver profile
  const { data: driverProfile, isLoading, error, retry } = useDataFetching({
    queryKey: ['driverProfile', driverId],
    queryFn: () => driverService.getDriverProfile(driverId),
  });

  // Fetch team memberships
  const { data: allTeamMemberships } = useDataFetching({
    queryKey: ['driverTeamMemberships', driverId],
    queryFn: async () => {
      if (!driverProfile?.currentDriver) return [];
      
      const allTeams = await teamService.getAllTeams();
      const memberships: TeamMembershipInfo[] = [];

      for (const team of allTeams) {
        const teamMembers = await teamService.getTeamMembers(team.id, driverId, '');
        const membership = teamMembers.find(member => member.driverId === driverId);
        if (membership) {
          memberships.push({
            team: {
              id: team.id,
              name: team.name,
            } as Team,
            role: membership.role,
            joinedAt: new Date(membership.joinedAt),
          });
        }
      }
      return memberships;
    },
    enabled: !!driverProfile?.currentDriver,
  });

  const handleAddFriend = () => {
    setFriendRequestSent(true);
  };

  const handleBackClick = () => {
    router.push('/drivers');
  };

  // Build sponsor insights for driver
  const friendsCount = driverProfile?.socialSummary?.friends?.length ?? 0;
  const stats = driverProfile?.stats || null;
  const driver = driverProfile?.currentDriver;

  const driverMetrics = [
    MetricBuilders.rating(stats?.rating ?? 0, 'Driver Rating'),
    MetricBuilders.views((friendsCount * 8) + 50),
    MetricBuilders.engagement(stats?.consistency ?? 75),
    MetricBuilders.reach((friendsCount * 12) + 100),
  ];

  const sponsorInsights = isSponsorMode && driver ? (
    <SponsorInsightsCard
      entityType="driver"
      entityId={driver.id}
      entityName={driver.name}
      tier="standard"
      metrics={driverMetrics}
      slots={SlotTemplates.driver(true, 200)}
      trustScore={88}
      monthlyActivity={stats?.consistency ?? 75}
    />
  ) : null;

  return (
    <StateContainer
      data={driverProfile}
      isLoading={isLoading}
      error={error}
      retry={retry}
      config={{
        loading: { variant: 'skeleton', message: 'Loading driver profile...' },
        error: { variant: 'full-screen' },
        empty: {
          icon: Car,
          title: 'Driver not found',
          description: 'The driver profile may not exist or you may not have access',
          action: { label: 'Back to Drivers', onClick: handleBackClick }
        }
      }}
    >
      {(profileData) => (
        <DriverProfileTemplate
          driverProfile={profileData}
          allTeamMemberships={allTeamMemberships || []}
          isLoading={false}
          error={null}
          onBackClick={handleBackClick}
          onAddFriend={handleAddFriend}
          friendRequestSent={friendRequestSent}
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          isSponsorMode={isSponsorMode}
          sponsorInsights={sponsorInsights}
        />
      )}
    </StateContainer>
  );
 }