// export default function DocumentListView() 
"use client"

import { Box, Stack } from "@mui/material"
import { useCallback, useMemo, useEffect } from "react"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import { type TabConfig, 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 {
  DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD_RH,
  DEFAULT_DOCUMENT_REQUEST_FILTERS,
  INITIAL_DOCUMENT_REQUEST_DATA,
} from "@/shared/types/document-request"
import type { IDocumentRequest } from "@/shared/types/document-request"
import DocumentRequestTableRowRH from "./document-table-row"
import DocumentRequestForm from "./document-form"
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"

const documentRequestConfig: TableConfig<IDocumentRequest> = {
  initialData: [],
  defaultTableHead: [...DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD_RH],
  type: TableType.DocumentRequest,
}

const documentRequestTabsConfig: TabConfig<IDocumentRequest> = {
  type: TableType.DocumentRequest,
  listTitle: "Demandes de Documents RH",
  newItemTitle: "Nouvelle demande",
  initialData: INITIAL_DOCUMENT_REQUEST_DATA,
  getItemCode: (request) => request.codeReq,
}

export default function DocumentRequestListViewRH() {
  const { requests, loading, error, fetchAll } = useDocumentRequestStore()

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<IDocumentRequest>(documentRequestTabsConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    handleStatusChange,
  } = useTableManager<IDocumentRequest>({
    ...documentRequestConfig,
    initialData: requests,
  })

  // Fetch all requests on component mount
  useEffect(() => {
    fetchAll()
  }, [fetchAll])

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

  const currentData = useMemo(() => {
    return requests
  }, [requests])

  const renderRow = useCallback(
    (row: IDocumentRequest) => (
      <DocumentRequestTableRowRH
        key={row.id}
        dense={table.dense}
        row={row}
        handleEdit={handleEdit}
        handleCopy={handleCopy}
        handleDetails={handleView}
        columns={tableHead.slice(0, -1)}
        onStatusChange={handleStatusChange}
      />
    ),
    [table, handleEdit, handleCopy, handleView, tableHead, handleStatusChange],
  )

  const isList = activeTab === "list"

  if (loading) {
    return <Box>Chargement...</Box>
  }

  if (error) {
    return <Box>Erreur: {error}</Box>
  }

  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={2}>
        <TableControlBar
          type={TableType.DocumentRequest}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          buttonAddTitle="Nouvelle demande"
        />
      </Stack>

      {/* Main Content Box */}
      <Box
        sx={{
          display: "flex",
          flex: 1,
          overflow: "hidden",
          mt: 2,
          borderRadius: 1,
          borderColor: "divider",
        }}
      >
        <Box sx={{ flex: 1, display: "flex", flexDirection: "column" }}>
          <TabsCustom
            type={TableType.DocumentRequest}
            tabs={tabs}
            activeTab={activeTab}
            handleTabChange={handleTabChange}
            handleTabClose={handleTabClose}
          />

          {/* Table content */}
          <Box
            sx={{
              flex: 1,
              overflow: "hidden",
              position: "relative",
            }}
          >
            <ConditionalComponent
              isValid={isList}
              defaultComponent={
                <DocumentRequestForm
                  key={activeTab}
                  request={activeTabData?.content as IDocumentRequest}
                  mode={activeTabData?.mode || "view"}
                  onSave={handleSave}
                  onClose={(force : boolean) => handleCancel(activeTab, force)}
                  onEdit={handleEdit}
                  updateTabContent={updateTabContent}
                  tabId={activeTab}
                />
              }
            >
              <TableManager<IDocumentRequest>
                table={table}
                filteredData={filteredData}
                tableHead={tableHead}
                notFound={notFound}
                filters={filters}
                onFilterChange={handleFilterChange}
                renderRow={renderRow}
                isWithoutTabs={false}
                fixedHeight="calc(100vh - 230px)"
              />
            </ConditionalComponent>
          </Box>
        </Box>

        <UnsavedChangesDialog
          open={showConfirmDialog}
          onClose={() => setShowConfirmDialog(false)}
          onConfirm={handleConfirmDialogAction}
          onCancel={() => setShowConfirmDialog(false)}
        />
      </Box>
    </Box>
  )
}
