"use client"

import { Grid, Typography } from "@mui/material"
import { useFormik } from "formik"
import { useRef, useEffect, useCallback } from "react"
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 SalarieTripsTable from '../components/salarie-trips-table'
import WorkingHoursSelector from '../components/working-hours-selector'
import { useWorkingHours } from '../hooks/use-working-hours'
import type { WorkingHoursSlot } from '@/shared/types/working-hours'
import { salarieSchema } from '../utils/salarie-schema'
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useEmployeeExport } from '../hooks/use-employee-export'
import { useDepartments } from '../hooks/use-departments'

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 avatarUploaderRef = useRef<{ resetPreview: () => void }>(null)


  const {
    workingHoursSlots,
    setWorkingHoursSlots,
    saveWorkingHours
  } = useWorkingHours(candidat.id)

  const { exportAndDownload } = useEmployeeExport()
  const { departments, loading: departmentsLoading } = useDepartments()


  const formik = useFormik<Candidat>({
    initialValues: candidat,
    validationSchema: salarieSchema,
    enableReinitialize: true,
    onSubmit: async (values) => {
      try {
        await onSave(values);


        if (workingHoursSlots.length > 0 && values.id) {
          await saveWorkingHours(workingHoursSlots, values.id);
        }


        if (avatarUploaderRef.current && avatarUploaderRef.current.resetPreview) {
          avatarUploaderRef.current.resetPreview();
        }

        onClose(true);
      } catch (error) {
        console.error('Error saving employee:', error);

      }
    },
  })

  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 handleWorkingHoursChange = useCallback((newWorkingHoursSlots: WorkingHoursSlot[]) => {
    setWorkingHoursSlots(newWorkingHoursSlots)
  }, [])

  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={async () => {
            try {
              await exportAndDownload({
                employeeIds: candidat.id && candidat.id !== 'new' ? [parseInt(candidat.id)] : undefined,
                userId: 1,
              });
            } catch (error) {
              console.error('Export failed:', error);
            }
          }}
          tooltipTitle="Candidat"
        />
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
          <Grid item xs={12}>
            <AvatarUploader
              ref={avatarUploaderRef}
              onUpload={(file: File) => {
                console.log('AvatarUploader onUpload called with file:', file.name, file.type, file.size);
                formik.setFieldValue('profilePictureFile', file);
                console.log('Form field profilePictureFile set to:', file);
              }}
              isReadOnly={isReadOnly}
              currentImage={formik.values.profilePictureUrl}
            />
          </Grid>
          {candidatFormFields.map((field) => {
            // Special handling for department field
            if (field.name === 'departement') {
              const departmentField = {
                ...field,
                options: departments.map(dept => ({
                  value: dept.name,
                  label: dept.name
                }))
              };
              return (
                <Grid
                  item
                  xs={12}
                  sm={4}
                  key={field.name}
                >
                  {renderField(departmentField)}
                </Grid>
              );
            }

            return (
              <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}>
                <WorkingHoursSelector
                  workingHours={workingHoursSlots}
                  onChange={handleWorkingHoursChange}
                  disabled={isReadOnly}
                  employeeId={formik.values.id && formik.values.id !== 'new' ? formik.values.id : undefined}
                />
              </Grid>

              <Grid item xs={12}>
                <SalarieTripsTable
                  driverId={
                    formik.values.id &&
                      formik.values.id !== 'new' &&
                      !isNaN(parseInt(formik.values.id))
                      ? parseInt(formik.values.id)
                      : undefined
                  }
                />
              </Grid>
            </>
          </ConditionalComponent>

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

              <ActionButtons
                onSave={() => {
                  formik.validateForm().then((errors) => {

                    formik.handleSubmit();
                  })
                }}
                onCancel={() => onClose(false)}
                mode={mode}
              />
            </ConditionalComponent>

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