import InputText from '@/components/Form/InputText';
import React, { useEffect } from 'react';
import { Trash2, Plus, Users } from 'lucide-react';
import SectionHeader from '@/components/SectionHeader';
import { v4 as uuidv4 } from 'uuid';

export default function SiblingInputFields({
  siblings,
  setSiblings,
  setFormData,
  errors,
  setIsPageValid,
  enable = true,
}) {
  const getError = (index, field) => {
    return errors[index]?.[field]?.[0];
  };

  const getLocalError = (index, field) => {
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (
      (field === 'last_name' &&
        (!siblings[index].last_name ||
          siblings[index].last_name.trim() === '')) ||
      (field === 'first_name' &&
        (!siblings[index].first_name ||
          siblings[index].first_name.trim() === '')) ||
      (field === 'birth_date' &&
        (!siblings[index].birth_date ||
          siblings[index].birth_date.trim() === '' ||
          !dateRegex.test(siblings[index].birth_date)))
    ) {
      return 'Champs requis';
    }
    return '';
  };

  useEffect(() => {
    // Si siblings est null ou undefined, l'initialiser à un tableau vide
    if (!siblings) {
      if (!Array.isArray(siblings) || siblings.length !== 0) {
        setSiblings([]); // Éviter de réexécuter inutilement si siblings est déjà []
      }
      return; // Sortir pour éviter de continuer l'exécution inutilement
    }

    // Synchroniser siblings avec formData uniquement si nécessaire
    setFormData((prevFormData) => {
      if (JSON.stringify(prevFormData.siblings) !== JSON.stringify(siblings)) {
        return {
          ...prevFormData,
          siblings: siblings, // Mettez à jour siblings dans formData
        };
      }
      return prevFormData; // Évitez une mise à jour inutile
    });

    // Valider les siblings
    const isValid = siblings.every((sibling, index) => {
      return !Object.keys(sibling).some(
        (field) => getLocalError(index, field) !== ''
      );
    });

    setIsPageValid(isValid);
  }, [siblings, getLocalError, setFormData, setIsPageValid]);

  const onSiblingsChange = (id, field, value) => {
    const updatedSiblings = siblings.map((sibling) => {
      if (sibling.id === id) {
        return { ...sibling, [field]: value };
      }
      return sibling;
    });

    setSiblings(updatedSiblings);
  };

  const addSibling = () => {
    setSiblings([
      ...siblings,
      {
        id: `temp-${uuidv4()}`,
        last_name: '',
        first_name: '',
        birth_date: '',
      },
    ]);
  };

  const deleteSibling = (index) => {
    const updatedSiblings = siblings.filter((_, i) => i !== index);
    setSiblings(updatedSiblings);
  };

  return (
    <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
      <SectionHeader
        icon={Users}
        title={'Frères et Sœurs'}
        description={'Ajoutez les informations des frères et sœurs'}
      />
      {siblings.map((item, index) => (
        <div className="p-6" key={index}>
          <div className="flex justify-between items-center mb-4">
            <h3 className="font-headline text-xl font-bold">Frère/Sœur {index + 1}</h3>
            <Trash2
              className="w-5 h-5 text-red-500 cursor-pointer hover:text-red-700 transition-colors"
              onClick={() => deleteSibling(index)}
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <InputText
              name="last_name"
              type="text"
              label="Nom"
              value={item.last_name}
              onChange={(event) => {
                onSiblingsChange(item.id, 'last_name', event.target.value);
              }}
              errorMsg={getError('last_name')}
              errorLocalMsg={getLocalError(index, 'last_name')}
              required
              enable={enable}
            />
            <InputText
              name="first_name"
              type="text"
              label="Prénom"
              value={item.first_name}
              onChange={(event) => {
                onSiblingsChange(item.id, 'first_name', event.target.value);
              }}
              errorMsg={getError('first_name')}
              errorLocalMsg={getLocalError(index, 'first_name')}
              required
              enable={enable}
            />
          </div>

          <div className="grid grid-cols-1 gap-4">
            <InputText
              name="birth_date"
              type="date"
              label="Date de Naissance"
              value={item.birth_date}
              onChange={(event) => {
                onSiblingsChange(item.id, 'birth_date', event.target.value);
              }}
              errorMsg={getError('birth_date')}
              errorLocalMsg={getLocalError(index, 'birth_date')}
              required
              enable={enable}
            />
          </div>
        </div>
      ))}

      {enable && (
        <div className="flex justify-center">
          <Plus
            className="w-8 h-8 text-primary cursor-pointer hover:text-secondary transition-colors border-2 border-primary hover:border-secondary rounded-full p-1"
            onClick={addSibling}
          />
        </div>
      )}
    </div>
  );
}
