'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Box, Stack, Typography } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import { useAddNewProadMapTabs } from '../components/hooks/use-add-new-roadmap-tabs';
import AddNewRoadMapTable from '../components/roadmap-list/add-roadmap/add-new-roadmap-table';
import { useAddNewRoadMapTable } from '../components/hooks/use-add-new-roadmap-table';
import { TableType } from '@/shared/types/common';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faEnvelope } from '@fortawesome/free-solid-svg-icons';
import SendPlanningDialog from '../components/roadmap-list/add-roadmap/send-roadmap-dialog';
import { _drivers } from '@/shared/_mock/_drivers';
import { Dayjs } from 'dayjs';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import RoadMapHistoryDetails from '../components/roadmap-list/add-roadmap/roadmap-history-details';
import { PlanningRequest, PlanningRequestFilterParams } from '@/shared/types/roadMap';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';

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

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
  } = useAddNewRoadMapTable();
  const { planningRequests,totalElements, getAllPlanningRequest, loading, error } = useRoadMapStore();
  const [params, setParams] = useState<PlanningRequestFilterParams>({
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDirection: 'desc',
  });
  useEffect(() => {
    const newParams: PlanningRequestFilterParams = {
      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,
      page: Object.keys(filterParams).length > 0 ? 0 : newParams.page,
      ...filterParams,
    });
  }, [table.page, table.rowsPerPage, table.orderBy, table.order, filters]);

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

  const [openDialog, setOpenDialog] = useState(false);

  const handleSend = async () => {
  await getAllPlanningRequest(params); 
};
  const activeTabData = useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab);
  }, [tabs, activeTab]);
  const isList = activeTab === 'list';
  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Typography
        variant="h5"
        sx={{
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Historique des envois de Feuille de Route
      </Typography>

      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <ConditionalComponent isValid={activeTab === 'list'}>
          <AddButton
            variant="contained"
            color="primary"
            endIcon={<FontAwesome icon={faEnvelope} width={18} />}
            onClick={() => setOpenDialog(true)}
          >
            Envoyer
          </AddButton>
        </ConditionalComponent>
        <TableControlBar
          type={TableType.DriverRoadmap}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
        />
      </Stack>

      <TabsCustom
        type={TableType.Driver}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      <ConditionalComponent isValid={isList} defaultComponent={<RoadMapHistoryDetails data={activeTabData?.content as PlanningRequest} />}>
        <AddNewRoadMapTable
          table={table}
          filteredData={planningRequests}
          filters={filters}
          tableHead={tableHead.filter((head) => head.id !== '')}
          notFound={notFound}
          dataToExport={dataToExport}
          activeTab={activeTab}
          onFilterChange={handleFilterChange}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          handleEdit={handleEdit}
          handleCopy={handleCopy}
          handleView={handleView}
          totalElements={totalElements}
        />
      </ConditionalComponent>
      <SendPlanningDialog
        open={openDialog}
        onClose={() => setOpenDialog(false)}
        onSend={handleSend}
        drivers={_drivers}
      />
    </Box>
  );
}
