'use client';
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useRef, useState } 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 } 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';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { useConfirmDialog } from './hooks/use-confirm-dialog';

interface RepresentantTabsProps {
  isUsagerAttachedToAmendment?: boolean;
  withContact?: boolean;
  scheduleMode?: ModeType;
  onSave: () => void;
  loading?: boolean;
  onClose: () => void;
  mode: ModeType;
  onEdit: (passenger: IPassengerList) => void;
  trajectorySchedules?: {
    pair: { [key: string]: { all: boolean; ret: boolean } };
    impair: { [key: string]: { all: boolean; ret: boolean } };
  };
}

export default function RepresentantTabs({
  withContact,
  scheduleMode,
  onSave,
  loading,
  onClose,
  mode,
  onEdit,
  isUsagerAttachedToAmendment,
  trajectorySchedules,
}: RepresentantTabsProps) {
  const formik = useFormikContext<IPassengerList>();
  const representatives = useMemo(
    () => formik.values.representatives || [],
    [formik.values.representatives]
  );
  const isReadOnly = mode === 'view';
  const { confirmDialog, handleTabCloseRequest, handleConfirmTabClose, handleCancelTabClose } =
    useConfirmDialog();

  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('representatives', updatedRepresentatives);
    },
    [representatives, formik]
  );

  const handleAddTab = () => {
    const newRepresentative = { ...INITIAL_REPRESENTATIVE_DATA };
    const updatedRepresentatives = [...representatives, newRepresentative];
    formik.setFieldValue('representatives', updatedRepresentatives);
  };
  const validateTabDeletion = useCallback(
    (tabId: number) => {
      const representative = representatives[tabId];

      if (representative?.id) {
        return {
          canDelete: false,
          message:
            'Suppression impossible : Vous pouvez seulement supprimer les nouveaux représentants non sauvegardés.',
        };
      }

      return { canDelete: true };
    },
    [representatives]
  );
  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'}
          >
            <ConditionalComponent isValid={tab.id === 0}>
              <UnifiedRepresentantForm
                tabId={tab.id}
                representatives={representatives}
                trajectorySchedules={trajectorySchedules}
                isUsagerAttachedToAmendment={isUsagerAttachedToAmendment}
                key={tab.id}
                variant="standard"
                data={tab.data}
                isReadOnly={isReadOnly}
                onChange={(newData) => handleFormChange(tab.id, newData)}
                tabIndex={tab.id}
                mode={mode}
                handleTabClose={(event, tabId) =>
                  handleTabCloseRequest(event, tabId, undefined, validateTabDeletion)
                }
              />
            </ConditionalComponent>
            <ConditionalComponent isValid={tab.id !== 0}>
              <UnifiedRepresentantForm
                tabId={tab.id}
                representatives={representatives}
                isUsagerAttachedToAmendment={isUsagerAttachedToAmendment}
                key={tab.id}
                variant="standard"
                data={tab.data}
                isReadOnly={isReadOnly}
                onChange={(newData) => handleFormChange(tab.id, newData)}
                tabIndex={tab.id}
                mode={mode}
                handleTabClose={(event, tabId) =>
                  handleTabCloseRequest(event, tabId, undefined, validateTabDeletion)
                }
              />
            </ConditionalComponent>
          </MultiSectionContainer>
        ))}
        <ConditionalComponent isValid={mode !== 'view'}>
          <Grid item xs={12} sx={{ mt: 2 }}>
            <ActionButtons onSave={onSave} onCancel={onClose} mode={mode} loading={loading} />
          </Grid>
        </ConditionalComponent>
      </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}
      />
    </Box>
  );
}
