'use client';

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

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 [driverProfile, setDriverProfile] = useState<DriverProfileViewModel | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
  const [allTeamMemberships, setAllTeamMemberships] = useState<TeamMembershipInfo[]>([]);
  const [friendRequestSent, setFriendRequestSent] = useState(false);

  const isSponsorMode = useSponsorMode();

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

  const loadDriver = async () => {
    try {
      // Get driver profile
      const profileViewModel = await driverService.getDriverProfile(driverId);

      if (!profileViewModel.currentDriver) {
        setError('Driver not found');
        setLoading(false);
        return;
      }

      setDriverProfile(profileViewModel);

      // Load team memberships - get all teams and check memberships
      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),
          });
        }
      }
      setAllTeamMemberships(memberships);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load driver');
    } finally {
      setLoading(false);
    }
  };

  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;

  if (!driverProfile) {
    return null;
  }

  return (
    <DriverProfileTemplate
      driverProfile={driverProfile}
      allTeamMemberships={allTeamMemberships}
      isLoading={loading}
      error={error}
      onBackClick={handleBackClick}
      onAddFriend={handleAddFriend}
      friendRequestSent={friendRequestSent}
      activeTab={activeTab}
      setActiveTab={setActiveTab}
      isSponsorMode={isSponsorMode}
      sponsorInsights={sponsorInsights}
    />
  );
}