"use client"

import { Grid, Typography } from "@mui/material"
import { useFormik } from "formik"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import FormContainer from "@/layouts/form/form-container"
import { type Candidat, type WorkingHours } from "@/shared/types/candidat"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { candidatFormFields } from "@/shared/sections/rh/salarie/utils/form-fields-candidat"
import ActionButtons from "@/shared/components/form/buttons-action"
import AvatarUploader from "@/shared/components/form/avatar-uploader"
import SalariePlanning from '../components/salarie-planning'
import SalarieCircuitsTable from '../components/salarie-circuits-table'
import { salarieSchema } from '../utils/salarie-schema'
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useEffect } from "react"
interface CandidatFormProps {
  candidat: Candidat
  mode: ModeType
  onSave: (updatedCandidat: Candidat) => void
  onEdit: (updatedCandidat: Candidat) => void
  onClose: (forceClose: boolean) => void
  updateTabContent: (tabId: string, newContent: Candidat) => void
  tabId: string
}

export default function CandidatForm({ candidat, mode, onSave, onClose, onEdit, updateTabContent, tabId }: CandidatFormProps) {
  const isReadOnly = mode === "view"

  const formik = useFormik<Candidat>({
    initialValues: candidat,
    validationSchema: salarieSchema,
    enableReinitialize: true,
    onSubmit: (values) => {
      onSave(values)
      onClose(true)
    },
  })

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

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


  const handlePlanningChange = (newWorkingHours: WorkingHours[]) => {
    formik.setFieldValue('workingHours', newWorkingHours)
  }

  const renderField = (field: FormFieldType<Candidat>) => {
    const isRequired = formik.values.type === 'chauffeur' &&
      (field.name === 'dureePermis' || field.name === 'numeroPermis')

    return (
      <FormField
      field={{
        ...field,
        required: isRequired || field.required,
      }}      
      value={formik.values[field.name as keyof Candidat]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof Candidat]
          ? field.name==="adresse" ? (formik.errors.adresse)?.["address"]
          : formik.errors[field.name as keyof Candidat] as string
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
    )
  }

  return (
    <FormContainer titre="Fiche Salarié">
      <ConditionalComponent isValid={isReadOnly}>

      <EditExportButtons
        onEdit={() => onEdit(formik.values)}
        onExport={() => void 0}
        tooltipTitle="Candidat"
      />
      </ConditionalComponent>
     
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          <Grid item xs={12}>
            <AvatarUploader onUpload={() => void 0} isReadOnly={isReadOnly} />
          </Grid>
          {candidatFormFields.map((field) => (
            <Grid
              item
              xs={12}
              sm={4}
              key={field.name}
            >
              {renderField(field)}
            </Grid>
          ))}

          {/* Only show Planning and Circuits sections for chauffeur type */}
          <ConditionalComponent isValid={formik.values.type === 'chauffeur'}>
            <>
              <Grid item xs={12}>
                <Typography
                  variant="h6"
                  sx={{
                    my: 2,
                    color: 'primary.main',
                    fontWeight: (theme) => theme.typography.fontWeightBold,
                  }}
                >
                  Disponibilité
                </Typography>
                <SalariePlanning
                  workingHours={formik.values.workingHours || []}
                  isReadOnly={isReadOnly}
                  onChange={handlePlanningChange}
                />
              </Grid>

              <Grid item xs={12}>
                <SalarieCircuitsTable />
              </Grid>
            </>
          </ConditionalComponent>

          <Grid item xs={12}>
            <ConditionalComponent isValid={!isReadOnly}>

            <ActionButtons 
              onSave={() => {
                formik.validateForm().then((errors) => {
                    formik.submitForm()
                })
              }} 
              onCancel={() => onClose(false)} 
              mode={mode} 
            />
            </ConditionalComponent>

          </Grid>
        </Grid>
      </form>
    </FormContainer>
  )
} 
