"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 { _REPAIRS_DOCUMENT_TYPES, INITIAL_REPAIRS_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"
import { _interventions } from "@/shared/_mock/flottes/_supplier"

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_REPAIRS_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={field.name === "typeIntervention" || isReadOnly}
    />
  )

  const tabs = [
    {
      label: "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} documentTypes={_REPAIRS_DOCUMENT_TYPES} />,
    },
  ]

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