"use client"

import React, { useCallback, useEffect, useMemo } from "react"
import { Box, Stack, IconButton, Grid, Typography } from "@mui/material"
import { faFileExport, faPenToSquare } from "@fortawesome/free-solid-svg-icons"
import { iconButtonStyles, tabsBorder } from "@/shared/theme/css"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import type { IChauffeur } from "@/shared/types/chauffeur"
import FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import ActionButtons from "@/shared/components/form/buttons-action"
import JoursAttribuesInput from "@/shared/components/form/jours-attribues-input"
import { formFieldsChauffeur } from "../../../utils/form-fields-circuit"
import { useFormik } from "formik"
import { chauffeurSchema } from "../../../utils/circuit-validation"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

const TOOLTIP_TITLES = {
  edit: "Modifier chauffeur",
  export: "Exporter",
}

interface ChauffeurFormProps {
  chauffeur: IChauffeur
  mode: ModeType
  onSave: (updatedTrajet: IChauffeur) => void
  onEdit: (updatedTrajet: IChauffeur) => void
  onClose: () => void
  setHasUnsavedChanges: (value: boolean) => void
  updateTabContent: (tabId: string, content: IChauffeur) => void
  tabId: string
}

export default function NewChauffeurForm({ chauffeur, mode, onSave, onClose, onEdit, setHasUnsavedChanges, updateTabContent, tabId }: ChauffeurFormProps) {
  const isReadOnly = mode === "view"

  const formik = useFormik<IChauffeur>({
    initialValues: chauffeur,
    validationSchema: chauffeurSchema,
    onSubmit: (values) => {
      onSave(values)
      setHasUnsavedChanges(false)
      onClose()
    },
    enableReinitialize: true
  })

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

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

  const renderField = useCallback(
    (field: FormFieldType<IChauffeur>) => {
      const error = formik.touched[field.name] && formik.errors[field.name]
      return (
        <FormField
          field={field}
          value={formik.values[field.name]}
          onChange={(name, value) => formik.setFieldValue(name, value)}
          error={error ? String(formik.errors[field.name]) : undefined}
          isReadOnly={isReadOnly}
          onBlur={formik.handleBlur}
        />
      )
    },
    [formik, isReadOnly],
  )

  const memoizedFormFields = useMemo(
    () => (
      <>
        {formFieldsChauffeur.map((field) =>
          field.name === "joursAttribues" ? (
            <React.Fragment key={field.name}>
              <Grid item sm={12} md={5} key={field.name}>
                <Typography sx={{ color: (theme) => theme.palette.primary.main }}>{field.label}</Typography>
                <JoursAttribuesInput
                  initialJours={formik.values[field.name]}
                  onChange={(updatedJours) => formik.setFieldValue(field.name, updatedJours)}
                  isReadOnly={isReadOnly}
                />
                <ConditionalComponent isValid={!!formik.touched[field.name] && !!formik.errors[field.name]}>
                  <Typography color="error" variant="caption">
                    {String(formik.errors[field.name])}
                  </Typography>
                </ConditionalComponent>
              </Grid>
              <Grid item xs={12} sm={3} sx={{ display: { xs: "none", sm: "block" } }} />
            </React.Fragment>
          ) : (
            <Grid
              sx={{
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
              }}
              item
              xs={12}
              sm={4}
              key={field.name}
            >
              {renderField(field)}
            </Grid>
          ),
        )}
      </>
    ),
    [formik, isReadOnly, renderField],
  )

  const handleSave = () => {
    formik.validateForm().then((errors) => {
      formik.submitForm()
    })
  }

  return (
    <Box pt={isReadOnly ? 0 : 4} sx={tabsBorder}>
      <ConditionalComponent isValid={isReadOnly}>
        <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" gap="8px" py={1}>
          <CustomTooltip title={TOOLTIP_TITLES.edit} arrow>
            <IconButton onClick={() => onEdit(chauffeur)} size="small" sx={iconButtonStyles}>
              <FontAwesome icon={faPenToSquare} width={16} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title={TOOLTIP_TITLES.export} arrow>
            <IconButton size="small" sx={iconButtonStyles}>
              <FontAwesome icon={faFileExport} width={16} />
            </IconButton>
          </CustomTooltip>
        </Stack>
      </ConditionalComponent>

      <form onSubmit={formik.handleSubmit}>
        <Grid container spacing={6}>
          {memoizedFormFields}
        </Grid>
        <ConditionalComponent isValid={!isReadOnly}>
          <Grid item xs={12}>
            <ActionButtons onSave={handleSave} onCancel={onClose} />
          </Grid>
        </ConditionalComponent>
      </form>
    </Box>
  )
}
