"use client"

import type React from "react"

import { useState, createContext } from "react"
import { Box, Tabs, Tab, Typography } from "@mui/material"
import EmailTemplatesView from "./views/email-template-view"
import EmailAutomationsView from "./views/email-automation-view"
import EmailHistoryView from "./views/email-history-view"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { EmailManagementTab } from "@/shared/types/email"
import { HEADER } from "@/layouts/config-layout"
import { StyledFilterTabs } from "@/shared/theme/css"

// Create a context for tab navigation
export const EmailTabContext = createContext<{
  setActiveTab: (tab: EmailManagementTab) => void
}>({
  setActiveTab: () => {},
})

export default function EmailManagementPage() {
  const [activeTab, setActiveTab] = useState<EmailManagementTab>(EmailManagementTab.Templates)

  const handleTabChange = (_: React.SyntheticEvent, newValue: EmailManagementTab) => {
    setActiveTab(newValue)
  }

  return (
    <EmailTabContext.Provider value={{ setActiveTab }}> 
      <Box sx={{ width: "100%" }}>
        <Box sx={{  mb: 2 }}>
          <StyledFilterTabs value={activeTab} onChange={handleTabChange} aria-label="email management tabs">
            <Tab label="Modèles d'Emails" value={EmailManagementTab.Templates} />
            <Tab label="Envois Automatiques" value={EmailManagementTab.Automations} />
            <Tab label="Historique des Envois" value={EmailManagementTab.History} />
          </StyledFilterTabs>
        </Box>

        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
            height: `calc(100vh - ${HEADER.H_DESKTOP + 70}px)`,
          }}
        >
          <ConditionalComponent 
            isValid={activeTab === EmailManagementTab.Templates}
          >
            <EmailTemplatesView />
          </ConditionalComponent>
          <ConditionalComponent 
            isValid={activeTab === EmailManagementTab.Automations}
          >
            <EmailAutomationsView />
          </ConditionalComponent>
          <ConditionalComponent 
            isValid={activeTab === EmailManagementTab.History}
          >
            <EmailHistoryView />
          </ConditionalComponent>
        </Box>
      </Box>
    </EmailTabContext.Provider>
  )
}
