"use client"
import { useEffect } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  IconButton,
  Typography,
  Grid,
} from "@mui/material"
import { Close as CloseIcon } from "@mui/icons-material"
import { EmailTemplateCategory, type IEmailTemplate } from "@/shared/types/email-template"
import dynamic from "next/dynamic"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { useFormik } from "formik"
import FormField from "@/shared/components/form/form-field"
import { emailTemplateSchema } from "../utils/email-template-schema"

// Import dynamique de l'éditeur de texte riche pour éviter les erreurs SSR
const ReactQuill = dynamic(() => import("react-quill"), { ssr: false })
import "react-quill/dist/quill.snow.css"

interface EmailTemplateFormProps {
  open: boolean
  template: IEmailTemplate | null
  mode: "add" | "edit" | "view"
  onClose: () => void
  onSave: (template: IEmailTemplate) => void
}

// Configuration de l'éditeur de texte riche
const modules = {
  toolbar: [
    [{ header: [1, 2, false] }],
    ["bold", "italic", "underline", "strike", "blockquote"],
    [{ list: "ordered" }, { list: "bullet" }],
    [{ color: [] }, { background: [] }],
    ["link", "image"],
    ["clean"],
  ],
}

const formats = [
  "header",
  "bold",
  "italic",
  "underline",
  "strike",
  "blockquote",
  "list",
  "bullet",
  "link",
  "image",
  "color",
  "background",
]

// Valeurs initiales par défaut pour un nouveau modèle d'email
const defaultInitialValues: IEmailTemplate = {
  id: "",
  titre: "",
  description: "",
  categorie: EmailTemplateCategory.AUTRE,
  contenu: "",
  dateCreation: new Date().toISOString().split("T")[0],
  isArchive: false,
}

export default function EmailTemplateForm({ open, template, mode, onClose, onSave }: EmailTemplateFormProps) {
  const isReadOnly = mode === "view"

  // Définition des champs du formulaire
  const emailTemplateFormFields = [
    {
      name: "titre",
      label: "Titre",
      type: "text",
      required: true,
    },
    {
      name: "description",
      label: "Description",
      type: "textarea",
      rows: 2,
    },
    {
      name: "categorie",
      label: "Catégorie",
      type: "select",
      options: Object.values(EmailTemplateCategory).map((category) => ({
        value: category,
        label: category.replace(/_/g, " "),
      })),
    },
  ]

  // Initialisation de Formik
  const formik = useFormik<IEmailTemplate>({
    initialValues: template || defaultInitialValues,
    validationSchema: emailTemplateSchema,
    onSubmit: (values) => {
      onSave(values)
      // Réinitialiser le formulaire après la soumission si en mode ajout
      if (mode === "add") {
        formik.resetForm({ values: defaultInitialValues })
      }
    },
    enableReinitialize: true,
  })

  // Réinitialiser le formulaire lorsque le dialogue s'ouvre en mode ajout
  useEffect(() => {
    if (open) {
      if (mode === "add" && !template) {
        formik.resetForm({ values: defaultInitialValues })
      } else if (template) {
        formik.resetForm({ values: template })
      }
    }
  }, [open, mode, template])

  // Gestion du changement de l'éditeur de texte riche
  const handleEditorChange = (content: string) => {
    formik.setFieldValue("contenu", content)
    formik.setFieldTouched("contenu", true)
  }

  const renderField = (field: any) => (
    <FormField
      field={field}
      value={formik.values[field.name as keyof IEmailTemplate]}
      onChange={(name, value) => formik.setFieldValue(name, value)}
      error={
        formik.touched[field.name as keyof IEmailTemplate]
          ? (formik.errors[field.name as keyof IEmailTemplate] as string | undefined)
          : undefined
      }
      onBlur={formik.handleBlur}
      isReadOnly={isReadOnly}
    />
  )

  // Fonction pour gérer la fermeture du dialogue
  const handleDialogClose = () => {
    // Réinitialiser le formulaire lors de la fermeture
    if (mode === "add") {
      formik.resetForm({ values: defaultInitialValues })
    }
    onClose()
  }

  return (
    <Dialog
      open={open}
      onClose={handleDialogClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 4,
          overflow: "hidden",
        },
      }}
    >
      <DialogTitle
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          backgroundColor: "primary.main",
          color: "white",
          fontWeight: "600",
          padding: "16px 24px",
          borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
        }}
      >
        <Typography variant="h6" sx={{ fontSize: "1.25rem", fontWeight: "bold", color: "white" }}>
          {mode === "add"
            ? "Ajouter un modèle d'email"
            : mode === "edit"
              ? "Modifier le modèle d'email"
              : "Détails du modèle d'email"}
        </Typography>
        <IconButton aria-label="close" onClick={handleDialogClose} size="small" sx={{ color: "white" }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <form onSubmit={formik.handleSubmit}>
        <DialogContent
          dividers
          sx={{
            backgroundColor: "#fafafa",
            padding: "24px",
            display: "flex",
            flexDirection: "column",
            gap: "16px",
          }}
        >
          <Grid container spacing={3}>
            {emailTemplateFormFields.map((field) => (
              <Grid item xs={12} key={field.name}>
                {renderField(field)}
              </Grid>
            ))}

            <Grid item xs={12}>
              <Typography variant="subtitle1" gutterBottom>
                Contenu de l&#39;email
              </Typography>
              <Box
                sx={{
                  border: formik.touched.contenu && formik.errors.contenu ? "1px solid red" : "1px solid #ddd",
                  borderRadius: 1,
                  marginBottom: "8px",
                }}
              >
                <ReactQuill
                  theme="snow"
                  value={formik.values.contenu}
                  onChange={handleEditorChange}
                  onBlur={() => formik.setFieldTouched("contenu", true)}
                  modules={modules}
                  formats={formats}
                  style={{ height: "250px", marginBottom: "50px" }}
                  readOnly={isReadOnly}
                />
              </Box>
              {formik.touched.contenu && formik.errors.contenu && (
                <Typography color="error" variant="caption">
                  {formik.errors.contenu as string}
                </Typography>
              )}
            </Grid>
          </Grid>
        </DialogContent>

        <DialogActions sx={{ padding: "16px 24px", backgroundColor: "#fafafa" }}>
          <Button
            onClick={handleDialogClose}
            variant="outlined"
            type="button"
            sx={{
              borderRadius: "8px",
              padding: "8px 16px",
              color: "primary.main",
              borderColor: "primary.main",
              "&:hover": {
                borderColor: "primary.dark",
                color: "primary.dark",
              },
            }}
          >
            {isReadOnly ? "Fermer" : "Annuler"}
          </Button>

          <ConditionalComponent isValid={!isReadOnly}>
            <Button
              variant="contained"
              type="button"
              onClick={() => {
                formik.validateForm().then((errors) => {
                  if (Object.keys(errors).length === 0) {
                    formik.submitForm()
                  }
                })
              }}
              sx={{
                borderRadius: "8px",
                padding: "8px 16px",
                backgroundColor: "primary.main",
                "&:hover": {
                  backgroundColor: "primary.dark",
                },
                boxShadow: 2,
              }}
            >
              {mode === "add" ? "Ajouter" : "Enregistrer"}
            </Button>
          </ConditionalComponent>
        </DialogActions>
      </form>
    </Dialog>
  )
}
