"use client"

import { useState, useMemo } from "react"
import { Box, Stack, Button, Tooltip } from "@mui/material"
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { useTabsManager } from "@/hooks/use-tabs-manager"
import { useTableManager } from "@/hooks/use-table-manager"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import FormulaireTableRow from "./formulaire-table-row"
import FormulaireForm from "../components/formulaire-form"
import { type IFormulaire, INITIAL_FORMULAIRE_DATA } from "@/shared/types/formulaire"
import { DEFAULT_FORMULAIRE_TABLE_HEAD } from "@/shared/_mock/_formulaire"
import { TableType } from "@/shared/types/common"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faTrash } from "@fortawesome/free-solid-svg-icons"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
import { useDeleteForm, useGetAllForms } from "@/shared/api/stores/hr-service/forms-recruitment"
import { useSnackbar } from "notistack"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

const formulaireTabsConfig = {
  type: TableType.Formulaire,
  listTitle: "Liste Formulaires",
  newItemTitle: "Nouvelle Formulaire",
  initialData: INITIAL_FORMULAIRE_DATA,
  getItemCode: (form: IFormulaire) => form.id,
}

export default function FormulaireListView() {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [formulaireToDelete, setFormulaireToDelete] = useState<string | null>(null)
  const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false)
  const { enqueueSnackbar } = useSnackbar()
  const { deleteForm } = useDeleteForm()
  const [page, setPage] = useState(0)
  const [rowsPerPage, setRowsPerPage] = useState(10)
  const { forms, formsLoading } = useGetAllForms()

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    updateTabContent
  } = useTabsManager<IFormulaire>(formulaireTabsConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    
  } = useTableManager<IFormulaire>({
    initialData: forms,
    defaultTableHead: DEFAULT_FORMULAIRE_TABLE_HEAD,
  })

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

  const renderRow = (row: IFormulaire) => (
    <FormulaireTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEdit}
      handleView={handleView}
      handleDelete={handleDelete}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
    />
  )

  const isList = activeTab === "list"

  const handleDelete = (id: string) => {
    setFormulaireToDelete(id)
    setDeleteDialogOpen(true)
  }

  const confirmDelete = async () => {
    if (formulaireToDelete) {
      try {
        await deleteForm(formulaireToDelete)
        enqueueSnackbar("Formulaire supprimé avec succès", {
          variant: "success",
          autoHideDuration: 3000,
        })
        setDeleteDialogOpen(false)
        setFormulaireToDelete(null)
      } catch (error) {
        console.error("Error deleting form:", error)
        enqueueSnackbar("Erreur lors de la suppression du formulaire", { variant: "error", autoHideDuration: 5000 })
      }
    }
  }

  const cancelDelete = () => {
    setDeleteDialogOpen(false)
    setFormulaireToDelete(null)
    console.log(forms)
  }

  const openBulkDeleteDialog = () => {
    setBulkDeleteDialogOpen(true)
  }

  const confirmBulkDelete = async () => {
    if (table.selected.length > 0) {
      try {
        await Promise.all(table.selected.map((id) => deleteForm(id)))
        enqueueSnackbar(`${table.selected.length} formulaires supprimés avec succès`, {
          variant: "success",
          autoHideDuration: 3000,
        })
        table.onSelectAllRows(false, [])
        setBulkDeleteDialogOpen(false)
      } catch (error) {
        console.error("Error in bulk delete:", error)
        enqueueSnackbar("Erreur lors de la suppression multiple", { variant: "error", autoHideDuration: 5000 })
      }
    }
  }

  const cancelBulkDelete = () => {
    setBulkDeleteDialogOpen(false)
  }
  const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setPage(newPage)
  }

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(Number.parseInt(event.target.value, 10))
    setPage(0)
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="space-between" sx={{ px: 2, py: 1 }}>
        {/* Bulk actions that appear when items are selected */}
        {activeTab === "list" && table.selected.length > 0 && (
          <Box>
            <Tooltip title="Supprimer la sélection">
              <Button
                size="small"
                color="error"
                variant="contained"
                startIcon={<FontAwesomeIcon icon={faTrash} />}
                onClick={openBulkDeleteDialog}
              >
                Supprimer ({table.selected.length})
              </Button>
            </Tooltip>
          </Box>
        )}

        <Box sx={{ ml: "auto" }}>
          <TableControlBar
            type={TableType.Formulaire}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead}
            onFilters={handleFilterChange}
            filteredData={filteredData}
          />
        </Box>
      </Stack>

      <TabsCustom
        type={TableType.Formulaire}
        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}
          count={filteredData.length}
          page={page}
          rowsPerPage={rowsPerPage}
          onPageChange={handlePageChange}
          onRowsPerPageChange={handleRowsPerPageChange}
          loading={formsLoading}
        />
      </ConditionalComponent>

      <ConditionalComponent isValid={!isList}>
        <FormulaireForm
          key={activeTab}
          formulaire={activeTabData?.content as IFormulaire}
          mode={activeTabData?.mode || "view"}
          onSave={handleSave}
          onClose={(forceClose) => handleCancel(activeTab, forceClose)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      </ConditionalComponent>

      <ConfirmDialog
        open={deleteDialogOpen}
        title="Confirmation de suppression"
        content="Êtes-vous sûr de vouloir supprimer ce formulaire ? Cette action est irréversible."
        confirmButtonText="Supprimer"
        cancelButtonText="Annuler"
        confirmButtonColor="error"
        onConfirm={confirmDelete}
        onCancel={cancelDelete}
      />

      {/* Bulk Delete Confirmation Dialog */}
      <ConfirmDialog
        open={bulkDeleteDialogOpen}
        title="Confirmation de suppression multiple"
        content={`Êtes-vous sûr de vouloir supprimer les ${table.selected.length} formulaires sélectionnés ? Cette action est irréversible.`}
        confirmButtonText={`Supprimer (${table.selected.length})`}
        cancelButtonText="Annuler"
        confirmButtonColor="error"
        onConfirm={confirmBulkDelete}
        onCancel={cancelBulkDelete}
      />
    </Box>
  )
}
