import {
  Trash2,
  Edit3,
  Check,
  X,
  BookOpen,
  Download,
  Plus,
} from 'lucide-react';
import { useState, useEffect } from 'react';
import Table from '@/components/Table';
import Popup from '@/components/Popup';
import InputTextWithColorIcon from '@/components/Form/InputTextWithColorIcon';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import SpecialityItem from '@/components/Structure/Configuration/SpecialityItem';
import { useEstablishment } from '@/context/EstablishmentContext';
import logger from '@/utils/logger';
import SectionHeader from '@/components/SectionHeader';
import EmptyState from '@/components/EmptyState';
import { exportToCSV } from '@/utils/exportCSV';

const SpecialitiesSection = ({
  specialities,
  allSpecialities,
  setSpecialities,
  handleCreate,
  handleEdit,
  handleDelete,
}) => {
  const [newSpeciality, setNewSpeciality] = useState(null);
  const [editingSpeciality, setEditingSpeciality] = useState(null);
  const [formData, setFormData] = useState({});
  const [localErrors, setLocalErrors] = useState({});
  const [popupVisible, setPopupVisible] = useState(false);
  const [popupMessage, setPopupMessage] = useState('');

  const [removePopupVisible, setRemovePopupVisible] = useState(false);
  const [removePopupMessage, setRemovePopupMessage] = useState('');
  const [removePopupOnConfirm, setRemovePopupOnConfirm] = useState(() => {});
  const ITEMS_PER_PAGE = 10;
  const [currentPage, setCurrentPage] = useState(1);
  useEffect(() => {
    setCurrentPage(1);
  }, [specialities]);
  useEffect(() => {
    if (newSpeciality) setCurrentPage(1);
  }, [newSpeciality]);
  const totalPages = Math.ceil(specialities.length / ITEMS_PER_PAGE);
  const pagedSpecialities = specialities.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  const { selectedEstablishmentId, profileRole } = useEstablishment();

  const getError = (field) => {
    return localErrors?.[field]?.[0];
  };

  const handleAddSpeciality = () => {
    setNewSpeciality({ id: Date.now(), name: '', color_code: '' });
  };

  const handleExportCSV = () => {
    const exportColumns = [
      { key: 'id', label: 'ID' },
      { key: 'name', label: 'Nom' },
      { key: 'color_code', label: 'Code couleur' },
      { key: 'updated_date_formatted', label: 'Date de mise à jour' },
    ];
    const filename = `specialites_${new Date().toISOString().split('T')[0]}`;
    exportToCSV(specialities, exportColumns, filename);
  };

  const handleRemoveSpeciality = (id) => {
    return handleDelete(id)
      .then(() => {
        setSpecialities((prevSpecialities) =>
          prevSpecialities.filter((speciality) => speciality.id !== id)
        );
      })
      .catch((error) => {
        logger.error(error);
      });
  };

  const handleSaveNewSpeciality = () => {
    if (newSpeciality.name) {
      const specialityData = {
        ...newSpeciality,
        establishment: selectedEstablishmentId,
      };

      handleCreate(specialityData)
        .then((createdSpeciality) => {
          setSpecialities([createdSpeciality, ...specialities]);
          setNewSpeciality(null);
          setLocalErrors({});
        })
        .catch((error) => {
          logger.error('Error:', error.message);
          if (error.details) {
            logger.error('Form errors:', error.details);
            setLocalErrors(error.details);
          }
        });
    } else {
      setPopupMessage('Tous les champs doivent être remplis et valides');
      setPopupVisible(true);
    }
  };

  const handleUpdateSpeciality = (id, updatedSpeciality) => {
    if (updatedSpeciality.name) {
      handleEdit(id, updatedSpeciality)
        .then((updatedItem) => {
          setSpecialities(
            specialities.map((speciality) =>
              speciality.id === id ? updatedItem : speciality
            )
          );
          setEditingSpeciality(null);
          setLocalErrors({});
        })
        .catch((error) => {
          logger.error('Error:', error.message);
          if (error.details) {
            logger.error('Form errors:', error.details);
            setLocalErrors(error.details);
          }
        });
    } else {
      setPopupMessage('Tous les champs doivent être remplis et valides');
      setPopupVisible(true);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    const fieldName = name.includes('_color') ? 'color_code' : name;

    if (editingSpeciality) {
      setFormData((prevData) => ({
        ...prevData,
        [fieldName]: value,
      }));
    } else if (newSpeciality) {
      setNewSpeciality((prevData) => ({
        ...prevData,
        [fieldName]: value,
      }));
    }
  };

  const renderSpecialityCell = (speciality, column) => {
    const isEditing = editingSpeciality === speciality.id;
    const isCreating = newSpeciality && newSpeciality.id === speciality.id;
    const currentData = isEditing ? formData : newSpeciality;

    if (isEditing || isCreating) {
      switch (column) {
        case 'LIBELLE':
          return (
            <InputTextWithColorIcon
              name="name"
              textValue={currentData.name}
              colorValue={currentData.color_code}
              onTextChange={handleChange}
              onColorChange={handleChange}
              placeholder="Nom de la spécialité"
              errorMsg={getError('name')}
            />
          );
        case 'ACTIONS':
          return (
            <div className="flex justify-center space-x-2">
              <button
                type="button"
                onClick={() =>
                  isEditing
                    ? handleUpdateSpeciality(editingSpeciality, formData)
                    : handleSaveNewSpeciality()
                }
                className="text-primary hover:text-secondary"
              >
                <Check className="w-5 h-5" />
              </button>
              <button
                type="button"
                onClick={() =>
                  isEditing
                    ? setEditingSpeciality(null)
                    : setNewSpeciality(null)
                }
                className="text-red-500 hover:text-red-700"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          );
        default:
          return null;
      }
    }

    switch (column) {
      case 'LIBELLE':
        return <SpecialityItem key={speciality.id} speciality={speciality} />;
      case 'MISE A JOUR':
        return speciality.updated_date_formatted;
      case 'ACTIONS':
        return (
          <div className="flex justify-center space-x-2">
            <button
              type="button"
              onClick={() =>
                setEditingSpeciality(speciality.id) || setFormData(speciality)
              }
              className="text-blue-500 hover:text-blue-700"
            >
              <Edit3 className="w-5 h-5" />
            </button>
            <button
              type="button"
              onClick={() => {
                setRemovePopupVisible(true);
                setRemovePopupMessage(
                  'Attention ! \nVous êtes sur le point de supprimer la spécialité ' +
                    speciality.name +
                    ".\nÊtes-vous sûr(e) de vouloir poursuivre l\'opération ?"
                );
                setRemovePopupOnConfirm(() => () => {
                  handleRemoveSpeciality(speciality.id)
                    .then((data) => {
                      logger.debug('Success:', data);
                      setPopupMessage(
                        'La spécialité ' +
                          speciality.name +
                          ' a été correctement supprimée'
                      );
                      setPopupVisible(true);
                      setRemovePopupVisible(false);
                    })
                    .catch((error) => {
                      logger.error('Error archiving data:', error);
                      setPopupMessage(
                        'Erreur lors de la suppression de la spécialité ' +
                          speciality.name
                      );
                      setPopupVisible(true);
                      setRemovePopupVisible(false);
                    });
                });
              }}
              className="text-red-500 hover:text-red-700"
            >
              <Trash2 className="w-5 h-5" />
            </button>
          </div>
        );
      default:
        return null;
    }
  };

  const columns = [
    { name: 'LIBELLE', label: 'Libellé' },
    { name: 'MISE A JOUR', label: 'Date mise à jour' },
    ...(profileRole !== 0 ? [{ name: 'ACTIONS', label: 'Actions' }] : []),
  ];

  return (
    <DndProvider backend={HTML5Backend}>
      <div className="space-y-4">
        {(pagedSpecialities.length > 0 || newSpeciality) && (
          <SectionHeader
            icon={BookOpen}
            title="Liste des spécialités"
            description="Gérez les spécialités de votre école"
            button={profileRole !== 0}
            onClick={handleAddSpeciality}
            secondaryButton={
              <button
                onClick={handleExportCSV}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-secondary bg-primary/10 rounded-lg hover:bg-primary/20 transition-colors"
                title="Exporter en CSV"
              >
                <Download className="w-4 h-4" />
                Exporter
              </button>
            }
          />
        )}
        <Table
          data={
            newSpeciality
              ? [newSpeciality, ...pagedSpecialities]
              : pagedSpecialities
          }
          columns={columns}
          renderCell={renderSpecialityCell}
          emptyMessage={
            <EmptyState
              icon={BookOpen}
              title="Aucune spécialité enregistrée"
              description="Créez des spécialités pour les attribuer à vos enseignants et structurer votre offre pédagogique."
              actionLabel={
                profileRole !== 0 ? 'Ajouter une spécialité' : undefined
              }
              onAction={profileRole !== 0 ? handleAddSpeciality : undefined}
              actionIcon={profileRole !== 0 ? Plus : undefined}
            />
          }
          itemsPerPage={ITEMS_PER_PAGE}
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
        <Popup
          isOpen={popupVisible}
          message={popupMessage}
          onConfirm={() => setPopupVisible(false)}
          onCancel={() => setPopupVisible(false)}
          uniqueConfirmButton={true}
        />
        <Popup
          isOpen={removePopupVisible}
          message={removePopupMessage}
          onConfirm={removePopupOnConfirm}
          onCancel={() => setRemovePopupVisible(false)}
        />
      </div>
    </DndProvider>
  );
};

export default SpecialitiesSection;
