'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Box, SelectChangeEvent, Stack, Typography } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import { TableType } from '@/shared/types/common';
import TableControlBar from '@/shared/components/table/table-control-bar';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useGeolocHistoryTabs } from '../hooks/use-geoloc-history-tabs';
import { useGeolocHistoryTable } from '../hooks/use-geoloc-history-table';
import { useGeolocHistoryStore } from '@/shared/api/stores/geolocHistory';
import { GeolocHistoryFilterParams, IGeolocHistory } from '@/shared/types/geoloc';
import TableManager from '@/shared/components/table/table-manager';
import GeolocHistoryTableRow from '../components/geoloc-history-table-row';
import GeolocHistoryDialog from './geoloc-history-dialog';

export default function GeolocHistoryView() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
  } = useGeolocHistoryTabs();

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

  const isList = activeTab === 'list';
  const [selectedHistoryId, setSelectedHistoryId] = useState<number | null>(null);

  const { geolocsData, loading, error, getGeolocData } = useGeolocHistoryStore();
  const [params, setParams] = useState<GeolocHistoryFilterParams>({
    page: 0,
    size: 5,
    sortBy: 'id',
    sortDirection: 'desc',
  });

  useEffect(() => {
    const newParams: GeolocHistoryFilterParams = {
      page: table.page,
      size: table.rowsPerPage,
      sortBy: table.orderBy,
      sortDirection: table.order.toLowerCase() as 'asc' | 'desc',
    };

    const filterParams: Record<string, string> = {};
    Object.entries(filters).forEach(([key, { value }]) => {
      if (value) {
        filterParams[key] = value;
      }
    });

    setParams({ ...newParams, ...filterParams });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

  useEffect(() => {
    getGeolocData(params);
  }, [params]);

  const handlePageChange = (event: unknown, newPage: number) => {
    table.onChangePage(event, newPage);
  };

  const handleRowsPerPageChange = (event: SelectChangeEvent<number>) => {
    table.onChangeRowsPerPage(event);
  };

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

  const renderRow = (row: IGeolocHistory) => (
    <GeolocHistoryTableRow
      key={row.id}
      onView={() => setSelectedHistoryId(Number(row.id))}
      dense={table.dense}
      row={row}
      handleCopy={handleCopy}
      handleView={handleView}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  );
  return (
    <>
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'column',
          ...(isList && {
            height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
          }),
        }}
      >
        <ConditionalComponent isValid={isList}>
          <Typography
            variant="h5"
            sx={{
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Historique des données de géolocalisation
          </Typography>
        </ConditionalComponent>

        <Stack direction="row" spacing={{ xs: 0.5, sm: 1 }} justifyContent="flex-end">
          <TableControlBar
            type={TableType.DriverRoadmap}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
          />
        </Stack>
        <TabsCustom
          type={TableType.GEOLOC}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />
        <GeolocHistoryDialog
          historyId={selectedHistoryId}
          onClose={() => setSelectedHistoryId(null)}
        />
        <ConditionalComponent isValid={isList}>
          <TableManager
            filteredData={geolocsData?.content || []}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            page={params.page}
            onRowsPerPageChange={handleRowsPerPageChange}
            onPageChange={handlePageChange}
            rowsPerPage={params.size}
            count={geolocsData?.totalElements || 0}
            sortBy={params.sortBy}
            sortDirection={params.sortDirection}
            loading={loading}
          />
        </ConditionalComponent>
      </Box>
    </>
  );
}
