'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
import { DriverProfileViewModelBuilder } from '@/lib/builders/view-models/DriverProfileViewModelBuilder';
import type { GetDriverProfileOutputDTO } from '@/lib/types/generated/GetDriverProfileOutputDTO';

interface DriverProfilePageClientProps {
  pageDto: GetDriverProfileOutputDTO | null;
  error?: string;
  empty?: {
    title: string;
    description: string;
  };
}

/**
 * DriverProfilePageClient
 *
 * Client component that:
 * 1. Handles UI state (tabs, friend requests)
 * 2. Uses ViewModelBuilder to transform DTO
 * 3. Passes ViewModel to Template
 */
export function DriverProfilePageClient({ pageDto, error, empty }: DriverProfilePageClientProps) {
  const router = useRouter();
  
  // UI State
  const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
  const [friendRequestSent, setFriendRequestSent] = useState(false);

  // Event handlers
  const handleAddFriend = () => {
    setFriendRequestSent(true);
  };

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

  // Handle error/empty states
  if (error) {
    return (
      <div className="max-w-6xl mx-auto px-4 py-12 text-center">
        <div className="text-red-400 mb-4">Error loading driver profile</div>
        <p className="text-gray-400">Please try again later</p>
      </div>
    );
  }

  if (!pageDto || !pageDto.currentDriver) {
    if (empty) {
      return (
        <div className="max-w-4xl mx-auto px-4">
          <div className="text-center py-12">
            <h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
            <p className="text-gray-400">{empty.description}</p>
          </div>
        </div>
      );
    }
    return null;
  }

  // Transform DTO to ViewModel using Builder
  const viewModel = DriverProfileViewModelBuilder.build(pageDto);

  // Transform teamMemberships for template
  const allTeamMemberships = pageDto.teamMemberships.map(membership => ({
    team: {
      id: membership.teamId,
      name: membership.teamName,
    },
    role: membership.role,
    joinedAt: new Date(membership.joinedAt),
  }));

  return (
    <DriverProfileTemplate
      driverProfile={viewModel}
      allTeamMemberships={allTeamMemberships}
      isLoading={false}
      error={null}
      onBackClick={handleBackClick}
      onAddFriend={handleAddFriend}
      friendRequestSent={friendRequestSent}
      activeTab={activeTab}
      setActiveTab={setActiveTab}
    />
  );
}