"use client"

import React from "react"
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  IconButton,
  Stack
} from "@mui/material"
import { useTheme } from "@mui/material/styles"
import FontAwesome from "@/shared/components/fontawesome"
import { faDownload, faTimes, faFileExport } from "@fortawesome/free-solid-svg-icons"
import * as XLSX from "xlsx"

interface ExportTemplateDialogProps {
  open: boolean
  onClose: () => void
}

export default function ExportTemplateDialog({ open, onClose }: ExportTemplateDialogProps) {
  const theme = useTheme()

  const handleExportTemplate = () => {
    // Créer le template Excel avec les colonnes requises
    const templateData = [
      [
        "Numéro de la carte",
        "Nom du conducteur",
        "Date de transaction", 
        "Pétrolier",
        "Type de carburant",
        "Montant de transaction",
        "Quantité",
        "Adresse de transaction"
      ],
      [
        "000001",
        "Jean Dupont *",
        "2025-01-15",
        "DKV",
        "Diesel",
        "85.50",
        "50",
        "Station Total - 123 Avenue de la République, Paris"
      ],
      [
        "000002", 
        "Marie Martin *",
        "2025-01-16",
        "TOTAL",
        "Essence",
        "67.20",
        "40",
        "Shell Express - 45 Rue du Commerce, Lyon"
      ]
    ]

    const ws = XLSX.utils.aoa_to_sheet(templateData)

    // Styliser l'en-tête
    for (let col = 0; col < 8; col++) {
      const cell = ws[XLSX.utils.encode_cell({ r: 0, c: col })]
      if (cell) {
        cell.s = {
          fill: { fgColor: { rgb: "E3F2FD" } },
          font: { bold: true, color: { rgb: "1976D2" } },
          alignment: { horizontal: "center", vertical: "center" },
          border: {
            top: { style: "thin", color: { rgb: "CCCCCC" } },
            bottom: { style: "thin", color: { rgb: "CCCCCC" } },
            left: { style: "thin", color: { rgb: "CCCCCC" } },
            right: { style: "thin", color: { rgb: "CCCCCC" } }
          }
        }
      }
    }

    // Ajuster la largeur des colonnes
    const colWidths = [
      { wch: 18 }, // Numéro de la carte
      { wch: 20 }, // Nom du conducteur
      { wch: 18 }, // Date de transaction
      { wch: 12 }, // Pétrolier
      { wch: 15 }, // Type de carburant
      { wch: 18 }, // Montant de transaction
      { wch: 12 }, // Quantité
      { wch: 40 }  // Adresse de transaction
    ]
    ws['!cols'] = colWidths

    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, "Template Cartes Carburant")
    XLSX.writeFile(wb, `template_cartes_carburant_${new Date().toISOString().split('T')[0]}.xlsx`)
    
    onClose()
  }

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      maxWidth="sm"
      PaperProps={{
        sx: {
          borderRadius: 4,
          overflow: "hidden",
        },
      }}
    >
      <DialogTitle
        sx={{
          backgroundColor: theme.palette.primary.main,
          color: "white",
          fontWeight: "600",
          padding: "16px 24px",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center" }}>
          <FontAwesome
            icon={faFileExport}
            sx={{ color: "white", marginRight: "12px", width: 24, height: 24 }}
          />
          <Typography variant="h6" sx={{ fontSize: "1.25rem", fontWeight: "bold", color: "white" }}>
            Exporter le Template Fournisseur
          </Typography>
        </Box>
        <IconButton edge="end" color="inherit" onClick={onClose} aria-label="close" sx={{ color: "white" }}>
          <FontAwesome icon={faTimes} />
        </IconButton>
      </DialogTitle>

      <DialogContent
        sx={{
          backgroundColor: "#fafafa",
          padding: "32px 24px",
          textAlign: "center",
        }}
      >
        <Stack spacing={3} alignItems="center">
          <FontAwesome 
            icon={faDownload} 
            sx={{ 
              color: theme.palette.primary.main, 
              fontSize: "4rem",
              opacity: 0.8 
            }} 
          />
          <Typography 
            variant="h6" 
            sx={{ 
              mb: 2, 
              color: theme.palette.text.primary,
              fontWeight: 600
            }}
          >
            Préparez le template pour l&apos;exportation
          </Typography>
          <Typography 
            variant="body1" 
            sx={{ 
              color: theme.palette.text.secondary,
              textAlign: "center",
              maxWidth: "400px"
            }}
          >
            Cliquez sur le bouton ci-dessous pour générer le fichier template contenant les colonnes requises pour l&apos;import des cartes carburant.
          </Typography>
          <Box sx={{ 
            p: 2, 
            backgroundColor: theme.palette.info.light,
            borderRadius: 2,
            border: `1px solid ${theme.palette.info.main}20`
          }}>
            <Typography variant="body2" sx={{ color: theme.palette.info.dark, fontWeight: 500 }}>
              📝 Le template inclut les champs obligatoires :
            </Typography>
            <Typography variant="body2" sx={{ color: theme.palette.text.secondary, mt: 1 }}>
              • Numéro de carte • Nom conducteur* • Date transaction<br/>
              • Pétrolier • Type carburant • Montant • Quantité • Adresse
            </Typography>
          </Box>
        </Stack>
      </DialogContent>

      <DialogActions
        sx={{
          backgroundColor: "#fafafa",
          padding: "16px 24px",
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Button
          variant="outlined"
          onClick={onClose}
          sx={{
            borderRadius: "8px",
            padding: "10px 20px",
            textTransform: "none",
            color: theme.palette.text.secondary,
            borderColor: theme.palette.grey[300],
            "&:hover": {
              borderColor: theme.palette.grey[400],
              backgroundColor: theme.palette.grey[50],
            },
          }}
        >
          Ignorer
        </Button>
        <Button
          variant="contained"
          onClick={handleExportTemplate}
          startIcon={<FontAwesome icon={faDownload} />}
          sx={{
            borderRadius: "8px",
            padding: "10px 24px",
            textTransform: "none",
            backgroundColor: theme.palette.primary.main,
            boxShadow: "0 4px 12px rgba(25, 118, 210, 0.3)",
            "&:hover": {
              backgroundColor: theme.palette.primary.dark,
              boxShadow: "0 6px 16px rgba(25, 118, 210, 0.4)",
            },
          }}
        >
          Exporter le Template
        </Button>
      </DialogActions>
    </Dialog>
  )
} 