'use client';

import { useState, useEffect } from 'react';
import { Alert, Grid, Snackbar, Typography } from '@mui/material';
import FormField from '@/shared/components/form/form-field';
import { TypeImport, type FormFieldType, type ModeType } from '@/shared/types/common';
import FormContainer from '@/layouts/form/form-container';
import EditExportButtons from '@/shared/components/form/edit-export-buttons';
import { holidayImportFormFields } from '../utils/form-fields-vacance';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faFileArrowUp } from '@fortawesome/free-solid-svg-icons';
import HolidayZoneDetails, { ZONES_IMPORT_DEFAULT } from '../components/holiday-zone-details';
import { DEFAULT_ZONES } from '@/shared/_mock/_vacance';
import ActionButtons from '@/shared/components/form/buttons-action';
import { tabsBorder } from '@/shared/theme/css';
import { useBoolean } from '@/hooks';
import MassUploadFile from '@/shared/components/mass-import/mass-upload-file';
import { useEstablishmentStore } from '@/shared/api/stores/admin-service/establishmentStore';
import { HolidayType, IHolidayImport, IHolidayImportChildren, IHolidayZoneImport } from '@/shared/types/establishment';
import * as XLSX from 'xlsx';
import { logger } from '@/utils/logger';
import { useSnackbar } from 'notistack';

interface VacationFormProps {
  holidayImport: IHolidayImport;
  mode: ModeType;
  onSave: (updatedVacation: IHolidayImport) => void;
  onEdit: (updatedVacation: IHolidayImport) => void;
  onClose: () => void;
  isChild?: boolean;
}

