"use client"

import { useState, useCallback } from "react"
import { Box, Button, 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 { Add as AddIcon } from "@mui/icons-material"
import type { IEmailAutomation, IEmailAutomationFilter } from "@/shared/types/email-automation"
import { _emailAutomations, DEFAULT_EMAIL_AUTOMATION_TABLE_HEAD } from "@/shared/_mock/_email-automation"
import { _emailTemplates } from "@/shared/_mock/_email-templates"
import EmailAutomationForm from "../components/email-automation-form"
import EmailAutomationArchive from "../components/email-automation-archive"
import EmailAutomationTableRow from "./email-automation-table-row"

// Configuration pour le tableau des automatisations d'email
const emailAutomationConfig: TableConfig<IEmailAutomation> = {
  initialData: _emailAutomations.filter((automation) => !automation.isArchive),
  defaultTableHead: DEFAULT_EMAIL_AUTOMATION_TABLE_HEAD,
}

export default function EmailAutomationsView() {
  const [selectedAutomation, setSelectedAutomation] = useState<IEmailAutomation | null>(null)
  const [isAddModalOpen, setIsAddModalOpen] = useState(false)
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)
  const [isArchiveModalOpen, setIsArchiveModalOpen] = useState(false)

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

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

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

        if (newFilters.templateId) {
          handleFilterChange("templateId", newFilters.templateId, "equals")
        }

        if (newFilters.declencheurType) {
          handleFilterChange("declencheur.type", newFilters.declencheurType, "equals")
        }

        if (newFilters.frequence) {
          handleFilterChange("declencheur.frequence", newFilters.frequence, "equals")
        }

        if (newFilters.evenement) {
          handleFilterChange("declencheur.evenement", newFilters.evenement, "equals")
        }
      }, 0)
    },
    [handleResetFilters, handleFilterChange],
  )

  // Gérer l'ajout d'une automatisation
  const handleAddAutomation = (automation: IEmailAutomation) => {
    console.log("Ajout d'une nouvelle automatisation:", automation)
    // Ici, vous ajouteriez l'automatisation à votre base de données
    setIsAddModalOpen(false)
  }

  // Gérer la modification d'une automatisation
  const handleEditAutomation = (automation: IEmailAutomation) => {
    console.log("Modification de l'automatisation:", automation)
    setSelectedAutomation(automation)
    setIsEditModalOpen(true)
  }

  // Gérer l'archivage d'une automatisation
  const handleArchiveAutomation = (automation: IEmailAutomation) => {
    console.log("Archivage de l'automatisation avec l'ID:", automation.id)
    setSelectedAutomation(automation)
    setIsArchiveModalOpen(true)
  }

  // Gérer la sauvegarde des modifications
  const handleSaveAutomation = (automation: IEmailAutomation) => {
    console.log("Sauvegarde de l'automatisation:", automation)
    setIsEditModalOpen(false)
  }

  // Gérer la confirmation d'archivage
  const handleConfirmArchive = (id: string) => {
    console.log("Confirmation d'archivage de l'automatisation:", id)
    setIsArchiveModalOpen(false)
  }

  // Rendu d'une ligne du tableau
  const renderAutomationRow = (row: IEmailAutomation) => (
    <EmailAutomationTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEditAutomation}
      handleDetails={handleEditAutomation}
      handleArchive={handleArchiveAutomation}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead}
    />
  )

  // Filtrer les modèles d'email non archivés
  const availableTemplates = _emailTemplates.filter((template) => !template.isArchive)

  return (
    <>
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" sx={{ mb: 2 }}>
        
          <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}
            handleTabAdd={() => setIsAddModalOpen(true)}
            buttonAddTitle="Ajouter une règle"
          />
        </Box>
      </Stack>
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={[...tableHead, { id: "actions", label: "Actions", type: "text", width: 80 }]}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderAutomationRow}
        />

      {/* Modales */}
      <EmailAutomationForm
        open={isAddModalOpen}
        automation={null}
        mode="add"
        templates={availableTemplates}
        onClose={() => setIsAddModalOpen(false)}
        onSave={handleAddAutomation}
      />

      <EmailAutomationForm
        open={isEditModalOpen}
        automation={selectedAutomation}
        mode="edit"
        templates={availableTemplates}
        onClose={() => setIsEditModalOpen(false)}
        onSave={handleSaveAutomation}
      />

      <EmailAutomationArchive
        open={isArchiveModalOpen}
        automation={selectedAutomation}
        onClose={() => setIsArchiveModalOpen(false)}
        onArchive={handleConfirmArchive}
      />
    </>
  )
}
