import { useState, useCallback } from 'react';

export type FieldType = 'mobile' | 'fixe' | 'personne' | 'etablissement';

interface UseMultipleFieldsProps {
  initialValues: Partial<Record<FieldType, string[]>>;
  onChange: (type: FieldType, newValues: string[]) => void;
  isReadOnly: boolean;
}

export function useMultipleFields({ initialValues, onChange, isReadOnly }: UseMultipleFieldsProps) {
  const [fields, setFields] = useState<Partial<Record<FieldType, string[]>>>(initialValues);

  const reset = useCallback((newValues?: Partial<Record<FieldType, string[]>>) => {
    const valuesToReset = newValues || initialValues;
    setFields(valuesToReset);
  }, [initialValues]);

  const handleAdd = useCallback((type: FieldType) => {
    if (!isReadOnly && fields[type]) {
      const newFields = [...fields[type]!, ''];
      setFields(prevFields => ({ ...prevFields, [type]: newFields }));
      onChange(type, newFields);
    }
  }, [fields, isReadOnly, onChange]);

  const handleDelete = useCallback((type: FieldType, index: number) => {
    if (!isReadOnly && fields[type]) {
      const newFields = [...fields[type]!];
      newFields.splice(index, 1);
      setFields(prevFields => ({ ...prevFields, [type]: newFields }));
      onChange(type, newFields);
    }
  }, [fields, isReadOnly, onChange]);

  const handleChange = useCallback((type: FieldType, index: number, value: string) => {
    if (!isReadOnly && fields[type]) {
      const newFields = [...fields[type]!];
      newFields[index] = value;
      setFields(prevFields => ({ ...prevFields, [type]: newFields }));
      onChange(type, newFields);
    }
  }, [fields, isReadOnly, onChange]);

  return {
    fields,
    handleAdd,
    handleDelete,
    handleChange,
    reset,
  };
}