// components/attendance-new-view.tsx
"use client";

import { useEffect, useCallback, useState } from "react";
import React from "react";
import { Button, CircularProgress, Alert } from "@mui/material";
import FormField from "@/shared/components/form/form-field";
import type { FormFieldType } from "@/shared/types/common";
import FormContainer from "@/layouts/form/form-container";
import { Box, Stack } from "@mui/system";
import MultiSectionForm from "../components/multiSection-form";
import { useFormik } from "formik";
import { attendanceSheetSchema } from "../utils/attendance-validation";
import ConditionalComponent from "@/shared/components/table/ConditionalComponent";
import { isEqual, type AttendanceUnion } from "../utils/attendance-utils";
import { AttendanceSheet, Circuit, RouteSheetDTO } from "@/shared/types/attendance-sheet";
import { mainColor, outlinedColor } from "@/shared/components/table/styles";
import { useInfrastructureStore } from "@/shared/api/stores/admin-service/infrastructureStore";
import { useSnackbar } from "notistack";
import { useAttendanceSheetStore } from "@/shared/api/stores/attendanceSheetStore";
import { vacationFormFields } from "../utils/form-fields-attendance";
import { AttendanceTabContent } from "../hooks/use-attendance-tabs"; // Importer depuis le hook

interface AttendanceFormProps {
  attendance: AttendanceTabContent;
  onClose: (isSaved: boolean) => void;
  updateTabContent: (tabId: string, newContent: AttendanceTabContent) => void;
  updateTabAttendance: (tabId: string, attendance: AttendanceUnion) => void;
  tabId: string;
}

