"use client"

import type React from "react"
import { useEffect, useRef } from "react"
import { Grid, IconButton, InputAdornment } from "@mui/material"
import { centerFlexColumn, StyledTextField } from "@/shared/theme/css"
import FormField from "@/shared/components/form/form-field"
import { TableColumn, TableType, type FormFieldType, type ModeType } from "@/shared/types/common"
import type { IDriverAbsence } from "@/shared/types/driver-absence"
import FormContainer from "@/layouts/form/form-container"
import ActionButtons from "@/shared/components/form/buttons-action"
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { formFieldsDriverAbsence } from "../utils/form-fields-absence"
import { useResponsive } from "@/hooks"
import { faPaperclip } from "@fortawesome/free-solid-svg-icons"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { useFormik } from "formik"
import { driverAbsenceValidationSchema } from "../utils/driver-absence-validation"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface AbsenceFormProps {
  absence: IDriverAbsence
  mode: ModeType
  onSave: (updatedAbsence: IDriverAbsence) => void
  onEdit: (updatedAbsence: IDriverAbsence) => void
  onClose: (forceClose: boolean) => void
  isTraiteAbsence?: boolean
  tableHead: TableColumn[];
  updateTabContent?: (tabId: string, content: IDriverAbsence) => void;
  tabId?: string;
}

export default function AbsenceDriverForm({
  absence,
  mode,
  onSave,
  onClose,
  onEdit,
  isTraiteAbsence,
  tableHead,
  updateTabContent,
  tabId
}: AbsenceFormProps) {
  const isBetweenSmAndLg = useResponsive("between", "sm", "lg")
  const fileInputRef = useRef<HTMLInputElement>(null)
  const isReadOnly = mode === "view"

  const formik = useFormik<IDriverAbsence>({
    initialValues: absence,
    validationSchema: driverAbsenceValidationSchema,
    onSubmit: (values) => {
      onSave(values)
      onClose(true)
    },
  })

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

  const handleIconClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click()
    }
  }

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      formik.setFieldValue('justificatif', file.name)
    }
  }

  const renderField = (field: FormFieldType<IDriverAbsence>) => {
    if (field.name === "justificatif") {
      const error = formik.touched[field.name] && formik.errors[field.name]
      return (
        <StyledTextField
          isSmallScreen={isBetweenSmAndLg}
          fullWidth
          name={field.name}
          InputLabelProps={{
            shrink: true,
          }}
          value={formik.values[field.name] || ""}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={!!error}
          helperText={error ? String(formik.errors[field.name]) : undefined}
          label={field.label}
          placeholder={field.placeholder}
          sx={{
            ...(isReadOnly && {
              '& .MuiInputBase-root': {
                backgroundColor: '#f5f5f5',
                cursor: 'not-allowed',
              },
              '& .MuiInputBase-input': {
                cursor: 'not-allowed',
                color: 'text.disabled',
              }
            })
          }}
          InputProps={{
            readOnly: isReadOnly,
            endAdornment: (
              <InputAdornment position="end" >
                <CustomTooltip title="Importer la justification" arrow>
                <IconButton onClick={handleIconClick} disabled={isReadOnly}> 
                <FontAwesome
                  icon={faPaperclip}
                  sx={{
                    color: isReadOnly ? 'text.disabled' : "primary.main",
                    width: isBetweenSmAndLg ? 16 : 18,
                  }}
                />
                </IconButton>
              </CustomTooltip>
              </InputAdornment>
            ),
          }}
        />
      )
    }
    return (
      <FormField
        field={field}
        value={formik.values[field.name]}
        onChange={(name, value) => formik.setFieldValue(name, value)}
        error={
          formik.touched[field.name]
            ? (formik.errors[field.name] as string | undefined)
            : undefined
        }
        onBlur={formik.handleBlur}
        isReadOnly={field.name === "department" || field.name === "chauffeurAffecte" ? true : isReadOnly}
      />
    )
  }

  return (
    <FormContainer titre="Fiche d'absence chauffeur">
      <ConditionalComponent isValid={isReadOnly}>
        <EditExportButtons
          onEdit={isTraiteAbsence ? undefined : () => onEdit(absence)}
          onExport={() => void 0}
          tooltipTitle={TableType.absence}
          dataRow={absence}
          tableHead={tableHead}
        />
      </ConditionalComponent>
      
      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={4}>
        {formFieldsDriverAbsence.filter((field) => 
          !(!isTraiteAbsence && field.name === "validePar" && mode !== "edit")
        ).map((field) => (
          <Grid item xs={12} sm={4} sx={centerFlexColumn} key={field.name}>
            {renderField(field)}
          </Grid>
        ))}
          <input type="file" ref={fileInputRef} style={{ display: "none" }} onChange={handleFileUpload} />
          <Grid item xs={12} >
            <ConditionalComponent isValid={mode !== "view"}>
              <ActionButtons 
                onSave={() => {
                  formik.validateForm().then((errors) => {
                    formik.submitForm();
                  });
                }} 
                onCancel={() => onClose(false)} 
                mode={mode} 
              />
            </ConditionalComponent>
          </Grid>
        </Grid>
      </form>
    </FormContainer>
  )
}
