import { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";

import { useDialogStore } from "@/contexts/dialog/lib/useDialogStore";
import { Loading } from "@/contexts/loading/ui/Loading";
import { FileType, ReportType } from "@/contracts/client.schemas";
import { useCreateExport } from "@/contracts/exports";
import { saveFile } from "@/modules/reports/utils/file";
import { normalizeLanguage } from "@/services/languageService";
import { Button, DialogContent, ExcelIcon, PdfIcon, ZipIcon } from "@/shared";
import { DialogTitle } from "@/shared";

import { useReportFileName } from "../lib/useReportFileName";

type Props = {
	reportId: string;
	type: ReportType;
	createdAt: Date;
};

export function ReportDownloadDialog({ reportId, type, createdAt }: Props) {
	const { t, i18n } = useTranslation("translation");
	const { mutateAsync: createExport, isPending } = useCreateExport();
	const closeDialog = useDialogStore((x) => x.close);
	const { getFileName } = useReportFileName();

	const buttons: {
		key: FileType;
		labelKey: "Download PDF" | "Download Excel" | "Download ZIP";
		icon: ReactNode;
	}[] = [
		{
			key: FileType.Pdf,
			labelKey: "Download PDF",
			icon: <PdfIcon />,
		},
		{
			key: FileType.Excel,
			labelKey: "Download Excel",
			icon: <ExcelIcon />,
		},
		{
			key: FileType.Zip,
			labelKey: "Download ZIP",
			icon: <ZipIcon />,
		},
	];

	const exportReport = async (fileType: FileType) => {
		try {
			const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;

			const response = await createExport({
				data: {
					reportId,
					fileType,
					language: normalizeLanguage(i18n.language),
					timeZone: tz,
				},
			});

			toast.success(t("Report downloaded successfully"));
			closeDialog();

			saveFile(response, getFileName(type, fileType, createdAt));
		} catch (error) {
			toast.error(t("Report download failed"));
			console.error(error);
		}
	};

	return (
		<>
			{isPending && <Loading />}

			<DialogContent className="max-w-[500px]">
				<div className="flex flex-col gap-4 p-[50px]">
					<DialogTitle className="text-center text-lg font-medium">
						{t(
							"Download report in Excel or PDF format, or both formats in a ZIP file.",
						)}
					</DialogTitle>

					<div className="flex flex-col gap-[12px]">
						{buttons.map((button) => (
							<Button
								key={button.key}
								variant="outline"
								className="w-full flex gap-[15px] items-center border-[var(--primary-600)] text-[var(--primary-600)] hover:bg-[var(--primary-600)] hover:text-white"
								onClick={() => exportReport(button.key)}
								disabled={isPending}
							>
								{button.icon}
								{t(button.labelKey)}
							</Button>
						))}
					</div>
				</div>
			</DialogContent>
		</>
	);
}
