'use client';

import React, { useEffect, useState } from 'react';
import { getClients, getTasks } from '@/helpers/axios_helper';
import { Client, Task } from '@/types/types';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { motion, AnimatePresence } from 'framer-motion';
import { useSelectedClient } from '@/context/SelectedClientContext';
import { useRouter } from 'next/navigation';

// Liste verticale des clients à gauche
const ClientList = ({ clients, selectedClientId, onSelect }) => {
  const router = useRouter();
  
  return (
    <div className="w-1/4 min-w-[280px] bg-white dark:bg-gray-900 h-full overflow-y-auto border-r border-gray-200 dark:border-gray-800">
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Liste des Clients</h3>
          <button
            onClick={() => router.push('/clients/new')}
            className="p-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            title="Nouveau client"
          >
            +
          </button>
        </div>
        <p className="text-sm text-gray-600 dark:text-gray-400">{clients.length} client(s)</p>
      </div>
    <div className="divide-y divide-gray-200 dark:divide-gray-700">
      {clients.map(client => (
        <div
          key={client.id}
          onClick={() => onSelect(client)}
          className={`p-4 cursor-pointer transition-all duration-200 hover:bg-blue-50 dark:hover:bg-gray-800 ${
            selectedClientId === client.id 
              ? 'bg-blue-100 dark:bg-blue-900 border-r-2 border-blue-500' 
              : 'hover:bg-gray-50 dark:hover:bg-gray-800'
          }`}
        >
          <div className="font-medium text-gray-900 dark:text-gray-100">
            {client.firstName} {client.lastName}
          </div>
          <div className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            {client.email || 'Aucun email'}
          </div>
          <div className="text-xs text-gray-500 dark:text-gray-500 mt-1">
            N° AVS: {client.socialSecurityNumber || 'Non renseigné'}
          </div>
        </div>
      ))}
    </div>
  </div>
  );
};

