"use client"
import { useEffect, useCallback } from "react"
import React from "react"

import { Button } 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 { vacationFormFields } from "../utils/form-fields-attendance"
import { Box, Stack } from "@mui/system"
import type { IAttendanceSheet } from "@/shared/types/etablissement"
import { mainColor, outlinedColor } from "@/shared/components/table/styles"
import MultiSectionForm from "../components/multiSection-form"
import { useFormik } from "formik"
import { attendanceSheetSchema } from "../utils/attendance-validation"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import type { AttendanceTabContent } from "./attendance-list-view"
import { isEqual, type AttendanceUnion } from "../utils/attendance-utils"
import { AttendanceSheet } from "@/shared/types/attendance-sheet"

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

function AttendanceForm({ vacation, onClose, updateTabContent, tabId, updateTabAttendance }: AttendanceFormProps) {
  const { data, currentStep, attendance } = vacation

  const formik = useFormik<IAttendanceSheet>({
    initialValues: data,
    validationSchema: attendanceSheetSchema,
    onSubmit: (values) => {
      updateTabContent(tabId, {
        data: values,
        currentStep: "sheet",
        id: values.id,
        attendance: attendance || {},
      })
    },
    enableReinitialize: true,
  })

  const updateContent = useCallback(() => {
    if (updateTabContent && tabId) {
      const newContent = {
        data: formik.values,
        currentStep,
        id: formik.values.id,
        attendance: attendance || {},
      }

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

  useEffect(() => {
    updateContent()
  }, [updateContent])

  const handleValidate = useCallback(() => {
    formik.validateForm().then(() => {
      formik.submitForm()
    })
  }, [formik])

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

  const renderField = useCallback(
    (field: FormFieldType<IAttendanceSheet>) => {
      const error = formik.touched[field.name] && formik.errors[field.name]
      return (
        <FormField
          field={field}
          value={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],
  )

  return (
    <FormContainer sx={{ mb: 1, borderTopLeftRadius: "10px", pt: 4 }}>
      <ConditionalComponent
        isValid={currentStep === "form"}
        defaultComponent={
          <MultiSectionForm
            onReturn={handleReturn}
            onClose={(isSaved) => onClose(isSaved)}
            mode="edit"
            initialDepartement={formik.values.departmentName}
            updateTabAttendance={updateTabAttendance}
            tabId={tabId}
            attendance={attendance || {}}
          />
        }
      >
        <Box display="flex" justifyContent="center">
          <Box width="100%" maxWidth="500px">
            <form onSubmit={formik.handleSubmit}>
              <Stack spacing={5} alignItems="center">
                {vacationFormFields.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,
                    }}
                  >
                    Annuler
                  </Button>
                  <Button
                    variant="contained"
                    onClick={handleValidate}
                    disabled={!formik.values.departmentName || !formik.values.year || !formik.values.month}
                    sx={{
                      boxShadow: "none",
                      textTransform: "none",
                      ...mainColor,
                    }}
                  >
                    Valider
                  </Button>
                </Box>
              </Stack>
            </form>
          </Box>
        </Box>
      </ConditionalComponent>
    </FormContainer>
  )
}

export default React.memo(AttendanceForm)
