"use client";

import { FileUpload } from "@mui/icons-material";
import { Button, Card, CardContent, Grid, Stack, Typography } from "@mui/material";
import React, { ChangeEvent, useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { errorDialogWithContent, submitDialog, successDialog, successDialogWithContent } from "../Swal/CustomAlerts";
import { importStockTake } from "@/app/api/stockTake/actions";
import { importWarehouse, importNewWarehouse } from "@/app/api/warehouse/actions";

interface Props {
}

const BUTTON_NAMES = ["Import Stock Take", "Import Warehouse"] as const;
type ButtonNameType = typeof BUTTON_NAMES[number];

const ExcelFileImport: React.FC<Props> = ({ }) => {

    const { t } = useTranslation("common");
    const [isLoading, setIsLoading] = useState(false);

    const buttonNames: ButtonNameType[] = useMemo(() => {
        return [...BUTTON_NAMES]
    }, [])

    const handleExcelFileImportClick = useCallback(async (event: ChangeEvent<HTMLInputElement>) => {
        try {
            if (event.target.files !== null) {
                const file = event.target.files[0]
                const formData = new FormData();
                formData.append('multipartFileList', file);

                if (file.name.endsWith(".xlsx") || file.name.endsWith(".csv")) {
                    let response: String = ""
                    const buttonId = event.target.id as ButtonNameType;
                    setIsLoading(() => true);

                    console.log(buttonId)
                    switch (buttonId) {
                        case "Import Stock Take":
                            response = await importStockTake(formData)
                            break;
                        case "Import Warehouse":
                            response = await importNewWarehouse(formData)
                            break;
                    }

                    if (response.includes("Import Excel success")) {
                        successDialogWithContent(t("Import Success"), t(`${response}`), t)
                    } else {
                        errorDialogWithContent(t("Import Fail"), t(`${response}`), t)
                    }
                    setIsLoading(() => false);
                }
            }

        } catch (err) {
            console.log(err)
            setIsLoading(() => false);
            // return false
        }
    }, [isLoading])

    return (
        <Card>
            <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                <Typography
                    variant="h4"
                    sx={{
                        background: 'linear-gradient(90deg, red, orange, yellow, green, blue, indigo, violet)',
                        WebkitBackgroundClip: 'text',
                        WebkitTextFillColor: 'transparent',
                        backgroundClip: 'text',
                        color: 'transparent', // Fallback for non-Webkit browsers
                    }}
                >
                    {isLoading ? t("Importing...") : t("Pending for importing")}
                </Typography>
                <Stack
                    spacing={2}
                >
                    <Grid container rowGap={1.5}>
                        {
                            buttonNames.map((name) => {
                                return (
                                    <Grid container key={`${name}-grid`}>
                                        <Button
                                            key={`${name}-btn`}
                                            variant="contained"
                                            color="info"
                                            startIcon={<FileUpload />}
                                            component="label"
                                        >
                                            <input
                                                key={`${name}-in`}
                                                id={name}
                                                type='file'
                                                accept='.xlsx'
                                                hidden
                                                onChange={(event) => {
                                                    handleExcelFileImportClick(event)
                                                }}
                                            />
                                            {t(name)}
                                        </Button>
                                    </Grid>
                                )
                            })
                        }
                    </Grid>
                </Stack>
            </CardContent>
        </Card>
    );
};

export default ExcelFileImport;