"use client"

import { useCallback, 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, IPassengerList, TransportSchedule } from "@/shared/types/passenger"
import { INITIAL_REPRESENTATIVE_DATA } from "@/shared/_mock/_represantative"
import { useFormikContext } from "formik"
import ActionButtons from "@/shared/components/form/buttons-action"
import { enqueueSnackbar } from "notistack"
import { checkScheduleConflict } from "../avenants-horaires/utils/converters"
import UnifiedRepresentantForm from "./unified-representantForm"

interface RepresentantTabsProps {
  withContact?: boolean
  scheduleMode?: ModeType
  onSave: () => void
  loading?: boolean
  onClose: () => void
  mode: ModeType
  onEdit: (passenger: IPassengerList) => void
}

export default function RepresentantTabs({
  withContact,
  scheduleMode,
  onSave,
  loading,
  onClose,
  mode,
  onEdit,
}: RepresentantTabsProps) {
  const formik = useFormikContext<IPassengerList>()
  const representatives = useMemo(() => formik.values.representatives || [], [formik.values.representatives])
  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 handleAddTab = () => {
    const newRepresentative = { ...INITIAL_REPRESENTATIVE_DATA }
    const updatedRepresentatives = [...representatives, newRepresentative]

    formik.setFieldValue("representatives", 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(`representatives[${tabId}].transportSchedulesRepresentative`, undefined)
        }
      }

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

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

  return (
    <Box sx={{ width: "100%", display: "flex", flexDirection: "column" }}>
      <ConditionalComponent isValid={!!withContact}>
        <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="standard"
              data={tab.data}
              isReadOnly={isReadOnly}
              onChange={(newData) => handleFormChange(tab.id, newData)}
              withContact={withContact}
              tabIndex={tab.id}
              mode={mode}
            />
          </MultiSectionContainer>
        ))}
        <ConditionalComponent isValid={mode !== "view"}>
          <Grid item xs={12} sx={{ mt: 2 }}>
            <ActionButtons onSave={onSave} onCancel={onClose} mode={mode} loading={loading} />
          </Grid>
        </ConditionalComponent>
      </Grid>
    </Box>
  )
}
