"use client"

import React, { useCallback, useEffect, useMemo, useState } 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 FormField from "@/shared/components/form/form-field"
import type { FormFieldType, ModeType } from "@/shared/types/common"
import ActionButtons from "@/shared/components/form/buttons-action"
import { getFormFieldsTripDriverAssignment, Option } from "../../../utils/form-fields-circuit"
import { useFormik } from "formik"
import { chauffeurSchema } from "../../../utils/circuit-validation"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useTripDriverAssignmentStore } from "@/shared/api/stores/circuit-service/tripDriverAssignmentStore"
import { ITripDriverAssignment } from "@/shared/types/circuit"
import { enqueueSnackbar } from "notistack"
import { useDriverStore } from "@/shared/api/stores/driverStore"
import TransportScheduleField from "@/shared/components/form/transport-schedule-field"
import { transformFromWeekSchedule, transformToWeekSchedule } from "../../../utils/schedule-converters"

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

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

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

  const { addTripDriverAssignment, loading, updateTripDriverAssignment } = useTripDriverAssignmentStore();
  const { getActiveDrivers } = useDriverStore();
  const [driverOptions, setDriverOptions] = useState<Option[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      const drivers = await getActiveDrivers();
      setDriverOptions(drivers.map((driver) => ({
        value: driver.id.toString(),
        label: driver.name
      })));
    };
    
    fetchData();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleFormSubmit = async (values: ITripDriverAssignment) => {
    try {
      if (isEditMode) {
        await updateTripDriverAssignment(values);
        enqueueSnackbar("Chauffeur modifié avec succès", { variant: 'success' });
        markTabAsSaved(tabId, values)
        formik.resetForm({ values })
        } else if (mode === 'add' || mode === 'copy') {
        const { id, createdAt, updatedAt, ...valuesWithoutId } = values;
        await addTripDriverAssignment(valuesWithoutId as ITripDriverAssignment);
        enqueueSnackbar("Chauffeur ajouté avec succès", { variant: 'success' });
        onClose(true);
      }
    } catch (error: any) {
      enqueueSnackbar(error.message || "Erreur lors de l'ajout de l'affectation chauffeur-trajet", { variant: 'error' });
    }
  };

  const formik = useFormik<ITripDriverAssignment>({
    initialValues: chauffeur,
    validationSchema: chauffeurSchema,
    onSubmit: (values) => {
      handleFormSubmit(values)
    },
    enableReinitialize: true
  })

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

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

  useEffect(() => {
    if (formik.dirty && !hasUnsavedChanges) {
      formik.resetForm();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [hasUnsavedChanges])

  const renderField = useCallback(
    (field: FormFieldType<ITripDriverAssignment>) => {
      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(
    () => (
      <>
        {getFormFieldsTripDriverAssignment([], driverOptions).map((field) =>
          field.name === "weeklyAssignmentSchedule" ? (
            <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>
                <TransportScheduleField
                  initialSchedules={transformToWeekSchedule(formik.values[field.name])}
                  onChange={(updatedSchedules) => formik.setFieldValue(field.name, transformFromWeekSchedule(updatedSchedules))}
                  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(false)} />
          </Grid>
        </ConditionalComponent>
      </form>
    </Box>
  )
}
