'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { createClient, updateClient } from '@/helpers/axios_helper';
import { Client, FolderStatus } from '@/types/types';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Button } from '@/components/ui/button';
import { toast } from 'react-hot-toast';

interface ClientFormProps {
  client?: Client;
  onSuccess?: () => void;
}

export default function ClientForm({ client, onSuccess }: ClientFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState('personal');
  const [formData, setFormData] = useState<any>(client || {
    // Données personnelles
    firstName: '',
    lastName: '',
    socialSecurityNumber: '',
    dateOfBirth: '',
    nationality: '',
    status: FolderStatus.PENDING,
    // Contact
    email: '',
    mobilePhone: '',
    otherPhone: '',
    street: '',
    streetNumber: '',
    postalCode: '',
    stateCanton: '',
    // Coordonnées financières
    bank: '',
    accountNumber: '',
    accountHolder: '',
    accountPurpose: '',
    accountStatus: '',
    financialOther: '',
    // Coordonnées professionnelles
    employer: '',
    professionalResponsible: '',
    professionalPhone: '',
    professionalCity: '',
    professionalCountry: '',
    contractStart: '',
    professionalStatus: '',
    professionalOther: '',
    // Coordonnées relationnelles
    fatherName: '',
    fatherContact: '',
    motherName: '',
    motherContact: '',
    spouseName: '',
    spouseContact: '',
    relationOther: '',
  });
  const [error, setError] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev: any) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    try {
      // Validation simple : seuls les champs essentiels sont obligatoires
      const requiredFields = [
        'firstName','lastName','socialSecurityNumber'
      ];
      for (const field of requiredFields) {
        if (!formData[field]) {
          setError('Veuillez remplir au minimum le prénom, nom et numéro AVS.');
          setLoading(false);
          return;
        }
      }
      // Soumission
      if (client) {
        // Modification d'un client existant
        await updateClient(client.id.toString(), formData);
        toast.success('Client modifié avec succès');
      } else {
        // Création d'un nouveau client
      await createClient(formData);
        toast.success('Client créé avec succès');
      }
      if (onSuccess) onSuccess();
      else router.push('/clients');
    } catch (error: any) {
      if (error?.response?.data?.error?.includes('Unique constraint failed') || error?.response?.data?.error?.includes('P2002')) {
        setError('Un client avec ce numéro AVS existe déjà. Veuillez vérifier le champ ou utiliser un autre numéro.');
      } else {
        setError('Erreur lors de la création du client.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto px-4 py-6">
      <form onSubmit={handleSubmit} className="max-w-4xl mx-auto space-y-6">
        {error && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            {error}
          </div>
        )}
        <Tabs value={tab} onValueChange={setTab} className="w-full">
          <TabsList className="flex w-full justify-between bg-gray-100 rounded-lg shadow mb-6 p-1 gap-2">
            <TabsTrigger value="personal" className={`flex-1 py-2 px-4 rounded-lg transition-all duration-300 text-center font-semibold
              ${tab === 'personal' ? 'bg-blue-600 text-white shadow-lg scale-105' : 'bg-white text-gray-700 hover:bg-blue-50'}
            `}>Données Personnelles</TabsTrigger>
            <TabsTrigger value="contact" className={`flex-1 py-2 px-4 rounded-lg transition-all duration-300 text-center font-semibold
              ${tab === 'contact' ? 'bg-blue-600 text-white shadow-lg scale-105' : 'bg-white text-gray-700 hover:bg-blue-50'}
            `}>Contact</TabsTrigger>
            <TabsTrigger value="financial" className={`flex-1 py-2 px-4 rounded-lg transition-all duration-300 text-center font-semibold
              ${tab === 'financial' ? 'bg-blue-600 text-white shadow-lg scale-105' : 'bg-white text-gray-700 hover:bg-blue-50'}
            `}>Coordonnées financières</TabsTrigger>
            <TabsTrigger value="professional" className={`flex-1 py-2 px-4 rounded-lg transition-all duration-300 text-center font-semibold
              ${tab === 'professional' ? 'bg-blue-600 text-white shadow-lg scale-105' : 'bg-white text-gray-700 hover:bg-blue-50'}
            `}>Coordonnées professionnelles</TabsTrigger>
            <TabsTrigger value="relation" className={`flex-1 py-2 px-4 rounded-lg transition-all duration-300 text-center font-semibold
              ${tab === 'relation' ? 'bg-blue-600 text-white shadow-lg scale-105' : 'bg-white text-gray-700 hover:bg-blue-50'}
            `}>Coordonnées relationnelles</TabsTrigger>
          </TabsList>

          {/* Données personnelles */}
          <TabsContent value="personal" className="space-y-4 mt-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="firstName">Prénom</Label>
                <Input id="firstName" name="firstName" value={formData.firstName} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lastName">Nom</Label>
                <Input id="lastName" name="lastName" value={formData.lastName} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="dateOfBirth">Date de naissance</Label>
                 <Input id="dateOfBirth" name="dateOfBirth" type="date" value={formData.dateOfBirth} onChange={handleChange} />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="nationality">Nationalité</Label>
                 <Input id="nationality" name="nationality" value={formData.nationality} onChange={handleChange} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="city">Ville</Label>
                 <Input id="city" name="city" value={formData.city || ''} onChange={handleChange} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="socialSecurityNumber">Numéro AVS</Label>
                <Input id="socialSecurityNumber" name="socialSecurityNumber" value={formData.socialSecurityNumber} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label htmlFor="status">Statut</Label>
                <select id="status" name="status" value={formData.status} onChange={handleChange} required className="w-full p-2 border rounded">
                  <option value="">Sélectionner un statut</option>
                  <option value="PENDING">En attente</option>
                  <option value="PROGRESS">En cours</option>
                  <option value="FINISHED">Terminé</option>
                  <option value="URGENT">Urgent</option>
                </select>
              </div>
            </div>
          </TabsContent>

          {/* Contact */}
          <TabsContent value="contact" className="space-y-4 mt-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <Input id="email" name="email" type="email" value={formData.email} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="mobilePhone">Téléphone mobile</Label>
                <Input id="mobilePhone" name="mobilePhone" value={formData.mobilePhone} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="otherPhone">Autre téléphone</Label>
                <Input id="otherPhone" name="otherPhone" value={formData.otherPhone} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="stateCanton">Canton</Label>
                <Input id="stateCanton" name="stateCanton" value={formData.stateCanton} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="street">Rue</Label>
                <Input id="street" name="street" value={formData.street} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="streetNumber">Numéro</Label>
                <Input id="streetNumber" name="streetNumber" value={formData.streetNumber} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 gap-4">
              <div className="space-y-2">
                <Label htmlFor="postalCode">Code postal</Label>
                <Input id="postalCode" name="postalCode" value={formData.postalCode} onChange={handleChange} required />
              </div>
            </div>
          </TabsContent>

          {/* Coordonnées financières */}
          <TabsContent value="financial" className="space-y-4 mt-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="bank">Banque</Label>
                <Input id="bank" name="bank" value={formData.bank} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="accountNumber">N° de compte</Label>
                <Input id="accountNumber" name="accountNumber" value={formData.accountNumber} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="accountHolder">Titulaire</Label>
                <Input id="accountHolder" name="accountHolder" value={formData.accountHolder} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="accountPurpose">Objet du compte</Label>
                <select id="accountPurpose" name="accountPurpose" value={formData.accountPurpose} onChange={handleChange} required className="w-full p-2 border rounded">
                  <option value="">Sélectionner</option>
                  <option value="curatelle">Curatelle</option>
                  <option value="prive">Privé</option>
                  <option value="epargne">Épargne</option>
                </select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="accountStatus">Statut</Label>
                <select id="accountStatus" name="accountStatus" value={formData.accountStatus} onChange={handleChange} required className="w-full p-2 border rounded">
                  <option value="">Sélectionner</option>
                  <option value="actif">Actif</option>
                  <option value="cloture">Clôturé</option>
                </select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="financialOther">Autre</Label>
                <Input id="financialOther" name="financialOther" value={formData.financialOther} onChange={handleChange} />
              </div>
            </div>
          </TabsContent>

          {/* Coordonnées professionnelles */}
          <TabsContent value="professional" className="space-y-4 mt-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="employer">Employeur</Label>
                <Input id="employer" name="employer" value={formData.employer} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="professionalResponsible">Responsable</Label>
                <Input id="professionalResponsible" name="professionalResponsible" value={formData.professionalResponsible} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="professionalPhone">Téléphone</Label>
                <Input id="professionalPhone" name="professionalPhone" value={formData.professionalPhone} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="professionalCountry">Pays</Label>
                <Input id="professionalCountry" name="professionalCountry" value={formData.professionalCountry} onChange={handleChange} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="professionalCanton">Canton</Label>
                <Input id="professionalCanton" name="professionalCanton" value={formData.professionalCanton || ''} onChange={handleChange} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="professionalCity">Ville</Label>
                <Input id="professionalCity" name="professionalCity" value={formData.professionalCity} onChange={handleChange} required />
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="contractType">Type de contrat</Label>
                <select id="contractType" name="contractType" value={formData.contractType || ''} onChange={handleChange} required className="w-full p-2 border rounded">
                  <option value="">Sélectionner</option>
                  <option value="CDD">CDD</option>
                  <option value="CDI">CDI</option>
                  <option value="AUTRE">AUTRE</option>
                </select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="contractStart">Début de contrat</Label>
                <Input id="contractStart" name="contractStart" type="date" value={formData.contractStart} onChange={handleChange} required />
              </div>
              {formData.contractType !== 'CDI' && (
                <div className="space-y-2">
                  <Label htmlFor="contractEnd">Fin de contrat</Label>
                  <Input id="contractEnd" name="contractEnd" type="date" value={formData.contractEnd || ''} onChange={handleChange} />
                </div>
              )}
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="professionalStatus">Statut</Label>
                <select id="professionalStatus" name="professionalStatus" value={formData.professionalStatus} onChange={handleChange} required className="w-full p-2 border rounded">
                  <option value="">Sélectionner</option>
                  <option value="actif">Actif</option>
                  <option value="fin">Fin</option>
                </select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="professionalOther">Autre</Label>
                <Input id="professionalOther" name="professionalOther" value={formData.professionalOther} onChange={handleChange} />
              </div>
            </div>
          </TabsContent>

          {/* Coordonnées relationnelles */}
          <TabsContent value="relation" className="space-y-8 mt-6">
            {/* Bloc Père */}
            <div>
              <div className="flex flex-col items-center mb-2">
                <span className="text-lg font-semibold text-center">
                  <span className="text-red-500">*</span> Père :
                </span>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="fatherName">Nom</Label>
                  <Input id="fatherName" name="fatherName" value={formData.fatherName} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="fatherContact">Contact</Label>
                  <Input id="fatherContact" name="fatherContact" value={formData.fatherContact} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="fatherCountry">Pays</Label>
                  <Input id="fatherCountry" name="fatherCountry" value={formData.fatherCountry || ''} onChange={handleChange} />
                </div>
              </div>
            </div>
            {/* Bloc Mère */}
            <div>
              <div className="flex flex-col items-center mb-2">
                <span className="text-lg font-semibold text-center">
                  <span className="text-red-500">*</span> Mère :
                </span>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="motherName">Nom</Label>
                  <Input id="motherName" name="motherName" value={formData.motherName} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="motherContact">Contact</Label>
                  <Input id="motherContact" name="motherContact" value={formData.motherContact} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="motherCountry">Pays</Label>
                  <Input id="motherCountry" name="motherCountry" value={formData.motherCountry || ''} onChange={handleChange} />
                </div>
              </div>
            </div>
            {/* Bloc Partenaire */}
            <div>
              <div className="flex flex-col items-center mb-2">
                <span className="text-lg font-semibold text-center">
                  <span className="text-red-500">*</span> Partenaire :
                </span>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="partnerName">Nom</Label>
                  <Input id="partnerName" name="partnerName" value={formData.partnerName || ''} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="partnerContact">Contact</Label>
                  <Input id="partnerContact" name="partnerContact" value={formData.partnerContact || ''} onChange={handleChange} />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="partnerCountry">Pays</Label>
                  <Input id="partnerCountry" name="partnerCountry" value={formData.partnerCountry || ''} onChange={handleChange} />
                </div>
              </div>
            </div>
            {/* Champ Autre */}
            <div className="space-y-2">
              <Label htmlFor="relationOther">Autre</Label>
              <Input id="relationOther" name="relationOther" value={formData.relationOther || ''} onChange={handleChange} />
            </div>
            <div className="flex justify-end space-x-4 mt-6">
              <Button
                type="button"
                variant="outline"
                onClick={() => router.push('/clients')}
                disabled={loading}
              >
                Annuler
              </Button>
              <Button type="submit" disabled={loading}>
                {loading ? 'Enregistrement...' : 'Enregistrer'}
              </Button>
            </div>
          </TabsContent>
        </Tabs>
      </form>
    </div>
  );
} 