function AttendanceForm({ attendance, onClose, updateTabContent, tabId, updateTabAttendance }: AttendanceFormProps) {
  const { data, currentStep, attendance: attendanceData } = attendance;
  const { enqueueSnackbar } = useSnackbar();
  const { createAttendanceSheet, fetchCircuits, circuits, loading, error } = useAttendanceSheetStore();
  const { fetchDepartmentNames, departmentNames, getDepartmentById } = useInfrastructureStore();

  const [departmentName, setDepartmentName] = useState<string>('');
  const [departmentOptions, setDepartmentOptions] = useState<{ value: string; label: string }[]>([]);
  const [circuitOptions, setCircuitOptions] = useState<{ value: string; label: string }[]>([]);
  const [localRouteSheets, setLocalRouteSheets] = useState<RouteSheetDTO[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    fetchDepartmentNames();
    fetchCircuits();
  }, [fetchDepartmentNames, fetchCircuits]);

  useEffect(() => {
    if (departmentNames.length > 0) {
      setDepartmentOptions(
        departmentNames.map((dept: any) => ({
          value: String(dept.id),
          label: dept.name,
        }))
      );
    }
  }, [departmentNames]);

  useEffect(() => {
    if (circuits.length > 0) {
      setCircuitOptions(
        circuits.map((circuit: Circuit) => ({
          value: circuit.id,
          label: circuit.titled,
        }))
      );
    }
  }, [circuits]);

  const formik = useFormik<AttendanceSheet>({
    initialValues: {
      ...data,
      circuitId: data.circuitId || '',
      departmentId: data.departmentId || 0,
      year: data.year || 0,
      month: data.month || '1',
    },
    validationSchema: attendanceSheetSchema,
    onSubmit: async (values) => {
      setIsSubmitting(true);
      try {
        const routeSheets = await createAttendanceSheet({
          circuitId: values.circuitId,
          departmentId: Number(values.departmentId),
          year: Number(values.year),
          month: values.month,
        });
        setLocalRouteSheets(routeSheets);
        const attendanceSheetId = routeSheets[0]?.id || values.id;
        const newTabContent: AttendanceTabContent = {
          id: attendanceSheetId,
          data: {
            ...values,
            id: attendanceSheetId
          },
          currentStep: "sheet",
          attendance: attendanceData || {},
          routeSheets,
        };
        updateTabContent(tabId, newTabContent);

        enqueueSnackbar('Feuille de présence créée avec succès', { variant: 'success' });
      } catch (err: any) {
        console.error('Erreur lors de la création:', err);
        enqueueSnackbar(err.message || 'Échec de la création de la feuille de présence', { variant: 'error' });
      } finally {
        setIsSubmitting(false);
      }
    },
    enableReinitialize: true,
  });

  useEffect(() => {
    const fetchDepartmentName = async () => {
      if (formik.values.departmentId) {
        const department = await getDepartmentById(String(formik.values.departmentId));
        if (department) {
          setDepartmentName(department.name);
        }
      }
    };
    fetchDepartmentName();
  }, [formik.values.departmentId, getDepartmentById]);

  const handleFormChange = useCallback(() => {
    if (updateTabContent && tabId && currentStep === 'form') {
      const newContent: AttendanceTabContent = {
        id: formik.values.id,
        data: formik.values,
        currentStep,
        attendance: attendanceData || {},
        routeSheets: localRouteSheets,
      };

      if (!isEqual(newContent, attendance)) {
        updateTabContent(tabId, newContent);
      }
    }
  }, [formik.values, updateTabContent, tabId, currentStep, attendanceData, attendance, localRouteSheets]);

  useEffect(() => {
    handleFormChange();
  }, [formik.values, handleFormChange]);

  const handleValidate = useCallback(() => {
    formik.validateForm().then((errors) => {
      if (Object.keys(errors).length === 0) {
        formik.submitForm();
      } else {
        formik.setTouched({
          circuitId: true,
          departmentId: true,
          year: true,
          month: true,
        });
      }
    });
  }, [formik]);

  const handleReturn = useCallback(() => {
    const newContent: AttendanceTabContent = {
      id: formik.values.id,
      data: formik.values,
      currentStep: "form",
      attendance: attendanceData || {},
      routeSheets: localRouteSheets,
    };
    updateTabContent(tabId, newContent);
  }, [formik.values, updateTabContent, tabId, attendanceData, localRouteSheets]);

  const renderField = useCallback(
    (field: FormFieldType<AttendanceSheet>) => {
      const error = formik.touched[field.name] && formik.errors[field.name];
      return (
        <FormField
          field={field}
          value={
            field.name === 'departmentId' || field.name === 'circuitId'
              ? String(formik.values[field.name])
              : formik.values[field.name]
          }
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={error ? String(formik.errors[field.name]) : undefined}
          isReadOnly={false}
          onBlur={formik.handleBlur}
        />
      );
    },
    [formik]
  );

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
        <Alert severity='error'>Erreur : {error}</Alert>
      </Box>
    );
  }

  return (
    <FormContainer sx={{ mb: 1, borderTopLeftRadius: "10px", pt: 4 }}>
      <ConditionalComponent
        isValid={currentStep === "form"}
        defaultComponent={
          <MultiSectionForm
            onReturn={handleReturn}
            onClose={(isSaved) => onClose(isSaved)}
            mode="edit"
            vacation={{ ...formik.values, routeSheets: localRouteSheets }}
            initialDepartement={departmentName}
            updateTabAttendance={updateTabAttendance}
            tabId={tabId}
            attendance={attendanceData || {}}
          />
        }
      >
        <Box display="flex" justifyContent="center">
          <Box width="100%" maxWidth="500px">
            <form onSubmit={formik.handleSubmit}>
              <Stack spacing={5} alignItems="center">
                {vacationFormFields(departmentOptions, circuitOptions).map((field) => (
                  <Box key={field.name} width="100%">
                    {renderField(field)}
                  </Box>
                ))}

                <Box width="100%" display="flex" justifyContent="flex-end" gap={2}>
                  <Button
                    variant="outlined"
                    onClick={() => onClose(false)}
                    sx={{
                      textTransform: "none",
                      ...outlinedColor,
                    }}
                    disabled={isSubmitting}
                  >
                    Annuler
                  </Button>
                  <Button
                    variant="contained"
                    type="submit"
                    onClick={handleValidate}
                    disabled={
                      isSubmitting ||
                      !formik.values.circuitId ||
                      !formik.values.departmentId ||
                      !formik.values.year ||
                      !formik.values.month
                    }
                    sx={{
                      boxShadow: "none",
                      textTransform: "none",
                      ...mainColor,
                    }}
                  >
                    {isSubmitting ? <CircularProgress size={20} /> : "Valider"}
                  </Button>
                </Box>
              </Stack>
            </form>
          </Box>
        </Box>
      </ConditionalComponent>
    </FormContainer>
  );
}

export default React.memo(AttendanceForm);