// Updated demande-list-view.tsx with correct type mapping for document request
"use client";

import { useEffect, useMemo } from "react";
import { Box, Stack } from "@mui/material";
import { HEADER } from "@/layouts/config-layout";
import TableControlBar from "@/shared/components/table/table-control-bar";
import { useTableManager } from "@/hooks/use-table-manager";
import { useTabsManager } from "@/hooks/use-tabs-manager";
import { TableType } from "@/shared/types/common";
import TabsCustom from "@/shared/components/tabs/tabs-custom";
import TableManager from "@/shared/components/table/table-manager";
import DemandeTableRow from "./demande-table-row";
import DemandeForm from "./demande-new-view";
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore";
import { DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD, INITIAL_DOCUMENT_REQUEST_DATA, type IDocumentRequest } from "@/shared/types/document-request";
import ConditionalComponent from "@/shared/components/table/ConditionalComponent";

const demandeTabsConfig = {
  type: TableType.Demande,
  listTitle: "Liste demandes",
  newItemTitle: "Nouvelle demande",
  initialData: INITIAL_DOCUMENT_REQUEST_DATA,
  getItemCode: (demande: IDocumentRequest) => demande.codeReq,
};


export default function DemandeListView() {
  const userUuid = localStorage.getItem("userUuid") as string;
  const { fetchAllForUser, userRequests, } = useDocumentRequestStore();
  useEffect(() => {
  const userUuid = localStorage.getItem('userUuid');
  
  const loadUserRequests = async () => {
    try {
      await fetchAllForUser(userUuid as string);
    } catch (error) {
      console.error("Failed to load user requests:", error);
    }
  };
  
  if (userUuid) {
    loadUserRequests();
  }
}, [fetchAllForUser])

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
  } = useTabsManager<IDocumentRequest>(demandeTabsConfig);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
  } = useTableManager<IDocumentRequest>({
    initialData: userRequests,
    defaultTableHead: DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD,
  });

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

  const renderRow = (row: IDocumentRequest) => (
    <DemandeTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEdit}
      handleCopy={handleCopy}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
      onPriorityChange={handleStatusChange}
    />
  );

  const isList = activeTab === "list";

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        <TableControlBar
          type={TableType.Demande}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={filteredData}
        />
      </Stack>
      <TabsCustom
        type={TableType.Demande}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      <ConditionalComponent isValid={isList}>
         <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
        />
      </ConditionalComponent>
      <ConditionalComponent isValid={!isList}>
        <DemandeForm
          demande={activeTabData?.content as IDocumentRequest}
          mode={activeTabData?.mode || "view"}
          onSave={handleSave}
          onClose={() => handleCancel(activeTab)}
          onEdit={handleEdit}
        />
      </ConditionalComponent>
    </Box>
  );
}