// Onglet Documents (exemple simple)
const ClientDocumentsTab = ({ client }: { client: Client }) => {
  // Simuler des documents pour l'exemple
  const documents = [
    { id: 1, name: 'Contrat_2024.pdf', date: '2024-06-01', size: '2.4 MB' },
    { id: 2, name: 'Facture_001.pdf', date: '2024-06-10', size: '150 KB' },
  ];
  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center mb-4">
        <h4 className="text-xl font-bold text-gray-900 dark:text-gray-100">Documents du client</h4>
        <button className="px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-100 text-sm font-medium transition-colors">
          Ajouter un document
        </button>
      </div>
      <div className="rounded-xl border border-gray-100 dark:border-gray-800 overflow-hidden bg-white dark:bg-gray-900">
        <ul className="divide-y divide-gray-100 dark:divide-gray-800">
          {documents.map(doc => (
            <li key={doc.id} className="flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
              <div className="flex items-center space-x-3">
                <div className="p-2 bg-red-50 text-red-600 dark:bg-red-900/20 dark:text-red-400 rounded-lg">
                  📄
                </div>
                <div>
                  <p className="font-medium text-gray-900 dark:text-gray-100">{doc.name}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">{doc.date} • {doc.size}</p>
                </div>
              </div>
              <button className="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/30 rounded-lg transition-colors">
                Voir
              </button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

const ClientTasksTab = ({ client }: { client: Client }) => {
  const [tasks, setTasks] = useState<Task[]>([]);
  useEffect(() => {
    getTasks().then(allTasks => {
      setTasks(allTasks.filter((t: any) => t.clientId === client.id));
    });
  }, [client.id]);
  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center mb-4">
        <h4 className="text-xl font-bold text-gray-900 dark:text-gray-100">Tâches du client</h4>
        <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition-colors">
          Nouvelle tâche
        </button>
      </div>
      
      {tasks.length === 0 ? (
        <div className="p-8 border-2 border-dashed border-gray-200 dark:border-gray-800 rounded-xl flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-900/50">
          <span className="text-4xl mb-3 block">📋</span>
          <p className="text-gray-500 dark:text-gray-400 font-medium">Aucune tâche pour ce client.</p>
        </div>
      ) : (
        <ul className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {tasks.map((task: any) => (
            <li key={task.id} className="flex flex-col p-4 border border-gray-100 dark:border-gray-800 rounded-xl bg-white dark:bg-gray-900 shadow-sm hover:shadow-md transition-shadow">
              <div className="flex justify-between items-start mb-2">
                <span className="font-semibold text-gray-900 dark:text-gray-100">{task.title}</span>
                <span className="px-2 py-1 bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 rounded-full text-xs font-semibold uppercase tracking-wide">
                  {task.status || 'PENDING'}
                </span>
              </div>
              {task.description && <p className="text-sm text-gray-500 dark:text-gray-400 line-clamp-2">{task.description}</p>}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

// Composant principal d'onglets pour un client sélectionné
const ClientTabsView = ({ client, onBack }: { client: Client, onBack: () => void }) => (
  <motion.div
    key={client.id}
    initial={{ opacity: 0, x: 40 }}
    animate={{ opacity: 1, x: 0 }}
    exit={{ opacity: 0, x: -40 }}
    transition={{ duration: 0.3 }}
    className="flex-1 p-8 bg-white dark:bg-gray-900"
  >
    <div className="flex items-center justify-between mb-6">
      <div>
        <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
          {client.firstName} {client.lastName}
        </h2>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Client #{client.id} • {client.status || 'Statut non défini'}
        </p>
      </div>
      <button
        onClick={onBack}
        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
      >
        ← Retour à la liste
      </button>
    </div>
    
    <Tabs defaultValue="infos" className="w-full">
      <TabsList className="mb-6 bg-gray-100 dark:bg-gray-800">
        <TabsTrigger value="infos" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-700">
          Informations
        </TabsTrigger>
        <TabsTrigger value="documents" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-700">
          Documents
        </TabsTrigger>
        <TabsTrigger value="taches" className="data-[state=active]:bg-white dark:data-[state=active]:bg-gray-700">
          Tâches
        </TabsTrigger>
      </TabsList>
      
      <TabsContent value="infos" className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="bg-gray-50 dark:bg-gray-800 p-6 rounded-lg">
            <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">Informations personnelles</h3>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Nom complet:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.firstName} {client.lastName}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">N° AVS:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.socialSecurityNumber || 'Non renseigné'}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Date de naissance:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.dateOfBirth ? new Date(client.dateOfBirth).toLocaleDateString() : 'Non renseigné'}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Nationalité:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.nationality || 'Non renseigné'}</span>
              </div>
            </div>
          </div>
          
          <div className="bg-gray-50 dark:bg-gray-800 p-6 rounded-lg">
            <h3 className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">Contact</h3>
            <div className="space-y-3">
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Email:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.email || 'Non renseigné'}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Téléphone mobile:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.mobilePhone || 'Non renseigné'}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Autre téléphone:</span>
                <span className="text-gray-900 dark:text-gray-100">{client.otherPhone || 'Non renseigné'}</span>
              </div>
              <div className="flex justify-between">
                <span className="font-medium text-gray-700 dark:text-gray-300">Adresse:</span>
                <span className="text-gray-900 dark:text-gray-100">
                  {client.street && client.streetNumber ? `${client.street} ${client.streetNumber}` : 'Non renseigné'}
                </span>
              </div>
            </div>
          </div>
        </div>
      </TabsContent>
      
      <TabsContent value="documents">
        <ClientDocumentsTab client={client} />
      </TabsContent>
      
      <TabsContent value="taches">
        <ClientTasksTab client={client} />
      </TabsContent>
    </Tabs>
  </motion.div>
);

interface ClientViewProps {
  onlyList?: boolean;
}

const ClientView = ({ onlyList = false }: ClientViewProps) => {
  const [clients, setClients] = useState<Client[]>([]);
  const { selectedClient, setSelectedClient } = useSelectedClient();
  useEffect(() => {
    getClients().then(setClients);
  }, []);
  if (onlyList) {
    return (
      <ClientList clients={clients} selectedClientId={(selectedClient as any)?.id} onSelect={setSelectedClient} />
    );
  }
  // Si un client est sélectionné, afficher la vue onglets client
  if (selectedClient) {
    return <ClientTabsView client={selectedClient as any} onBack={() => setSelectedClient(null)} />;
  }
  // Sinon, vue classique (liste + placeholder)
  return (
    <div className="flex h-full bg-white dark:bg-gray-900 rounded-2xl shadow-xl border border-gray-100 dark:border-gray-800 overflow-hidden">
      <ClientList clients={clients} selectedClientId={(selectedClient as any)?.id} onSelect={setSelectedClient} />
      <div className="flex-1 flex flex-col items-center justify-center text-gray-500 dark:text-gray-400 bg-gray-50/50 dark:bg-gray-900/50">
        <motion.div 
          initial={{ scale: 0.9, opacity: 0 }} 
          animate={{ scale: 1, opacity: 1 }} 
          className="flex flex-col items-center p-8 bg-white dark:bg-gray-800 rounded-full shadow-sm mb-6 w-48 h-48 justify-center border border-gray-100 dark:border-gray-700"
        >
          <div className="text-6xl mb-2 text-blue-500">👥</div>
        </motion.div>
        <h3 className="text-2xl font-bold mb-3 text-gray-800 dark:text-gray-200">Aucun client sélectionné</h3>
        <p className="text-lg max-w-sm text-center text-gray-500 dark:text-gray-400">
          Sélectionnez un client dans la liste pour consulter et gérer ses informations détaillées.
        </p>
      </div>
    </div>
  );
};

export default ClientView;
