'use client';

import React, { useEffect, useMemo, useState } from 'react';
import {
  Box,
  Button,
  IconButton,
  Popover,
  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';
import { RoadMapStyledDatePicker } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import { faCalendar } from '@fortawesome/free-solid-svg-icons';
import dayjs, { Dayjs } from 'dayjs';
import { LocalizationProvider, StaticDatePicker } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import { Column } from 'jspdf-autotable';

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 [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [startDate, setStartDate] = useState<Dayjs | null>(null);
  const [endDate, setEndDate] = useState<Dayjs | null>(null);
  const [dateError, setDateError] = useState(false);
  const handleCalendarClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClosePopover = () => {
    setAnchorEl(null);
    setDateError(false);
  };

  const handleValidateDates = () => {
    if (!startDate || !endDate || startDate.isAfter(endDate)) {
      setDateError(true);
      return;
    }
    setDateError(false);

    handleFilterChange('startDate', startDate.format('YYYY-MM-DD'), 'gte');
    handleFilterChange('endDate', endDate.format('YYYY-MM-DD'), 'lte');

    setAnchorEl(null);
  };

  useEffect(() => {
    if (filters.startDate?.value) {
      setStartDate(dayjs(filters.startDate.value));
    } else {
      setStartDate(null);
    }

    if (filters.endDate?.value) {
      setEndDate(dayjs(filters.endDate.value));
    } else {
      setEndDate(null);
    }
  }, [filters.startDate, filters.endDate, anchorEl]);

  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">
          <IconButton onClick={handleCalendarClick}>
            <FontAwesome icon={faCalendar} style={{ width: 22 }} />
          </IconButton>

          <Popover
            open={Boolean(anchorEl)}
            anchorEl={anchorEl}
            onClose={handleClosePopover}
            anchorOrigin={{
              vertical: 'bottom',
              horizontal: 'right',
            }}
            transformOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
          >
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <Box p={2} sx={{ minWidth: 260 }}>
                <Stack direction="row" spacing={2} justifyContent="flex-start">
                  <StaticDatePicker
                    displayStaticWrapperAs="desktop"
                    value={startDate}
                    onChange={(newValue) => setStartDate(newValue ? dayjs(newValue) : null)}
                  />
                  <StaticDatePicker
                    displayStaticWrapperAs="desktop"
                    value={endDate}
                    onChange={(newValue) => setEndDate(newValue ? dayjs(newValue) : null)}
                  />
                </Stack>

                <ConditionalComponent isValid={dateError}>
                  <Typography variant="caption" color="error" sx={{ mt: 1 }}>
                    La date de début doit être inférieure ou égale à la date de fin.
                  </Typography>
                </ConditionalComponent>

                <Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ mt: 2 }}>
                  <Button variant="text" onClick={handleClosePopover}>
                    Annuler
                  </Button>
                  <Button variant="contained" onClick={handleValidateDates}>
                    Valider
                  </Button>
                </Stack>
              </Box>
            </LocalizationProvider>
          </Popover>
          <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>
    </>
  );
}
