import { useEffect, useState, useCallback } from 'react';
import { faUserTie, faStickyNote } from '@fortawesome/free-solid-svg-icons';
import type { FormFieldType } from '@/shared/types/common';
import type { IAbsence, IPassenger } from '@/shared/types/absence';
import { _SENS_AR } from '@/shared/_mock';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { FormikProps } from 'formik';

export type OptionType = {
  value: string;
  label: string;
};

const RECEPTION_MODES = [
  { value: 'SMS', label: 'SMS' },
  { value: 'EMAIL', label: 'Email' },
  { value: 'APPLICATION', label: 'Application mobile' }
];

export const _OPTION_DEMANDE = [
  { value: 'Traité', label: 'Traité' },
  { value: 'Non traité', label: 'Non traité' },
  { value: 'Annulé', label: 'Annulé' },
  { value: 'En cours', label: 'En cours' }
];

export const useFormFieldsAbsence = (optionDemande: OptionType[]) => {
  const { searchPassengers, passengers } = usePassengerStore();
  const [searchTerm, setSearchTerm] = useState('');

  const debouncedSearch = useCallback(
    (() => {
      let timeoutId: NodeJS.Timeout;
      return (term: string) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          if (term.trim()) {
            searchPassengers({ 
              firstName: term, 
              lastName: term, 
              size: 50 
            });
          } else {
            searchPassengers({ size: 100 });
          }
        }, 300);
      };
    })(),
    [searchPassengers]
  );

  useEffect(() => {
    searchPassengers({ size: 100 });
  }, [searchPassengers]);

  const fields: FormFieldType<IAbsence>[] = [
    {
      name: 'usager',
      label: 'Usager',
      type: 'combobox',
      required: true,
    },
    {
      name: 'dateDebut',
      label: 'Date de début',
      type: 'date',
      required: true,
    },
    {
      name: 'dateFin',
      label: 'Date de fin',
      type: 'date',
      required: true,
    },
    {
      name: 'par',
      label: 'Par',
      placeholder: 'Entrez un nom',
      required: true,
      type: 'text',
      icon: faUserTie
    },
    {
      name: 'sensAR',
      label: 'Trajets concernés',
      type: 'checkbox-group',
      options: [
        { value: 'aller', label: 'Aller' },
        { value: 'retour', label: 'Retour' }
      ],
      required: true,
    },
    {
      name: 'modeReception',
      label: 'Mode de réception',
      type: 'select',
      options: RECEPTION_MODES,
      required: true,
    },
    {
      name: 'previentLe',
      label: 'Quand',
      type: 'date',
      required: true,
    },
    {
      name: 'etat',
      label: 'Etat',
      type: 'select',
      options: optionDemande,
      required: true
    },
    {
      name: 'observation',
      label: "Observation",
      placeholder: "Ajoutez une note ou une observation",
      type: 'textarea',
      icon: faStickyNote,
    },
  ];

  return fields;
};
