import React from 'react';
import { Box, Stack, IconButton, CircularProgress } from '@mui/material';
import { faFileExport, faRotate } from '@fortawesome/free-solid-svg-icons';
import { iconButtonStyles } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import {
  _TRAJETS,
  INITIAL_CIRCUIT_TRAJET_DATA,
} from '@/shared/_mock/_circuitTrajets';
import TableManager from '@/shared/components/table/table-manager';
import TrajetTableRow from './trajet-table-row';
import TransportSchedule from './trajet-details';
import { TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TrajetForm from '@/shared/sections/trajet/view/trajet-new-view';
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from '@/shared/types/common';
import { useTrajetTable } from './hooks/use-trajet-table';
import { TripCircuitDTO } from '@/shared/types/circuit';
import { TripCircuitDetails } from '../../../../../types/circuit';
import { centerFlexRow, StyledCircularProgress } from '../../../../../components/form/style';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import CustomizedTripsList from './components/customized-trips-list';

export const trajetTabsConfig: TabConfig<TripCircuitDetails> = {
  type: 'trajet',
  listTitle: 'Liste des trajets',
  newItemTitle: 'Nouveau trajet',
  initialData: INITIAL_CIRCUIT_TRAJET_DATA,
  getItemCode: (trip) => trip.id,
};
interface CircuittrajetsFormProps {
  useTabs?: boolean;
  circuitId: string;
  amendmentId?: string;
  activationDate?: string;
}
export default function CircuittrajetsForm({ useTabs, circuitId, amendmentId, activationDate }: CircuittrajetsFormProps) {
  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    loading,
    totalTrips,
    getTripCircuit,
    loadingDetails,
    tripsWithTripPoints,
  } = useTrajetTable(circuitId, amendmentId);
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleView,
    handleCancel,
  } = useTabsManager<TripCircuitDetails>(trajetTabsConfig);

  const activeTabData = React.useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);

  const renderRow = (row: TripCircuitDTO) => (
    <TrajetTableRow
      dense={table.dense}
      key={row.id}
      row={row}
      handleEditContract={() => void 0}
      handleDetailsContract={useTabs ? () => getTripCircuit(row.id, handleView) : () => void 0}
      columns={tableHead}
    />
  );

  return (
    <Box >
      <Stack
        sx={{
          visibility: activeTabData?.id === 'list' ? 'visible' : 'hidden',
        }}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        gap="8px"
        pb={2}
      >
        <CustomTooltip title="Refresh" arrow>
          <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
            <FontAwesome icon={faRotate} width={16} />
          </IconButton>
        </CustomTooltip>
        <ExportButton
          tooltipTitle={"Exporter"}
          type={TableType.Trajet}
          filteredData={dataToExport}
          tableHead={tableHead}
        />
      </Stack>
      {useTabs ? <TabsCustom
        type="trajet"
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      /> : <></>}

      {activeTab === 'list' ? (
        <>
          <ConditionalComponent isValid={!loadingDetails}
            defaultComponent={
              <Box sx={centerFlexRow}>
                <StyledCircularProgress />
              </Box>
            }
          >
            <>
              <TableManager
                filteredData={filteredData}
                table={table}
                tableHead={tableHead}
                notFound={notFound}
                filters={filters}
                onFilterChange={handleFilterChange}
                renderRow={renderRow}
                sx={{ backgroundColor: 'primary.lighter' }}
                isTrajetTable={true}
                isWithoutTabs
                loading={loading}
                count={totalTrips}
              />
              <TransportSchedule circuitTripDetails={tripsWithTripPoints} loadingCircuitTripDetails={loading} activationDate={activationDate} />
            </>

          </ConditionalComponent>
        </>
      ) : (
        <TrajetForm
          key={activeTabData?.id}
          trajet={activeTabData?.content as TripCircuitDetails}
          mode={activeTabData?.mode || 'view'}
          onClose={() => handleCancel(activeTab)}
          hasBorder
          tableHead={tableHead}
          handleView={handleView}
          setDrawerMode={() => { }}
        />
      )}
      <CustomizedTripsList circuitId={circuitId} />
    </Box>
  );
}
