'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Box, Stack, Typography, SelectChangeEvent } from '@mui/material';
import {
  StyledFormControl,
  StyledInputLabel,
  StyledSelect,
  StyledMenuItem,
} from '@/shared/theme/css';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { TableType } from '@/shared/types/common';
import { type IExport } from '@/shared/types/export';
import TableManager from '@/shared/components/table/table-manager';
import ExportTableRow from './export-table-row';
import { useExportTable } from '../hooks/use-export-table';
import MODULE_TREE from '../utils/module-tree';
import { getElementMicroservice } from '../utils/microservice-mapping';
import { useExportStore } from '@/shared/api/stores/exportStore';

export default function ExportListView() {
  const [selectedModule, setSelectedModule] = useState<string>('Exploitation');
  const [selectedSubGroup, setSelectedSubGroup] = useState<string>('Usager');
  const [selectedLeaf, setSelectedLeaf] = useState<string>('PASSENGERS');
  const leafEntries = useMemo(
    () =>
      selectedModule && selectedSubGroup
        ? Object.entries(MODULE_TREE[selectedModule]?.[selectedSubGroup] || {})
        : [],
    [selectedModule, selectedSubGroup]
  );

  useEffect(() => {
    if (!selectedModule || !selectedSubGroup) return;
    if (leafEntries.length === 1) {
      const [onlyKey] = leafEntries[0];
      setSelectedLeaf(onlyKey);
    } else if (leafEntries.length > 1) {
      const existingKeys = new Set(leafEntries.map(([k]) => k));
      if (!existingKeys.has(selectedLeaf)) {
        setSelectedLeaf('');
      }
    } else {
      setSelectedLeaf('');
    }
  }, [leafEntries, selectedLeaf, selectedModule, selectedSubGroup]);

  const {
    items,
    totalElements,
    fetchExports,
    downloadExport,
    loading: exportsLoading,
  } = useExportStore();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
  } = useExportTable(items);

  useEffect(() => {
    if (!selectedModule || !selectedSubGroup || !selectedLeaf) return;

    const elementLabel = MODULE_TREE[selectedModule]?.[selectedSubGroup]?.[selectedLeaf];
    if (!elementLabel) return;

    const microservice = getElementMicroservice(elementLabel);
    const supported = [
      'user-service',
      'circuit-service',
      'fleet-service',
      'hr-service',
      'admin-service',
      'roadsheet-service',
      'planning-service',
      'document-service',
    ];
    if (!microservice || !supported.includes(microservice)) return;

    const baseParams: any = {
      description: elementLabel,
      page: table.page,
      size: table.rowsPerPage,
      sort: `${(table.orderBy as string) || 'startTime'},${((table.order as 'asc' | 'desc') || 'desc')}`,
    };

    const filterParams: Record<string, string> = {};
    Object.entries(filters).forEach(([key, { value }]) => {
      if (value !== undefined && value !== null && String(value).trim() !== '') {
        filterParams[key] = String(value);
      }
    });

    fetchExports(microservice as any, { ...baseParams, ...filterParams });
  }, [
    selectedModule,
    selectedSubGroup,
    selectedLeaf,
    table.page,
    table.rowsPerPage,
    table.orderBy,
    table.order,
    filters,
    fetchExports,
  ]);

  const handleDownloadExport = async (exportItem: IExport) => {
    const elementLabel = selectedLeaf
      ? MODULE_TREE[selectedModule]?.[selectedSubGroup]?.[selectedLeaf]
      : undefined;
    const microservice = elementLabel ? getElementMicroservice(elementLabel) : null;
    if (!microservice) return;
    await downloadExport(microservice as any, exportItem.filePath);
  };

  const renderRow = (row: IExport) => (
    <ExportTableRow
      key={row.id}
      row={row}
      handleDownloadExport={handleDownloadExport}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  );

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="space-between"
        spacing={{ xs: 0.5, sm: 1 }}
      >
      <Typography
          variant="h5"
          sx={{
            mb: 2,
            color: 'primary.main',
            fontWeight: (theme) => theme.typography.fontWeightBold,
          }}
        >
          Liste des exports de fichiers
        </Typography>
        <TableControlBar
          type={TableType.Export}
          activeTab={'list'}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={items}
        />
      </Stack>

      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 2, mt: 6 }}>
        <StyledFormControl fullWidth>
          <StyledInputLabel id="module-select-label" shrink>
            Module
          </StyledInputLabel>
          <StyledSelect
            labelId="module-select-label"
            id="module-select"
            value={selectedModule}
            label="Module"
            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 } }}
            onChange={(event: SelectChangeEvent<unknown>, _child) => {
              const value = String(event.target.value);
              setSelectedModule(value);
              setSelectedSubGroup('');
              setSelectedLeaf('');
            }}
          >
            {Object.keys(MODULE_TREE).map((moduleKey) => (
              <StyledMenuItem key={moduleKey} value={moduleKey}>
                {moduleKey}
              </StyledMenuItem>
            ))}
          </StyledSelect>
        </StyledFormControl>

        <StyledFormControl fullWidth disabled={!selectedModule}>
          <StyledInputLabel id="submodule-select-label" shrink>
            Sous-module
          </StyledInputLabel>
          <StyledSelect
            labelId="submodule-select-label"
            id="submodule-select"
            value={selectedSubGroup}
            label="Sous-module"
            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 } }}
            onChange={(event: SelectChangeEvent<unknown>, _child) => {
              const value = String(event.target.value);
              setSelectedSubGroup(value);
              setSelectedLeaf('');
            }}
          >
            <StyledMenuItem value="" disabled>
              Sélectionner un sous-module
            </StyledMenuItem>
            {selectedModule &&
              Object.keys(MODULE_TREE[selectedModule] || {}).map((subKey) => (
                <StyledMenuItem key={subKey} value={subKey}>
                  {subKey}
                </StyledMenuItem>
              ))}
          </StyledSelect>
        </StyledFormControl>

        <StyledFormControl fullWidth disabled={!selectedModule || !selectedSubGroup}>
          <StyledInputLabel id="leaf-select-label" shrink>
            Élément
          </StyledInputLabel>
          <StyledSelect
            labelId="leaf-select-label"
            id="leaf-select"
            value={selectedLeaf}
            label="Élément"
            sx={{ '& legend': { display: 'none' }, '& fieldset': { top: 0 } }}
            onChange={(event: SelectChangeEvent<unknown>, _child) =>
              setSelectedLeaf(String(event.target.value))
            }
          >
            <StyledMenuItem value="" disabled>
              Sélectionner un élément
            </StyledMenuItem>
            {selectedModule &&
              selectedSubGroup &&
              leafEntries.map(([leafKey, leafLabel]) => (
                <StyledMenuItem key={leafKey} value={leafKey}>
                  {leafLabel}
                </StyledMenuItem>
              ))}
          </StyledSelect>
        </StyledFormControl>
      </Stack>

      <Stack  sx={{ mb: 2, mt: 4 }}>
        <TableManager
          filteredData={items}
          table={table}
          tableHead={tableHead}
          notFound={items.length === 0}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          isWithoutTabs
          count={totalElements}
          loading={exportsLoading}
        />
      </Stack>
    </Box>
  );
}
