"use client"

import { useState, useCallback, useContext } from "react"
import { Box, Button, IconButton, Stack, 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 { TableType } from "@/shared/types/common"
import TableManager from "@/shared/components/table/table-manager"
import { Refresh as RefreshIcon, ArrowBack as ArrowBackIcon } from "@mui/icons-material"
import type { IEmailHistory, IEmailHistoryFilter } from "@/shared/types/email-history"
import { _emailHistory, DEFAULT_EMAIL_HISTORY_TABLE_HEAD } from "@/shared/_mock/_email-history"
import EmailHistoryDetail from "../components/email-history-detail"
import { EmailTabContext } from "../page"
import { EmailManagementTab } from "@/shared/types/email"
// import { useRouter } from "next/navigation"
import EmailHistoryTableRow from "./email-history-table-row"
import { WhiteIconButtonStyle } from "@/shared/theme/css"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { faArrowLeft } from "@fortawesome/free-solid-svg-icons"

// Configuration pour le tableau de l'historique des emails
const emailHistoryConfig: TableConfig<IEmailHistory> = {
  initialData: _emailHistory,
  defaultTableHead: DEFAULT_EMAIL_HISTORY_TABLE_HEAD,
}

export default function EmailHistoryView() {
  // const router = useRouter()
  const [selectedEmailHistory, setSelectedEmailHistory] = useState<IEmailHistory | null>(null)
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
  } = useTableManager<IEmailHistory>(emailHistoryConfig)

  // Gérer les filtres personnalisés
  const handleCustomFilterChange = useCallback(
    (newFilters: IEmailHistoryFilter) => {
      handleResetFilters()

      setTimeout(() => {
        if (newFilters.templateTitre) {
          handleFilterChange("templateTitre", newFilters.templateTitre, "contains")
        }

        if (newFilters.dateDebut) {
          const formattedDate = newFilters.dateDebut.toISOString()
          handleFilterChange("dateEnvoi", formattedDate, "gte")
        }

        if (newFilters.dateFin) {
          const formattedDate = newFilters.dateFin.toISOString()
          handleFilterChange("dateEnvoi", formattedDate, "lte")
        }

        if (newFilters.status && newFilters.status.length > 0) {
          newFilters.status.forEach((status) => {
            handleFilterChange("status", status, "equals")
          })
        }
      }, 0)
    },
    [handleResetFilters, handleFilterChange],
  )

  // Gérer la réessai d'envoi d'un email
  const handleRetryEmail = (emailHistory: IEmailHistory) => {
    console.log("Réessai d'envoi de l'email avec l'ID:", emailHistory.id)
    // Ici, vous implémenteriez la logique pour réessayer l'envoi
  }

  // Gérer l'annulation d'un email planifié
  const handleCancelEmail = (emailHistory: IEmailHistory) => {
    console.log("Annulation de l'email planifié avec l'ID:", emailHistory.id)
    // Ici, vous implémenteriez la logique pour annuler l'envoi planifié
  }

  // Gérer l'affichage des détails
  const handleViewDetails = (emailHistory: IEmailHistory) => {
    setSelectedEmailHistory(emailHistory)
    setIsDetailModalOpen(true)
  }

  // Naviguer vers la vue des modèles
  const { setActiveTab } = useContext(EmailTabContext)
  const handleBackToTemplates = () => {
    setActiveTab(EmailManagementTab.Templates)
  }

  // Rendu d'une ligne du tableau
  const renderHistoryRow = (row: IEmailHistory) => (
    <EmailHistoryTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleViewDetails={handleViewDetails}
      handleRetry={handleRetryEmail}
      handleCancel={handleCancelEmail}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead}
    />
  )

  return (
    <>
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="space-between" sx={{ mb: 2 }}>
        <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <CustomTooltip title={"Retour Aux Modèles"} arrow>
                <IconButton sx={WhiteIconButtonStyle} onClick={handleBackToTemplates}>
                  <FontAwesome icon={faArrowLeft} width={18} />
                </IconButton>
              </CustomTooltip>
          </Box>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
          <TableControlBar
            type={TableType.Email}
            activeTab="list"
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={filteredData}
            />
        </Box>
      </Stack>
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={[...tableHead, { id: "actions", label: "Actions", type: "text", width: 80 }]}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderHistoryRow}
        />

      {/* Modale de détails */}
      <EmailHistoryDetail
        open={isDetailModalOpen}
        emailHistory={selectedEmailHistory}
        onClose={() => setIsDetailModalOpen(false)}
        onRetry={(id) => {
          if (selectedEmailHistory) {
            handleRetryEmail(selectedEmailHistory)
          }
        }}
        onCancel={(id) => {
          if (selectedEmailHistory) {
            handleCancelEmail(selectedEmailHistory)
          }
        }}
      />
    </>
  )
}
