"use client"

import type React from "react"

import { useState, useCallback } from "react"
import {
  Box,
  Stack,
  Typography,
  Drawer,
  IconButton,
  Tooltip,
  Menu,
  MenuItem,
  ListItemIcon,
  ListItemText,
} 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 { INITIAL_EMAIL_DATA, type IEmail, type IEmailFilter } from "@/shared/types/email"
import { _emails, DEFAULT_EMAIL_TABLE_HEAD } from "@/shared/_mock/_emails"
import { TableType } from "@/shared/types/common"
import TableManager from "@/shared/components/table/table-manager"
import EmailTableRow from "./email-table-row"
import EmailDetailModal from "../components/email-detail-modal"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import {
  FilterList as FilterIcon,
  FilterListOff as FilterOffIcon,
  Refresh as RefreshIcon,
  FileDownload as ExportIcon,
  Print as PrintIcon,
  PictureAsPdf as PdfIcon,
  TableChart as CsvIcon,
} from "@mui/icons-material"
import { format } from "date-fns"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

const emailConfig: TableConfig<IEmail> = {
  initialData: _emails,
  defaultTableHead: DEFAULT_EMAIL_TABLE_HEAD,
}
const emailTabsConfig: TabConfig<IEmail> = {
  type: TableType.Email,
  listTitle: "Historique Des Emails",
  newItemTitle: "Nouveau Email",
  initialData: INITIAL_EMAIL_DATA,
  getItemCode: (email) => email.id,
}
const tableHeadWithAction = [
  ...DEFAULT_EMAIL_TABLE_HEAD,
  { id: "actions", label: "Action", type: "text" ,width: 110 },
]

export default function EmailListView() {
  const [selectedEmail, setSelectedEmail] = useState<IEmail | null>(null)
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false)
  const [isFilterDrawerOpen, setIsFilterDrawerOpen] = useState(false)
  const [exportMenuAnchorEl, setExportMenuAnchorEl] = useState<null | HTMLElement>(null)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleStatusChange,
  } = useTableManager<IEmail>({
    ...emailConfig,
    defaultTableHead: tableHeadWithAction,
  })

  const {
    tabs: emailTabs,
    activeTab: activeEmailTab,
    handleTabClose: handleEmailTabClose,
    handleTabChange: handleEmailTabChange,
    handleTabAdd: handleEmailTabAdd,
    handleEdit: handleEmailEdit,
    handleView: handleEmailView,
    handleCancel: handleEmailCancel,
    handleCopy: handleEmailCopy,
  } = useTabsManager<IEmail>(emailTabsConfig)

  const handleViewDetails = (email: IEmail) => {
    setSelectedEmail(email)
    setIsDetailModalOpen(true)
  }

  const handleCloseDetailModal = () => {
    setIsDetailModalOpen(false)
  }

  const handleResendEmail = (emailId: string) => {
    console.log("Resending email:", emailId)
    // Implement email resend logic here
  }

  // Use useCallback to ensure this function doesn't change on every render
  const handleCustomFilterChange = useCallback(
    (newFilters: IEmailFilter) => {
      // First reset all filters
      handleResetFilters()

      // Then apply each filter individually
      setTimeout(() => {
        // Apply date filters
        if (newFilters.dateDebut) {
          try {
            const formattedDate = format(newFilters.dateDebut, "yyyy-MM-dd")
            handleFilterChange("dateHeure", formattedDate, "gte")
          } catch (error) {
            console.error("Error formatting start date:", error)
          }
        }

        if (newFilters.dateFin) {
          try {
            const formattedDate = format(newFilters.dateFin, "yyyy-MM-dd")
            handleFilterChange("dateHeure", formattedDate, "lte")
          } catch (error) {
            console.error("Error formatting end date:", error)
          }
        }

        // Apply status filters
        if (newFilters.status && newFilters.status.length > 0) {
          newFilters.status.forEach((status) => {
            handleFilterChange("status", status, "equals")
          })
        }

        // Apply search filter
        if (newFilters.recherche) {
          handleFilterChange("destinataire", newFilters.recherche, "contains")
          // Uncomment if you want to search in subject too
          // handleFilterChange("objet", newFilters.recherche, "contains")
        }
      }, 0)
    },
    [handleResetFilters, handleFilterChange],
  )

  const toggleFilterDrawer = () => {
    setIsFilterDrawerOpen(!isFilterDrawerOpen)
  }

  const handleRefresh = () => {
    console.log("Actualisation des données...")
    // Implement refresh logic here
    // For example, you could refetch data from the server
  }

  const handleExportClick = (event: React.MouseEvent<HTMLElement>) => {
    setExportMenuAnchorEl(event.currentTarget)
  }

  const handleExportClose = () => {
    setExportMenuAnchorEl(null)
  }

  const handleExportPDF = () => {
    console.log("Exportation en PDF...")
    // Implement PDF export logic here
    handleExportClose()
  }

  const handleExportCSV = () => {
    console.log("Exportation en CSV...")
    // Implement CSV export logic here
    handleExportClose()
  }

  const handlePrint = () => {
    console.log("Impression...")
    window.print()
  }

  const renderRow = (row: IEmail) => (
    <EmailTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleViewDetails={() => handleViewDetails(row)}
      handleResend={() => handleResendEmail(row.id)}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
    />
  )

  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" sx={{ mb: 2 }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1, }}>

          {/* Export menu */}
          <Menu anchorEl={exportMenuAnchorEl} open={Boolean(exportMenuAnchorEl)} onClose={handleExportClose}>
            <MenuItem onClick={handleExportPDF}>
              <ListItemIcon>
                <PdfIcon fontSize="small" color="error" />
              </ListItemIcon>
              <ListItemText>Exporter en PDF</ListItemText>
            </MenuItem>
            <MenuItem onClick={handleExportCSV}>
              <ListItemIcon>
                <CsvIcon fontSize="small" color="success" />
              </ListItemIcon>
              <ListItemText>Exporter en CSV</ListItemText>
            </MenuItem>
          </Menu>

          {/* Table control bar */}
          <TableControlBar
            type={TableType.Email}
            activeTab="list"
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={filteredData}
          />
        </Box>
      </Stack>

      <Box sx={{ display: "flex" }}>

        <Box
          sx={{
            flexGrow: 1,
            overflow: "auto",
            transition: "margin 0.2s ease",
          }}
        >
          <TabsCustom
              type={TableType.Email}
              tabs={emailTabs}
              activeTab={activeEmailTab}
              handleTabChange={handleEmailTabChange}
              handleTabClose={handleEmailTabClose}
                    />
          <TableManager
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
          />
        </Box>
      </Box>

      <EmailDetailModal
        open={isDetailModalOpen}
        email={selectedEmail}
        onClose={handleCloseDetailModal}
        onResend={handleResendEmail}
      />
    </Box>
  )
}

