"use client"

import { useCallback, useEffect, useMemo } from "react"
import { Box, Grid, IconButton } from "@mui/material"
import FontAwesome from "@/shared/components/fontawesome"
import { faPenToSquare, faPlusCircle } from "@fortawesome/free-solid-svg-icons"
import { iconButtonStyles } from "@/shared/theme/css"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import type { ModeType } from "@/shared/types/common"
import MultiSectionContainer from "@/shared/components/form/multiForm-container"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import type { Representative } from "@/shared/types/passenger"
import { INITIAL_REPRESENTATIVE_DATA } from "@/shared/_mock/_represantative"
import { useFormikContext } from "formik"
import { enqueueSnackbar } from "notistack"
import { AmendmentPassengerDetails } from "@/shared/types/ammendment-passenger"
import { usePassengerStore } from "@/shared/api/stores/passengerStore"
import { checkScheduleConflict } from "../utils/converters"
import UnifiedRepresentantForm from "../../representant/unified-representantForm"

interface AvenantRepresentantProps {
  withContact?: boolean
  scheduleMode?: ModeType
  onSave: () => void
  loading?: boolean
  onClose: () => void
  mode: ModeType
  onEdit: (passenger: AmendmentPassengerDetails) => void
  passengerId: string
}

export default function   AvenantRepresentant({
  passengerId,
  withContact,
  scheduleMode,
  onSave,
  loading,
  onClose,
  mode,
  onEdit,
}: AvenantRepresentantProps) {
  const { getRepresentativesByPassengerId, loading: loadingRepresentatives } = usePassengerStore();
  const formik = useFormikContext<AmendmentPassengerDetails>()
  const representatives = useMemo(() => formik.values.amendmentRepresentatives || [], [formik.values.amendmentRepresentatives])
  useEffect(() => {
    if (
      mode === "add" &&
      representatives.length === 0 &&
      passengerId 
    ) {
      getRepresentativesByPassengerId(passengerId).then((reps) => {
        if (reps && reps.length > 0) {
          formik.setFieldValue("amendmentRepresentatives", reps);
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mode, representatives.length, passengerId]);

  const isReadOnly = mode === "view"

  const tabs = useMemo(() => {
    if (representatives.length > 0) {
      return representatives.map((rep, index) => ({
        id: index,
        label: `Adresse ${index + 1}`,
        data: rep,
      }))
    }
    return [
      {
        id: 0,
        label: "Adresse 1",
        data: { ...INITIAL_REPRESENTATIVE_DATA },
      },
    ]
  }, [representatives])
  
  const handleTabClose = useCallback((event: React.MouseEvent, tabId: number) => {
    event.stopPropagation();
    
    const updatedRepresentatives = representatives.filter((_, index) => index !== tabId);
    formik.setFieldValue('amendmentRepresentatives', updatedRepresentatives);
  }, [representatives, formik]);

  const handleAddTab = () => {
    const newRepresentative = { ...INITIAL_REPRESENTATIVE_DATA }
    const updatedRepresentatives = [...representatives, newRepresentative]

    formik.setFieldValue("amendmentRepresentatives", updatedRepresentatives)
  }

  const handleFormChange = useCallback(
    (tabId: number, newData: Partial<Representative>) => {
      if (newData.transportSchedulesRepresentative) {
        const { hasConflict, conflictDetails } = checkScheduleConflict(tabId, newData.transportSchedulesRepresentative, representatives)
        if (hasConflict) {
          const errorMessage = `Conflit de planning détecté:\n${conflictDetails.join("\n")}`
          enqueueSnackbar(errorMessage, { variant: 'warning' });
          return
        } else {
          formik.setFieldError(`amendmentRepresentatives[${tabId}].transportSchedulesRepresentative`, undefined)
        }
      }

      const updatedRepresentatives = [...representatives]
      updatedRepresentatives[tabId] = { ...updatedRepresentatives[tabId], ...newData }

      formik.setFieldValue("amendmentRepresentatives", updatedRepresentatives)
    },
    [representatives, formik, checkScheduleConflict],
  )

  return (
    <Box sx={{ width: "100%", display: "flex", flexDirection: "column" }}>
      <ConditionalComponent isValid={mode === 'add'}>
        <Box sx={{ display: "flex", justifyContent: "flex-end", mb: 1, gap: 1 }}>
          <ConditionalComponent isValid={isReadOnly}>
            <CustomTooltip title={`Modifier Usager`} arrow>
              <IconButton onClick={() => onEdit(formik.values)} size="small" sx={iconButtonStyles}>
                <FontAwesome icon={faPenToSquare} width={16} />
              </IconButton>
            </CustomTooltip>
          </ConditionalComponent>
          <CustomTooltip title="Ajouter Adresse" arrow>
            <IconButton sx={{ ...iconButtonStyles }} onClick={handleAddTab}>
              <FontAwesome icon={faPlusCircle} width={18} />
            </IconButton>
          </CustomTooltip>
        </Box>
      </ConditionalComponent>

      <Grid container spacing={4}>
        {tabs.map((tab) => (
          <MultiSectionContainer
            key={tab.id}
            id={tab.id}
            title="Adresse"
            greyBg={!withContact && scheduleMode != "add"}
          >
            <UnifiedRepresentantForm
              key={tab.id}
              variant="amendment"
              data={tab.data}
              isReadOnly={isReadOnly || mode === "edit"}
              onChange={(newData) => handleFormChange(tab.id, newData)}
              withContact={withContact}
              tabIndex={tab.id}
              mode={mode}
              handleTabClose={handleTabClose}
            />
          </MultiSectionContainer>
        ))}
      </Grid>
    </Box>
  )
}
