'use client';

import { useCallback, useState } from 'react';
import { Box, Grid, IconButton, Typography } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons';
import { IRepresentative, Civility, RelationType } from '@/shared/types/usager';
import RepresentantForm from '@/shared/sections/usager/components/usager-form/representant/representant-form';
import { iconButtonStyles } from '@/shared/theme/css';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { _representatives, INITIAL_REPRESENTATIVE_DATA } from '@/shared/_mock/_represantative';
import { ModeType } from '@/shared/types/common';
import MultiSectionContainer from '@/shared/components/form/multiForm-container';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface RepresentantTabsProps {
  withContact?: boolean;
  scheduleMode?: ModeType;
}

export default function RepresentantTabs({
  withContact,
  scheduleMode,
}: RepresentantTabsProps) {
  const [value, setValue] = useState(0);
  const [tabs, setTabs] = useState([
    { id: 0, label: 'Adresse 1', data: _representatives[0] || INITIAL_REPRESENTATIVE_DATA, isReadOnly: true },
  ]);

  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 handleEdit = (tabId: number) => {
    setTabs((prevTabs) =>
      prevTabs.map((tab) => (tab.id === tabId ? { ...tab, isReadOnly: false } : tab))
    );
  };

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

  const handleTabClose = useCallback(
    (event: React.MouseEvent, tabId: number) => {
      event.stopPropagation();
      if (tabs.length <= 1) {
        setTabs((prevTabs) => [
          { ...prevTabs[0], data: _representatives[0] || INITIAL_REPRESENTATIVE_DATA, isReadOnly: true },
        ]);
        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;
      });

      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]
  );

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

  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={() => onSave(tab.id)}
              withContact={withContact}
            />
          </MultiSectionContainer>
        ))}
      </Grid>
    </Box>
  )
}

