"use client"
import { Grid } from "@mui/material"
import { useFormik } from "formik"
import type { IFormulaire } from "@/shared/types/candidature"
import FormField from "@/shared/components/form/form-field"
import { formFieldsFormulaire } from "@/shared/sections/rh/recrutement/candidatures/utils/form-fields-formulaire"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { type TableColumn, TableType } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import ActionButtons from "@/shared/components/form/buttons-action"
import { formulaireSchema } from "@/shared/sections/rh/recrutement/candidatures/utils/formulaire-schema"
import { useEffect } from "react"

interface FormulaireDetailsFormProps {
  formulaire: IFormulaire
  mode: "view" | "edit" | "new" | "add" | "copy"
  onSave: (formulaire: IFormulaire) => void
  onClose: (forceClose: boolean) => void
  onEdit: (formulaire: IFormulaire) => void
  tableHead: TableColumn[]
  updateTabContent: (tabId: string, newContent: IFormulaire) => void
  tabId: string
}

export default function FormulaireDetailsForm({
  formulaire,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  updateTabContent,
  tabId,
}: FormulaireDetailsFormProps) {
  const isViewMode = mode === "view"
  const isNewMode = mode === "new" || mode === "add"

  // Initialisation de Formik avec Yup pour la validation
  const formik = useFormik<IFormulaire>({
    initialValues: formulaire,
    validationSchema: formulaireSchema,
    enableReinitialize: true, // Permet de réinitialiser le formulaire quand les props changent
    onSubmit: (values) => {
      onSave(values)
      onClose(true)
    },
  })

  const handleEditClick = () => {
    onEdit(formulaire)
  }

  useEffect(() => {
    if (updateTabContent && tabId && mode !== "view") {
      const timer = setTimeout(() => {
        updateTabContent(tabId, formik.values)
      }, 300)

      return () => {
        clearTimeout(timer)
      }
    }
  }, [formik.values, updateTabContent, tabId, mode])

  return (
    <FormContainer titre={isNewMode ? "Nouveau formulaire" : `Formulaire: ${formulaire.nom}`}>
      <ConditionalComponent isValid={isViewMode}>
        <EditExportButtons
          onEdit={handleEditClick}
          onExport={() => void 0}
          tooltipTitle={TableType.Candidature}
          dataRow={formulaire}
          tableHead={tableHead}
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={3}>
          {formFieldsFormulaire.map((field) => (
            <Grid item xs={12} md={field.name === "description" ? 12 : 6} key={String(field.name)}>
              <FormField
                field={field}
                value={formik.values[field.name] || ""}
                onChange={(name, value) => formik.setFieldValue(name, value)}
                error={
                  formik.touched[field.name] && formik.errors[field.name]
                    ? (formik.errors[field.name] as string)
                    : undefined
                }
                onBlur={formik.handleBlur}
                isReadOnly={isViewMode}
              />
            </Grid>
          ))}

          <Grid item xs={12}>
            <ConditionalComponent isValid={!isViewMode}>
                <ActionButtons onSave={formik.submitForm} onCancel={() => onClose(false)} mode={mode} />
            </ConditionalComponent>
          </Grid>
        </Grid>
      </form>
    </FormContainer>
  )
}
