'use client';

import { useCallback, useEffect, useMemo } from 'react';
import { Box, Grid, IconButton, CircularProgress } 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 type { AmendmentPassengerDetails } from '@/shared/types/ammendment-passenger';
import { checkScheduleConflict } from '../utils/converters';
import UnifiedRepresentantForm from '../../representant/unified-representantForm';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { useConfirmDialog } from '../../representant/hooks/use-confirm-dialog';

interface AvenantRepresentantProps {
  scheduleMode?: ModeType;
  loading?: boolean;
  mode: ModeType;
  passengerId: string;
}

export default function AvenantRepresentant({
  passengerId,
  scheduleMode,
  loading,
  mode,
}: AvenantRepresentantProps) {
  const formik = useFormikContext<AmendmentPassengerDetails>();
  const representatives = useMemo(
    () => formik.values.amendmentRepresentatives || [],
    [formik.values.amendmentRepresentatives]
  );

  const { confirmDialog, handleTabCloseRequest, handleConfirmTabClose, handleCancelTabClose } =
    useConfirmDialog();

  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 handleActualTabClose = useCallback(
    (tabId: number) => {
      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]
  );

  return (
    <Box sx={{ width: '100%', display: 'flex', flexDirection: 'column' }}>
      <ConditionalComponent
        isValid={!loading}
        defaultComponent={
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', pt: 4 }}>
            <CircularProgress size={32} />
          </Box>
        }
      >
        <>
          <ConditionalComponent isValid={mode === 'add'}>
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 1, gap: 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={scheduleMode === 'view'}
              >
                <UnifiedRepresentantForm
                  key={tab.id}
                  variant="amendment"
                  data={tab.data}
                  isReadOnly={isReadOnly}
                  onChange={(newData) => handleFormChange(tab.id, newData)}
                  tabIndex={tab.id}
                  mode={mode}
                  handleTabClose={(event, tabId) => handleTabCloseRequest(event, tabId)}
                />
              </MultiSectionContainer>
            ))}
          </Grid>

          <ConfirmDialog
            open={confirmDialog.open}
            title="Confirmer la suppression"
            content={`Êtes-vous sûr de vouloir supprimer "${confirmDialog.tabLabel}" ? Cette action est irréversible.`}
            onConfirm={() => handleConfirmTabClose(handleActualTabClose)}
            onCancel={handleCancelTabClose}
            confirmButtonText="Supprimer"
            cancelButtonText="Annuler"
            confirmButtonColor="error"
            useThemeButtons={true}
          />
        </>
      </ConditionalComponent>
    </Box>
  );
}
