'use client';

import React, { useCallback, useState, useMemo } from 'react';
import { Box, Grid, IconButton } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { 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 } from '@/shared/types/passenger';
import RepresentantForm from '@/shared/sections/usager/components/usager-form/representant/representant-form';
import { INITIAL_REPRESENTATIVE_DATA } from '@/shared/_mock/_represantative';
import { useFormikContext } from 'formik';

interface RepresentantTabsProps {
  withContact?: boolean;
  scheduleMode?: ModeType;
  onSave?: () => void;
  loading?: boolean;
}

export default function RepresentantTabs({ withContact, scheduleMode, onSave, loading }: RepresentantTabsProps) {
  const [value, setValue] = useState(0);
  const formik = useFormikContext<IPassengerList>();
  const representatives = useMemo(() => formik.values.representatives || [], [formik.values.representatives]);

  const [tabs, setTabs] = useState(() => {
    if (representatives.length > 0) {
      return representatives.map((rep, index) => ({
        id: index,
        label: `Adresse ${index + 1}`,
        data: rep,
        isReadOnly: true,
      }))
    }
    return [
      {
        id: 0,
        label: "Adresse 1",
        data: { ...INITIAL_REPRESENTATIVE_DATA },
        isReadOnly: false,
      },
    ]
  })

  const handleAddTab = () => {
    const newTab = {
      id: tabs.length,
      label: `Adresse ${tabs.length + 1}`,
      data: { ...INITIAL_REPRESENTATIVE_DATA },
      isReadOnly: false,
    }
    setTabs([...tabs, newTab])
    setValue(newTab.id)

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

  const handleEdit = (tabId: number) => {
    setTabs((prevTabs) => prevTabs.map((tab) => (tab.id === tabId ? { ...tab, isReadOnly: false } : tab)))
  }

  const handleSave = useCallback(
    (tabId: number) => {
      setTabs((prevTabs) => prevTabs.map((tab) => (tab.id === tabId ? { ...tab, isReadOnly: true } : tab)))
      onSave?.()
    },
    [onSave],
  )

  const handleTabClose = useCallback(
    (event: React.MouseEvent, tabId: number) => {
      event.stopPropagation();
      if (tabs.length <= 1) {
        const initialTab = {
          id: 0,
          label: "Adresse 1",
          data: { ...INITIAL_REPRESENTATIVE_DATA },
          isReadOnly: true,
        }
        setTabs([initialTab])
        formik.setFieldValue("representatives", [])
        return
      }

      const tabIndex = tabs.findIndex((tab) => tab.id === tabId)

      setTabs((prevTabs) => {
        const updatedTabs = prevTabs
          .filter((tab) => tab.id !== tabId)
          .map((tab, index) => ({
            ...tab,
            id: index,
            label: `Adresse ${index + 1}`,
          }))
        return updatedTabs
      })

      const updatedRepresentatives = representatives.filter((_, index) => index !== tabId)
      formik.setFieldValue("representatives", updatedRepresentatives)

      if (value === tabId) {
        if (tabIndex > 0) {
          setValue(tabIndex - 1)
        } else if (tabs.length > 1) {
          setValue(0)
        }
      } else if (value > tabId) {
        setValue(value - 1)
      }
    },
    [tabs, value, representatives, formik],
  )

  const handleFormChange = useCallback(
    (tabId: number, newData: Partial<Representative>) => {
      setTabs((prevTabs) =>
        prevTabs.map((tab) => (tab.id === tabId ? { ...tab, data: { ...tab.data, ...newData } } : tab)),
      )

      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 || scheduleMode === "add"}>
        <Box sx={{ display: "flex", alignSelf: "flex-end", mb: 1 }}>
          <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"}
          >
            <RepresentantForm
              key={tab.id}
              data={tab.data}
              isReadOnly={tab.isReadOnly}
              onChange={(newData) => handleFormChange(tab.id, newData)}
              handleEdit={() => handleEdit(tab.id)}
              handleTabClose={(e) => handleTabClose(e, tab.id)}
              onSave={() => handleSave(tab.id)}
              withContact={withContact}
              tabIndex={tab.id}
              loading={loading}
            />
          </MultiSectionContainer>
        ))}
      </Grid>
    </Box>
  )
}
