import React, { useState, useEffect } from 'react';
import ToggleSwitch from '@/components/ToggleSwitch'; // Import du composant ToggleSwitch
import DraggableFileUpload from './DraggableFileUpload';
import { fetchRegistrationFileGroups } from '@/app/actions/registerFileGroupAction';
import { useEstablishment } from '@/context/EstablishmentContext';

export default function FileUpload({ onFileUpload, fileToEdit = null }) {
  const [fileName, setFileName] = useState('');
  const [file, setFile] = useState(null);
  const [isRequired, setIsRequired] = useState(false); // État pour le toggle isRequired
  const [order, setOrder] = useState(0);
  const [groups, setGroups] = useState([]);
  const [selectedGroup, setSelectedGroup] = useState('');

  const { selectedEstablishmentId } = useEstablishment();

  useEffect(() => {
    fetchRegistrationFileGroups(selectedEstablishmentId).then(data => setGroups(data));

    if (fileToEdit) {
      setFileName(fileToEdit.name || '');
      setIsRequired(fileToEdit.is_required || false);
      setOrder(fileToEdit.fusion_order || 0);
      setSelectedGroup(fileToEdit.group_id || '');
    }
  }, [fileToEdit]);

  const handleFileNameChange = (event) => {
    setFileName(event.target.value);
  };

  const handleUpload = () => {
    onFileUpload({
      file,
      name: fileName,
      is_required: isRequired,
      order: parseInt(order, 10),
      groupId: selectedGroup || null
    });
    setFile(null);
    setFileName('');
    setIsRequired(false);
    setOrder(0);
    setSelectedGroup('');
  };

  return (
    <div>
      <DraggableFileUpload
        fileName={fileName}
        onFileSelect={(selectedFile) => {
          setFile(selectedFile);
          setFileName(selectedFile.name.replace(/\.[^/.]+$/, ""));
        }}
      />
      <div className="flex mt-2">
        <input
          type="text"
          placeholder="Nom du fichier"
          value={fileName}
          onChange={handleFileNameChange}
          className="flex-grow p-2 border border-gray-200 rounded-md"
        />
        <input
          type="number"
          value={order}
          onChange={(e) => setOrder(e.target.value)}
          placeholder="Ordre de fusion"
          className="p-2 border border-gray-200 rounded-md ml-2 w-20"
        />
        <button
          onClick={handleUpload}
          className={`p-2 rounded-md shadow transition duration-200 ml-2 ${fileName !== "" ? 'bg-emerald-600 text-white hover:bg-emerald-900' : 'bg-gray-300 text-gray-500 cursor-not-allowed'}`}
          disabled={fileName === ""}
        >
          Ajouter
        </button>
      </div>
      <div className="flex items-center mt-4">
        <ToggleSwitch
          label="Fichier à remplir obligatoirement"
          checked={isRequired}
          onChange={() => setIsRequired(!isRequired)}
        />
      </div>
      <div className="mt-4">
        <label className="block mb-2">Groupe</label>
        <select
          value={selectedGroup}
          onChange={(e) => setSelectedGroup(e.target.value)}
          className="w-full border rounded p-2"
        >
          <option value="">Aucun groupe</option>
          {groups.map(group => (
            <option key={group.id} value={group.id}>{group.name}</option>
          ))}
        </select>
      </div>
    </div>
  );
}