// email-template-import.tsx
"use client"

import type React from "react"

import { useState } from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Typography,
  IconButton,
  Paper,
} from "@mui/material"
import { Close as CloseIcon, CloudUpload as CloudUploadIcon } from "@mui/icons-material"
import { type IEmailTemplate, EmailTemplateCategory } from "@/shared/types/email-template"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

interface EmailTemplateImportProps {
  open: boolean
  onClose: () => void
  onImport: (template: IEmailTemplate) => void
}

export default function EmailTemplateImport({ open, onClose, onImport }: EmailTemplateImportProps) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [previewContent, setPreviewContent] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setError(null)

    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0]

      // Vérifier le type de fichier
      if (!file.name.endsWith(".html") && !file.name.endsWith(".txt")) {
        setError("Format de fichier non supporté. Veuillez sélectionner un fichier HTML ou TXT.")
        setSelectedFile(null)
        setPreviewContent(null)
        return
      }

      setSelectedFile(file)

      // Lire le contenu du fichier pour l'aperçu
      const reader = new FileReader()
      reader.onload = (e) => {
        if (e.target?.result) {
          setPreviewContent(e.target.result as string)
        }
      }
      reader.readAsText(file)
    }
  }

  const handleImport = () => {
    if (!selectedFile || !previewContent) {
      setError("Veuillez sélectionner un fichier valide.")
      return
    }

    // Créer un nouveau modèle d'email à partir du fichier importé
    const newTemplate: IEmailTemplate = {
      id: Date.now().toString(), // ID temporaire
      titre: selectedFile.name.split(".")[0], // Utiliser le nom du fichier comme titre
      description: `Modèle importé le ${new Date().toLocaleDateString()}`,
      categorie: EmailTemplateCategory.AUTRE,
      contenu: previewContent,
      dateCreation: new Date().toISOString().split("T")[0],
      isArchive: false,
    }

    onImport(newTemplate)
    resetForm()
  }

  const resetForm = () => {
    setSelectedFile(null)
    setPreviewContent(null)
    setError(null)
  }

  const handleClose = () => {
    resetForm()
    onClose()
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      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" }}>
        Importer un modèle d&#39;email
        </Typography>
        <IconButton aria-label="close" onClick={onClose} size="small" sx={{ color: "white" }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>

      <DialogContent
        dividers
        sx={{
          backgroundColor: "#fafafa",
          padding: "24px",
          display: "flex",
          flexDirection: "column",
          gap: "16px",
        }}
      >
        <Box sx={{ mb: 3 }}>
          <Box
            sx={{
              border: "2px dashed #ccc",
              borderRadius: 2,
              p: 3,
              textAlign: "center",
              bgcolor: "background.paper",
              cursor: "pointer",
              "&:hover": {
                borderColor: "primary.main",
              },
            }}
            component="label"
          >
            <input type="file" hidden onChange={handleFileChange} accept=".html,.txt" />
            <CloudUploadIcon color="primary" sx={{ fontSize: 48, mb: 2 }} />
            <Typography variant="body1" gutterBottom>
              Cliquez ou glissez-déposez un fichier HTML ou TXT ici
            </Typography>
            <ConditionalComponent isValid={!!selectedFile}>
              <Typography variant="body2" color="text.secondary">
                Fichier sélectionné: {selectedFile?.name}
              </Typography>
            </ConditionalComponent>
            <ConditionalComponent isValid={!!error}>
              <Typography variant="body2" color="error">
                {error}
              </Typography>
            </ConditionalComponent>
          </Box>
        </Box>

        <ConditionalComponent isValid={!!previewContent}>
          <Box sx={{ mt: 3 }}>
            <Typography variant="h6" gutterBottom>
              Aperçu du modèle
            </Typography>
            <Paper variant="outlined" sx={{ p: 2, maxHeight: "300px", overflow: "auto" }}>
              <div dangerouslySetInnerHTML={{ __html: previewContent || "" }} />
            </Paper>
          </Box>
        </ConditionalComponent>
      </DialogContent>

      <DialogActions sx={{ padding: "16px 24px", backgroundColor: "#fafafa" }}>
        <Button
          onClick={onClose}
          variant="outlined"
          sx={{
            borderRadius: "8px",
            padding: "8px 16px",
            color: "primary.main",
            borderColor: "primary.main",
            "&:hover": {
              borderColor: "primary.dark",
              color: "primary.dark",
            },
          }}
        >
          Annuler
        </Button>
        <Button
          variant="contained"
          onClick={handleImport}
          disabled={!selectedFile || !previewContent}
          sx={{
            borderRadius: "8px",
            padding: "8px 16px",
            backgroundColor: "primary.main",
            "&:hover": {
              backgroundColor: "primary.dark",
            },
            boxShadow: 2,
          }}
        >
          Importer
        </Button>
      </DialogActions>
    </Dialog>
  )
}