"use client"

import React, { useState, useEffect } from "react"
import { Box, Button, IconButton, Typography } 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 { TableType } from "@/shared/types/common"
import {
  type INotification,
  DEFAULT_NOTIFICATION_TABLE_HEAD,
  DEFAULT_NOTIFICATION_FILTERS,
  INITIAL_NOTIFICATION_DATA,
} from "@/shared/types/notification"
import { _notifications } from "@/shared/_mock/_notifications"
import NotificationTableRow from "./views/notification-table-row"
import NotificationForm from "./views/notification-form"
import NotificationSettings from "./views/notification-settings"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { ArrowBack } from "@mui/icons-material"
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 { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog"

// Notification table configuration
const notificationConfig: TableConfig<INotification> = {
  initialData: _notifications,
  defaultTableHead: DEFAULT_NOTIFICATION_TABLE_HEAD,
}

// Notification tabs configuration
const notificationTabsConfig: TabConfig<INotification> = {
  type: TableType.Notification,
  listTitle: "Historique des Notifications",
  newItemTitle: "Nouvelle Notification",
  initialData: INITIAL_NOTIFICATION_DATA,
  getItemCode: (notification) => notification.id,
}

// Style pour fixer l'en-tête du tableau
const fixedHeaderStyle = `
  .MuiTableContainer-root {
    max-height: calc(100vh - 200px);
    overflow: auto;
  }
  .MuiTableContainer-root .MuiTableHead-root {
    position: sticky;
    top: 0;
    z-index: 2;
    background-color: #fff;
  }
  .MuiTableContainer-root .MuiTableHead-root .MuiTableRow-head {
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
`

export default function NotificationMainView() {
  const [activeView, setActiveView] = useState<"list" | "settings">("list")

  // Ajouter le style pour fixer l'en-tête du tableau
  useEffect(() => {
    const styleElement = document.createElement("style")
    styleElement.innerHTML = fixedHeaderStyle
    document.head.appendChild(styleElement)

    return () => {
      document.head.removeChild(styleElement)
    }
  }, [])

  // Notification tabs management
  const {
    tabs: notificationTabs,
    activeTab: activeNotificationTab,
    handleTabClose: handleNotificationTabClose,
    handleTabChange: handleNotificationTabChange,
    handleTabAdd: handleNotificationTabAdd,
    handleEdit: handleNotificationEdit,
    handleView: handleNotificationView,
    handleCancel: handleNotificationCancel,
    handleCopy: handleNotificationCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<INotification>(notificationTabsConfig)

  // Notification table management
  const {
    table: notificationTable,
    filteredData: notificationFilteredData,
    filters: notificationFilters,
    tableHead: notificationTableHead,
    notFound: notificationNotFound,
    handleFilterChange: handleNotificationFilterChange,
    handleResetFilters: handleNotificationResetFilters,
    handleResetColumns: handleNotificationResetColumns,
    handleColumnsChange: handleNotificationColumnsChange,
    handleStatusChange,
    handleSave: handleNotificationSave,
  } = useTableManager<INotification>(notificationConfig)

  // Get active notification tab data
  const activeNotificationTabData = React.useMemo(() => {
    return notificationTabs.find((tab) => tab.id === activeNotificationTab)
  }, [notificationTabs, activeNotificationTab])

  // Toggle between list and settings views
  const toggleView = (view: "list" | "settings") => {
    setActiveView(view)
  }

  // Adapter functions to convert between string IDs and INotification objects
  const handleEditById = (id: string) => {
    const notification = notificationFilteredData.find((item) => item.id === id)
    if (notification) {
      handleNotificationEdit(notification)
    }
  }

  const handleCopyById = (id: string) => {
    const notification = notificationFilteredData.find((item) => item.id === id)
    if (notification) {
      handleNotificationCopy(notification)
    }
  }

  const handleDetailsById = (id: string) => {
    const notification = notificationFilteredData.find((item) => item.id === id)
    if (notification) {
      handleNotificationView(notification)
    }
  }

  // Render notification table row
  const renderNotificationRow = (row: INotification) => (
    <NotificationTableRow
      key={row.id}
      dense={notificationTable.dense}
      row={row}
      handleEdit={handleEditById}
      handleCopy={handleCopyById}
      handleDetails={handleDetailsById}
      selected={notificationTable.selected.includes(row.id)}
      onSelectRow={() => notificationTable.onSelectRow(row.id)}
      columns={notificationTableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
    />
  )

  // Convert mode type if needed
  const getFormMode = (mode?: string): "new" | "edit" | "view" => {
    if (mode === "add") return "new"
    return (mode as "new" | "edit" | "view") || "view"
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)`,
      }}
    >
      <ConditionalComponent isValid={!(activeView === "list")}>
        <Box>
        <CustomTooltip title={"Retour aux Documents"} arrow>
                <IconButton sx={WhiteIconButtonStyle} onClick={() => setActiveView("list")}>
                  <FontAwesome icon={faArrowLeft} width={18} />
                </IconButton>
              </CustomTooltip>
        </Box>
      </ConditionalComponent>
      <ConditionalComponent isValid={activeView === "list" && ! !(activeNotificationTab === "list")}>
        <Typography sx={{color: "primary.main"}} variant="h4" component="h1" fontWeight="bold">
          Historique Des Notifications
        </Typography>
      </ConditionalComponent>
      <Box
        sx={{
          mb: 2,
          display: "flex",
          justifyContent: "flex-end",
          alignItems: "center",
          px: 2,
          gap: 2,
        }}
      >
        <ConditionalComponent isValid={activeView === "list" && !!(activeNotificationTab === "list")}>
          <Box>
            <Button
              variant={activeView === "settings" ? "contained" : "outlined"}
              onClick={() => toggleView("settings")}
              sx={{ textTransform: "none" }}
            >
              Paramètres des Notifications
            </Button>
          </Box>
        </ConditionalComponent>

        <ConditionalComponent isValid={activeView === "list" && !!(activeNotificationTab === "list")}>
          <TableControlBar
            type={TableType.Notification}
            handleTabAdd={handleNotificationTabAdd}
            activeTab={activeNotificationTab}
            onResetFilters={handleNotificationResetFilters}
            onResetColumns={handleNotificationResetColumns}
            onColumnsChange={handleNotificationColumnsChange}
            initialColumns={DEFAULT_NOTIFICATION_TABLE_HEAD.filter((col) =>
              DEFAULT_NOTIFICATION_FILTERS.includes(col.id),
            )}
            onFilters={handleNotificationFilterChange}
            filteredData={notificationFilteredData}
          />
        </ConditionalComponent>
      </Box>

      <ConditionalComponent isValid={activeView === "list"}>
        <>
          <TabsCustom
            type={TableType.Notification}
            tabs={notificationTabs}
            activeTab={activeNotificationTab}
            handleTabChange={handleNotificationTabChange}
            handleTabClose={handleNotificationTabClose}
          />
          <ConditionalComponent isValid={activeNotificationTab === "list"}>
            <Box sx={{ overflow: "auto", flexGrow: 1 }}>
              <TableManager
                filteredData={notificationFilteredData}
                table={notificationTable}
                tableHead={notificationTableHead}
                notFound={notificationNotFound}
                filters={notificationFilters}
                onFilterChange={handleNotificationFilterChange}
                renderRow={renderNotificationRow}
              />
            </Box>
          </ConditionalComponent>
          <ConditionalComponent isValid={!(activeNotificationTab === "list")}>
            <Box sx={{ overflow: "auto", flexGrow: 1 }}>
              <NotificationForm
                key={activeNotificationTab}
                notification={activeNotificationTabData?.content as INotification}
                mode={getFormMode(activeNotificationTabData?.mode)}
                onSave={handleNotificationSave}
                onClose={(force) => handleNotificationCancel(activeNotificationTab, force)}
                onEdit={handleEditById}
                updateTabContent={updateTabContent}
                tabId={activeNotificationTab}
              />
            </Box>
          </ConditionalComponent>
        </>
      </ConditionalComponent>
      <ConditionalComponent isValid={!(activeView === "list")}>
          <NotificationSettings />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  )
}
