"use client"

import React, { useState } from "react"
import { Box, Button, IconButton } from "@mui/material"
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 TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import type { IDemande } from "@/shared/types/demande"
import { TableType } from "@/shared/types/common"
import DemandeTableRow from "./demandes/views/demande-table-row"
import DemandeForm from "./demandes/views/demande-new-view"
import { _demandes, DEFAULT_DEMANDE_FILTERS, DEFAULT_DEMANDE_TABLE_HEAD, INITIAL_DEMANDE_DATA } from "@/shared/_mock/_demandes"
import DocumentDrive from "./documents/document-page"
import CreateFolderDialog from "./documents/components/create-folder-dialog"
import UploadFileDialog from "./documents/components/upload-file-dialog"
import type { IDocument } from "@/shared/types/document"
import { _documents } from "@/shared/_mock/_documents"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { secoundaryColor } from "@/shared/components/table/styles"
import { WhiteIconButtonStyle } from "@/shared/theme/css"
import { faAngleDoubleLeft, faAngleLeft, faArrowLeft } from "@fortawesome/free-solid-svg-icons"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

// 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 table configuration
const demandeConfig: TableConfig<IDemande> = {
  initialData: _demandes,
  defaultTableHead: DEFAULT_DEMANDE_TABLE_HEAD,
}

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

export default function DocumentMainView() {
  // State to toggle between document drive and demandes
  const [showDemandes, setShowDemandes] = useState(false)
  const [importedFile, setImportedFile] = useState<File | null>(null)
  const [documents, setDocuments] = useState<IDocument[]>(_documents)
  const [folders, setFolders] = useState(mockFolders)
  const [documentKey, setDocumentKey] = useState(0) // Used to force re-render

  // Document management states
  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false)
  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<IDemande>(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<IDemande>(demandeConfig)

  // 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)
  }

  const handleAddDocument = (document: IDocument) => {
    setDocuments([...documents, document])
    setIsUploadDialogOpen(false)
  }

  // Render demande table row
  const renderDemandeRow = (row: IDemande) => (
    <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_DEMANDE_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 IDemande}
                  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>
  )
}

