"use client"

import { useEffect } from "react"
import { useFormik } from "formik"
import type { IIntervention } from "@/shared/types/flottes/intervention"
import FormContainer from "@/layouts/form/form-container"
import TabbedForm from "@/shared/components/tabs/tabbed-form"
import type { FormFieldType, ModeType, TableColumn } from "@/shared/types/common"
import FormField from "@/shared/components/form/form-field"
import { INITIAL_INTERVENTION_DATA } from "@/shared/_mock/flottes/_intervention"
import InterventionDetails from "../components/intervention-details"
import DocumentForm from "@/shared/components/documents/documents-form"
import { _interventionReport } from "@/shared/_mock/_documents"
import { interventionSchema } from "../utils/intervention-schema"

interface InterventionFormProps {
  intervention?: IIntervention
  mode: ModeType
  onSave: (updatedIntervention: IIntervention) => void
  onEdit: (updatedIntervention: IIntervention) => void
  onClose: () => void
  tableHead: TableColumn[]
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: IIntervention) => void
  tabId?: string
}

export default function InterventionForm({
  intervention = INITIAL_INTERVENTION_DATA,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: InterventionFormProps) {
  const isReadOnly = mode === "view"

  const formik = useFormik<IIntervention>({
    initialValues: intervention,
    validationSchema: interventionSchema,
    onSubmit: (values) => {
      onSave(values)
      if (setHasUnsavedChanges) setHasUnsavedChanges(false)
      onClose()
    },
  })

  useEffect(() => {
    if (updateTabContent && tabId && (mode !== "view")) {
      updateTabContent(tabId, formik.values)
    }
  }, [formik.values, updateTabContent, tabId, mode])

  const renderField = (field: FormFieldType<IIntervention>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof IIntervention]}
      onChange={(name, value) => {
        formik.setFieldValue(name, value)
      }}
      error={
        formik.touched[field.name as keyof IIntervention]
          ? (formik.errors[field.name as keyof IIntervention] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  )

  const tabs = [
    {
      label: "Entretien/Réparation",
      content: (
        <InterventionDetails
          renderField={renderField}
          mode={mode}
          onSave={() => {
            formik.validateForm().then(() => {
              formik.submitForm()
            })
          }}
          onClose={onClose}
          onEdit={() => onEdit(formik.values)}
          intervention={formik.values}
          tableHead={tableHead}
        />
      ),
    },
    {
      label: "Documents",
      content: <DocumentForm documents={mode === "add" ? [] : _interventionReport} />,
    },
  ]

  return (
    <FormContainer titre="Fiche Entretien/Réparation">
      <form onSubmit={formik.handleSubmit}>
        <TabbedForm tabs={tabs} />
      </form>
    </FormContainer>
  )
}
