import { PictureAsPdfOutlined, TableChartOutlined } from "@mui/icons-material";
import { Box, Button, Stack, Typography } from "@mui/material";
import dayjs from "dayjs";
import { FC, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { Centroid } from "@/common/components/Centroid";
import { Loader } from "@/common/components/Loader";
import { FileType } from "@/contracts/client.schemas";
import { useCreateExport } from "@/contracts/exports";
import { http } from "@/services/http.service";
import { getExportLanguage } from "@/services/languageService";

import { ReportWithDataContract } from "../contracts/ReportWithDataContract";
import { useBuilderFactory } from "../hooks/useBuilderFactory";
import { useReportStore } from "../store/useReportsStore";
import { getFileExtension, saveFile } from "../utils/file";

export const ReportDetails: FC = () => {
	// const objectList = useAssetsStore((x) => x.assets);
	// const { buildObjectListTitle } = useBuildObjectListTitle();
	const [report, setReport] = useState<ReportWithDataContract>();
	const { t, i18n } = useTranslation();
	const [loading, setLoading] = useState(false);
	const reportContainerId = useReportStore().currentReportId;
	const { create: createBuilder } = useBuilderFactory();
	const { mutateAsync: createExport } = useCreateExport();

	useEffect(() => {
		if (!reportContainerId) {
			return;
		}

		const load = async () => {
			try {
				setLoading(true);
				await http
					.get<ReportWithDataContract>(
						`/api/reports/${reportContainerId}`,
					)
					.then((x) => {
						setReport(x);
					});
			} catch (e) {
				console.error(e);
			} finally {
				setLoading(false);
			}
		};

		load();
	}, [reportContainerId]);

	if (!reportContainerId) {
		return <Typography>{t("No report selected")}</Typography>;
	}

	if (loading || !report) {
		return (
			<Centroid>
				<Loader />
			</Centroid>
		);
	}

	const builder = createBuilder(report.type);

	const exportToExcel = async () => {
		await Send(FileType.Excel, report.id);
	};

	const exportToPdf = async () => {
		await Send(FileType.Pdf, report.id);
	};

	async function Send(fileType: FileType, reportId: string) {
		try {
			const data = await createExport({
				data: {
					fileType,
					reportId,
					language: getLanguage(),
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
				},
			});

			saveFile(data, `${getFileName()}${getFileExtension(fileType)}`);
		} catch (e) {
			console.error(e);
		}
	}

	function getFileName() {
		return `${builder.getTitle(report!)} - ${dayjs(
			report!.createdAt,
		).format("YYYY-MM-DD HH-mm-ss")}`;
	}

	const getLanguage = () => {
		return getExportLanguage(i18n);
	};

	return (
		<Stack
			sx={{
				height: "100%",
				overflow: "hidden",
				width: "100%",
			}}
		>
			<Stack
				direction="row"
				alignItems="center"
				spacing={2}
				justifyContent="space-between"
			>
				<span></span>
				<Stack direction="row">
					<Button
						onClick={() => exportToExcel()}
						size="large"
						startIcon={<TableChartOutlined />}
					>
						Excel
					</Button>
					<Button
						onClick={() => exportToPdf()}
						startIcon={<PictureAsPdfOutlined />}
					>
						PDF
					</Button>
				</Stack>
			</Stack>

			<Box
				sx={{
					flexGrow: 1,
					overflow: "hidden",
					height: 0,
				}}
			>
				{builder.renderDetails(report)}
			</Box>
		</Stack>
	);
};
