import * as XLSX from "xlsx"
import { Box, Button, Typography, useTheme, CircularProgress } from "@mui/material"
import FontAwesome from "../fontawesome"
import { faCloudArrowDown } from "@fortawesome/free-solid-svg-icons"
import { TypeImport } from "@/shared/types/common"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

export default function ExportTemplate({
  onExport,
  onSkip,
  type = TypeImport.CIRCUIT,
  withData,
  customBackendExport,
  isExporting
}: {
  onExport: () => void
  onSkip: () => void
  type?: TypeImport
  withData?: boolean
  customBackendExport?: () => void
  isExporting?: boolean
}) {
  const theme = useTheme()

  function createExcelTemplate() {
    let data: string[][]

    if (type === TypeImport.CIRCUIT) {
      data = [
        ["N° circuit", "Code circuit", "Intitulé", "A partir du", "Fin de circuit", "Établissement"],
        ["", "", "", "", "", ""],
      ]
    } else if (type === TypeImport.FuelFee) {
      data = [
        ["Type de fournisseur", "Date immatriculation", "Kilomètre"],
        ["", "", ""],
      ]
    } else if (type === TypeImport.FUEL) {
      data = [
        ["Date", "Immatriculation", "Nombre de Kilométre"],
        ["", "", ""],
      ]
    } else if (type === TypeImport.VACANCE) {
      return;
    } else {
      data = [
        ["N°", "Nom et prénom", "Établissement", "Adresse"],
        ["", "", "", ""],
      ]
    }

    const ws = XLSX.utils.aoa_to_sheet(data)

    const numColumns = type === TypeImport.CIRCUIT ? 6 : 4

    for (let col = 0; col < numColumns; col++) {
      const cell = ws[XLSX.utils.encode_cell({ r: 0, c: col })]
      if (cell) {
        cell.s = {
          fill: { fgColor: { rgb: "E6E6FA" } },
          font: { bold: true, color: { rgb: theme.palette.text.primary.replace("#", "") } },
          alignment: { horizontal: "center", vertical: "center" },
        }
      }
    }

    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, "Template")
    XLSX.writeFile(wb, `template_${type}.xlsx`)
    onExport()
  }

  return (
    <>
      <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
        <FontAwesome icon={faCloudArrowDown} width={48} height={48} sx={{ color: theme.palette.primary.main }} />
        <Typography variant="h6" sx={{ mt: 2 }}>
          <ConditionalComponent
            isValid={!!withData}
            defaultComponent={"Préparez le template pour l'exportation"}
          >
            {"Préparez les données pour l'exportation"}
          </ConditionalComponent>
        </Typography>
        <Typography variant="body1" sx={{ mt: 1, color: theme.palette.text.secondary }}>
          <ConditionalComponent
            isValid={!!withData}
            defaultComponent={"Cliquez sur le bouton ci-dessous pour générer le fichier template."}
          >
            {"Cliquez sur le bouton ci-dessous pour générer le fichier de données."}
          </ConditionalComponent>
        </Typography>
      </Box>

      <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 3, width: "100%" }}>
        <Button
          variant="contained"
          color="primary"
          sx={{
            fontWeight: 600,
            padding: "12px 24px",
            borderRadius: "8px",
            backgroundColor: theme.palette.primary.main,
            "&:hover": {
              backgroundColor: theme.palette.primary.dark,
            },
          }}
          onClick={customBackendExport ? customBackendExport : createExcelTemplate}
          disabled={!!customBackendExport && !!isExporting}
        >
        <ConditionalComponent
          isValid={!!customBackendExport && !!isExporting}
          defaultComponent={
            <ConditionalComponent
              isValid={!!withData}
              defaultComponent={"Exporter le Template"}
            >
              {"Exporter les Données"}
            </ConditionalComponent>
          }
        >
          <>
            <CircularProgress size={18} sx={{ color: "white", mr: 1 }} />
            {"Export en cours..."}
          </>
        </ConditionalComponent>
        </Button>
        <Button
          variant="outlined"
          color="primary"
          sx={{
            ml: 2,
            fontWeight: 600,
            padding: "12px 24px",
            borderRadius: "8px",
            borderColor: theme.palette.primary.main,
          }}
          onClick={onSkip}
        >
          Ignorer
        </Button>
      </Box>
    </>
  )
}