export default function VacationForm({
  holidayImport,
  mode,
  onSave,
  onClose,
  onEdit,
  isChild = false,
}: VacationFormProps) {
  const { enqueueSnackbar } = useSnackbar();
  const uploadFile = useBoolean(false);
  const [formData, setFormData] = useState<IHolidayImport>(() => ({
    ...holidayImport,
    zones: holidayImport.zones || DEFAULT_ZONES,
  }));
  const [currentStep, setCurrentStep] = useState<"import" | "details">(() => {
    return "import"
  })
  useEffect(() => {
    setCurrentStep("import")
  }, [holidayImport.id])

  useEffect(() => {
    setFormData(holidayImport);
  }, [holidayImport]);

  const userId = localStorage.getItem("userId");

  useEffect(() => {
    if (userId) {
      setFormData({
        ...formData,
        importedBy: userId,
      });
    }
  }, [userId]);

  const { createHolidayImport, exportHolidaysExcelTemplate } = useEstablishmentStore();

  const handleSave = () => {
    createHolidayImport(formData).then(() => {
      enqueueSnackbar("Période sauvegardée avec succès", { variant: "success" });
      onClose();
    }).catch((error) => {
      enqueueSnackbar("Erreur lors de la sauvegarde de la période", { variant: "error" });
    });
  };

  const handleContinue = () => {
    setCurrentStep('details');
  };

  const isReadOnly = mode === 'view';

  const handleExportHolidayTemplate = () => {
    uploadFile.onFalse();
    if (mode !== 'edit') {
      exportHolidaysExcelTemplate("Élèves", false);
    } else {
      exportHolidaysExcelTemplate("Élèves", true);
    }
  }

  const renderField = (field: FormFieldType<IHolidayImport>) => (
    <FormField
      key={`${String(field.name)}-${holidayImport.id}`}
      field={field}
      value={formData[field.name as keyof IHolidayImport]}
      onChange={(name, value) => setFormData((prev: IHolidayImport) => ({ ...prev, [name]: value }))}
      isReadOnly={isReadOnly}
    />
  );

  const ZONES = ["Zone A", "Zone B", "Zone C"];
  const HEADERS = ["Nom", "de", "à", "Type", "Académie", "Population"];

  const [uploadedFile, setUploadedFile] = useState<File | null>(null);

  const handleUpload = (file: File) => {
    try {
      setUploadedFile(file);
    } catch (error) {
      logger("Erreur dans handleUpload :", error);
    }
  }

  useEffect(() => {
    if (uploadedFile) {
      processUploadedFile(uploadedFile);
    }
  }, [uploadedFile]);

  function toLocalDateTime(dateStr: string | number): string {
    if (!dateStr) return "";
    if (typeof dateStr === "number" || /^\d+$/.test(dateStr)) {
      const excelEpoch = new Date(1899, 11, 30);
      const days = typeof dateStr === "number" ? dateStr : parseInt(dateStr, 10);
      const ms = days * 24 * 60 * 60 * 1000;
      const date = new Date(excelEpoch.getTime() + ms);
      return date.toISOString().slice(0, 10) + "T00:00:00";
    }
    let [year, month, day] = ["", "", ""];
    if (dateStr.includes("/")) {
      const parts = dateStr.split("/");
      if (parts.length === 3) {
        [day, month, year] = parts;
      }
    } else if (dateStr.includes("-")) {
      const parts = dateStr.split("-");
      if (parts.length === 3) {
        [year, month, day] = parts;
      }
    }
    if (year && month && day) {
      return `${year.padStart(4, "0")}-${month.padStart(2, "0")}-${day.padStart(2, "0")}T00:00:00`;
    }
    return dateStr;
  }

  const processUploadedFile = async (file: File) => {
    try {
      const data = await file.arrayBuffer();
      logger("Fichier importé et lu avec succès :", file.name);

      const workbook = XLSX.read(data, { type: "array" });
      let sheetName = "Holidays";
      let sheet = workbook.Sheets[sheetName];

      if (!sheet) {
        sheetName = workbook.SheetNames[0];
        sheet = workbook.Sheets[sheetName];
        if (!sheet) {
          throw new Error("Aucune feuille trouvée dans le fichier Excel !");
        }
      }

      const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 }) as any[][];
      const holidayList: IHolidayImportChildren[] = [];

      for (let rowIndex = 2; rowIndex < rows.length; rowIndex++) {
        const row = rows[rowIndex];
        if (!row) continue;

        ZONES.forEach((zoneName, zoneIndex) => {
          try {
            const colOffset = zoneIndex * HEADERS.length;
            const name = String(row[colOffset] ?? "").trim();
            const startDate = String(row[colOffset + 1] ?? "").trim();
            const endDate = String(row[colOffset + 2] ?? "").trim();
            const type = String(row[colOffset + 3] ?? "").trim();
            const academy = String(row[colOffset + 4] ?? "").trim();
            const population = String(row[colOffset + 5] ?? "").trim();

            if (!type) return;

            const isPublicHoliday = type.toLowerCase() === "jour férié";
            const isEmpty = isPublicHoliday
              ? [name, startDate, type].every((val) => !val)
              : [name, startDate, endDate, type, academy, population].every((val) => !val);
            if (isEmpty) return;

            holidayList.push({
              id: "",
              name,
              startDate: toLocalDateTime(startDate),
              endDate: isPublicHoliday ? "" : toLocalDateTime(endDate),
              type: isPublicHoliday ? HolidayType.PUBLIC_HOLIDAY : HolidayType.SCHOOL_HOLIDAY,
              academy: isPublicHoliday ? "" : academy,
              population: isPublicHoliday ? "" : population,
              zoneName,
            });
            setFormData({
              ...formData,
              zones: processHolidayListByZone(holidayList),
            });
          } catch (zoneErr) {
            logger(`Erreur lors du traitement de la zone ${zoneName} à la ligne ${rowIndex + 1}:`, zoneErr);
          }
        });
      }
      logger("Import terminé.");
    } catch (error) {
      logger("Erreur pendant l'import :", error);
    }
  };

  useEffect(() => {
    console.log("formData", formData);
  }, [formData]);

  const processHolidayListByZone = (holidayList: IHolidayImportChildren[]) => {
    const holidayZoneImports: IHolidayZoneImport[] = [];
    ZONES_IMPORT_DEFAULT.forEach((zone: IHolidayZoneImport) => {
      holidayZoneImports.push({
        zoneName: zone.zoneName,
        holidays: holidayList.filter((holiday) => holiday.zoneName === zone.zoneName)
      });
    });
    return holidayZoneImports;
  }

  return (
    <FormContainer sx={isChild ? { ...tabsBorder } : undefined} titre="Fiche Période">
      {isReadOnly ? (
        <EditExportButtons
          onEdit={() => onEdit(holidayImport)}
          onExport={() => void 0}
          tooltipTitle="période des vacances"
        />
      ) : null}
      <form>
        {currentStep === 'import' ? (
          <Grid container spacing={4}>
            {holidayImportFormFields.map((field) => (
              <Grid item xs={12} sm={4} key={`${String(field.name)}-${holidayImport.id}`}>
                {renderField(field)}
              </Grid>
            ))}
            <Grid item xs={12} sm={6} xl={4} key={`import-${holidayImport.id}`} sx={{ display: 'flex' }}>
              <Typography sx={{ color: isReadOnly ? 'text.disabled' : 'primary.main', m: 'auto' }}>
                Importer une période
              </Typography>
              <AddButton
                variant="contained"
                onClick={uploadFile.onTrue}
                sx={{ minHeight: '43px' }}
                endIcon={<FontAwesome icon={faFileArrowUp} width={18} />}
                disabled={isReadOnly}
              >
                Importez une période
              </AddButton>
            </Grid>
          </Grid>
        ) : (
          <HolidayZoneDetails formData={formData} setFormData={setFormData} isReadOnly={isReadOnly} />
        )}

        <Grid item xs={12}>
          {!isReadOnly ? (
            <ActionButtons
              onSave={currentStep === 'import' ? handleContinue : () => setCurrentStep('import')}
              onCancel={onClose}
              mode={mode}
              onValidate={currentStep === 'import' ? undefined : handleSave}
              thirdButtonText="Enregistrer"
              secoundButtonText={currentStep === 'import' ? 'Continuer' : 'Retourner'}
            />
          ) : (
            <></>
          )}
        </Grid>
      </form>
      {uploadFile.value ?
        <MassUploadFile
          open={uploadFile.value}
          onClose={uploadFile.onFalse}
          type={TypeImport.VACANCE}
          withData={false}
          customBackendExport={handleExportHolidayTemplate}
          customUpload={handleUpload}
        /> : <></>}
    </FormContainer>
  );
}