'use client';

import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
import { useDriverProfilePageData } from "@/lib/hooks/driver/useDriverProfilePageData";
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
import { useParams, useRouter } from 'next/navigation';
import { useState } from 'react';

interface DriverProfileData {
  driverProfile: any;
  teamMemberships: Array<{
    team: { id: string; name: string };
    role: string;
    joinedAt: Date;
  }>;
}

export default function DriverProfilePage() {
  const router = useRouter();
  const params = useParams();
  const driverId = params.id as string;
  const currentDriverId = useEffectiveDriverId() || '';
  
  // UI State
  const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
  const [friendRequestSent, setFriendRequestSent] = useState(false);
  
  // Fetch data using domain hook
  const { data: queries, isLoading, error, refetch } = useDriverProfilePageData(driverId);
  
  // Transform data for template
  const data: DriverProfileData | undefined = queries?.driverProfile && queries?.teamMemberships
    ? {
        driverProfile: queries.driverProfile,
        teamMemberships: queries.teamMemberships,
      }
    : undefined;
  
  // Actions
  const handleAddFriend = () => {
    setFriendRequestSent(true);
  };

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

  return (
    <StatefulPageWrapper
      data={data}
      isLoading={isLoading}
      error={error as Error | null}
      retry={refetch}
      Template={({ data }) => {
        if (!data) return null;
        return (
          <DriverProfileTemplate
            driverProfile={data.driverProfile}
            allTeamMemberships={data.teamMemberships}
            isLoading={false}
            error={null}
            onBackClick={handleBackClick}
            onAddFriend={handleAddFriend}
            friendRequestSent={friendRequestSent}
            activeTab={activeTab}
            setActiveTab={setActiveTab}
          />
        );
      }}
      loading={{ variant: 'skeleton', message: 'Loading driver profile...' }}
      errorConfig={{ variant: 'full-screen' }}
      empty={{
        icon: require('lucide-react').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 }
      }}
    />
  );
}