'use client';

import React, { useEffect } from 'react'
import { useFormik } from 'formik'
import FormField from '@/shared/components/form/form-field'
import { FormFieldType, ModeType, TableColumn } from '@/shared/types/common'
import FormContainer from '@/layouts/form/form-container'
import { IIncident } from '@/shared/types/flottes/incident'
import TabbedForm from '@/shared/components/tabs/tabbed-form'
import SinistreDetails from '../components/sinistre-details'
import DocumentForm from '@/shared/components/documents/documents-form'
import { _interventionReport } from '@/shared/_mock/_documents'
import { incidentSchema } from '../utils/incident-schema'

interface IncidentFormProps {
  incident: IIncident
  mode: ModeType
  onSave: (updatedIncident: IIncident) => void
  onEdit: (updatedIncident: IIncident) => void
  onClose: () => void
  tableHead: TableColumn[]
  setHasUnsavedChanges?: (value: boolean) => void
  updateTabContent?: (tabId: string, newContent: IIncident) => void
  tabId?: string
}

export default function IncidentForm({
  incident,
  mode,
  onSave,
  onClose,
  onEdit,
  tableHead,
  setHasUnsavedChanges,
  updateTabContent,
  tabId,
}: IncidentFormProps) {
  const isReadOnly = mode === 'view'

  const formik = useFormik<IIncident>({
    initialValues: incident,
    validationSchema: incidentSchema,
    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<IIncident>) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof IIncident]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof IIncident]
          ? (formik.errors[field.name as keyof IIncident] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  )

  const tabs = [
    {
      label: "Sinistre",
      content: (
        <SinistreDetails
          renderField={renderField}
          mode={mode}
          onSave={() => {
            formik.validateForm().then((errors) => {
              formik.submitForm()
            })
          }}
          onClose={onClose}
          onEdit={() => onEdit(formik.values)}
          incident={formik.values}
          tableHead={tableHead}
        />
      ),
    },
    { 
      label: "Documents", 
      content: <DocumentForm documents={mode === "add" ? [] : _interventionReport} /> 
    },
  ]
  
  return (
    <FormContainer titre="Fiche Sinistre">
      <form onSubmit={formik.handleSubmit}>
        <TabbedForm tabs={tabs} />
      </form>
    </FormContainer>
  )
}
  