"use client"

import React, { useEffect, useState } from "react"
import { Box, IconButton } 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 { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import { TableType } from "@/shared/types/common"
import DemandeTableRow from "./demandes/views/demande-table-row"
import DemandeForm from "./demandes/views/demande-new-view"
import DocumentDrive from "./documents/document-page"
import CreateFolderDialog from "./documents/components/create-folder-dialog"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { WhiteIconButtonStyle } from "@/shared/theme/css"
import { faArrowLeft } from "@fortawesome/free-solid-svg-icons"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { DEFAULT_DOCUMENT_REQUEST_FILTERS, DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD, IDocumentRequest, INITIAL_DOCUMENT_REQUEST_DATA } from "@/shared/types/document-request"
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"
import { useDocumentStore } from "@/shared/api/stores/document-service/docsStore"
import { useFolderStore } from "@/shared/api/stores/document-service/folderStore"

// Mock folders data
const mockFolders = [
  { id: "1", name: "Classroom", files: 12 },
  { id: "2", name: "Word", files: 8 },
  { id: "3", name: "Outlook", files: 15 },
  { id: "4", name: "Contracts", files: 6 },
  { id: "5", name: "Invoices", files: 9 },
]

// Demande tabs configuration
const demandeTabsConfig: TabConfig<IDocumentRequest> = {
  type: TableType.Demande,
  listTitle: "Mes Demandes",
  newItemTitle: "Nouvelle Demande",
  initialData: INITIAL_DOCUMENT_REQUEST_DATA,
  getItemCode: (demande) => demande.id,
}

export default function DocumentMainView() {
  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])
  // State to toggle between document drive and demandes
  const [showDemandes, setShowDemandes] = useState(false)
  const [folders, setFolders] = useState(mockFolders)
  const [documentKey, setDocumentKey] = useState(0) // Used to force re-render


  const [isCreateFolderDialogOpen, setIsCreateFolderDialogOpen] = useState(false)
  // Demande tabs management
  const {
    tabs: demandeTabs,
    activeTab: activeDemandeTab,
    handleTabClose: handleDemandeTabClose,
    handleTabChange: handleDemandeTabChange,
    handleTabAdd: handleDemandeTabAdd,
    handleEdit: handleDemandeEdit,
    handleView: handleDemandeView,
    handleCancel: handleDemandeCancel,
    handleCopy: handleDemandeCopy,
  } = useTabsManager<IDocumentRequest>(demandeTabsConfig)

  // Demande table management
  const {
    table: demandeTable,
    filteredData: demandeFilteredData,
    filters: demandeFilters,
    tableHead: demandeTableHead,
    notFound: demandeNotFound,
    handleFilterChange: handleDemandeFilterChange,
    handleResetFilters: handleDemandeResetFilters,
    handleResetColumns: handleDemandeResetColumns,
    handleColumnsChange: handleDemandeColumnsChange,
    handleSave: handleDemandeSave,
    handleStatusChange,
  } = useTableManager<IDocumentRequest>({
    initialData: userRequests,
    defaultTableHead: DEFAULT_DOCUMENT_REQUEST_TABLE_HEAD,
  });

  // Get active demande tab data
  const activeDemandeTabData = React.useMemo(() => {
    return demandeTabs.find((tab) => tab.id === activeDemandeTab)
  }, [demandeTabs, activeDemandeTab])

  // Toggle between document drive and demandes
  const toggleDemandes = () => {
    setShowDemandes(true)
  }

  // Function to go back to document drive
  const backToDocuments = () => {
    setShowDemandes(false)
  }

  const handleAddFolder = (folderName: string) => {
    const newFolder = {
      id: (folders.length + 1).toString(),
      name: folderName,
      files: 0,
    }
    setFolders([...folders, newFolder])
    setIsCreateFolderDialogOpen(false)
  }

  // Render demande table row
  const renderDemandeRow = (row: IDocumentRequest) => (
    <DemandeTableRow
      key={row.id}
      dense={demandeTable.dense}
      row={row}
      handleEdit={handleDemandeEdit}
      handleCopy={handleDemandeCopy}
      handleDetails={handleDemandeView}
      selected={demandeTable.selected.includes(row.id)}
      onSelectRow={() => demandeTable.onSelectRow(row.id)}
      columns={demandeTableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
      onPriorityChange={handleStatusChange}
      
    />
  )

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <ConditionalComponent 
        isValid={!showDemandes}
        defaultComponent={
          <>
            <Box sx={{ mb: 2, display: "flex", justifyContent: "space-between", alignItems: "center", pr: 2 }}>
              <CustomTooltip title={"Retour aux Documents"} arrow>
                <IconButton sx={WhiteIconButtonStyle} onClick={backToDocuments}>
                  <FontAwesome icon={faArrowLeft} width={18} />
                </IconButton>
              </CustomTooltip>
              <TableControlBar
                type={TableType.Demande}
                handleTabAdd={handleDemandeTabAdd}
                activeTab={activeDemandeTab}
                onResetFilters={handleDemandeResetFilters}
                onResetColumns={handleDemandeResetColumns}
                onColumnsChange={handleDemandeColumnsChange}
                initialColumns={DEFAULT_DOCUMENT_REQUEST_FILTERS}
                onFilters={handleDemandeFilterChange}
                filteredData={demandeFilteredData}
              />
            </Box>

            <TabsCustom
              type={TableType.Demande}
              tabs={demandeTabs}
              activeTab={activeDemandeTab}
              handleTabChange={handleDemandeTabChange}
              handleTabClose={handleDemandeTabClose}
            />

            <ConditionalComponent 
              isValid={activeDemandeTab === "list"}
              defaultComponent={
                <DemandeForm
                  demande={activeDemandeTabData?.content as IDocumentRequest}
                  mode={activeDemandeTabData?.mode || "view"}
                  onSave={handleDemandeSave}
                  onClose={() => handleDemandeCancel(activeDemandeTab)}
                  onEdit={handleDemandeEdit}
                />
              }
            >
              <TableManager
                filteredData={demandeFilteredData}
                table={demandeTable}
                tableHead={demandeTableHead}
                notFound={demandeNotFound}
                filters={demandeFilters}
                onFilterChange={handleDemandeFilterChange}
                renderRow={renderDemandeRow}
              />
            </ConditionalComponent>
          </>
        }
      >
        <DocumentDrive onShowDemandes={toggleDemandes} />
      </ConditionalComponent>

      <CreateFolderDialog
        open={isCreateFolderDialogOpen}
        onClose={() => setIsCreateFolderDialogOpen(false)}
        onCreateFolder={(folderName) => {
          handleAddFolder(folderName)
          // Force DocumentDrive to refresh
          setDocumentKey((prev) => prev + 1)
        }}
      />
    </Box>
  )
}

