import dayjs from "dayjs";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "react-toastify";

import { useDialogStore } from "@/contexts/dialog/lib/useDialogStore";
import { DialogDefaultHeader } from "@/contexts/dialog/ui/DialogDefaultHeader";
import { Loading } from "@/contexts/loading/ui/Loading";
import { ReportType } from "@/contracts/client.schemas";
import { useCreateReport } from "@/contracts/reports";
import { ByStateReportProperties } from "@/features/Reports/ui/ByStateReportProperties";
import { JournalReportProperties } from "@/features/Reports/ui/JournalReportProperties";
import { ReportTypeSelector } from "@/features/Reports/ui/ReportTypeSelector";
import { SummaryEventsExtraProperties } from "@/features/Reports/ui/SummaryEventsExtraProperties";
import { Button, DialogContent, DialogTitle } from "@/shared";
import { useReportBuilderStore } from "@/store/report-builder.store";

import { ReportDownloadDialog } from "./ReportDownloadDialog";

export function NewReportBuilder() {
	const { t } = useTranslation("translation");
	const [isValid, setIsValid] = useState(true);
	const { type, assetIdList, getExtraForType } = useReportBuilderStore();
	const { mutateAsync: createReport, isPending } = useCreateReport();
	const pushDialog = useDialogStore((x) => x.push);
	const closeDialog = useDialogStore((x) => x.close);

	useEffect(() => {
		setIsValid(true);
	}, [type]);

	async function build() {
		if (assetIdList.length === 0) {
			toast.error(t("No assets selected"));
			return;
		}

		if (!Object.values(ReportType).includes(type)) {
			toast.error(t("No report type selected"));
			return;
		}

		const extra = getExtraForType(type);
		if (!extra) {
			toast.error(t("No report extra selected"));
			return;
		}

		try {
			const response = await createReport({
				data: {
					assetIdList: assetIdList,
					type: type,
					extra: JSON.stringify(extra),
					timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
				},
			});

			toast.success(t("Report built successfully"));

			closeDialog();

			pushDialog({
				key: "report-download",
				content: (
					<ReportDownloadDialog
						reportId={response.id}
						type={type}
						createdAt={dayjs(response.createdAt).toDate()}
					/>
				),
			});
		} catch (error) {
			toast.error(t("Report building failed"));
			console.error(error);
		}
	}

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

			<DialogContent>
				<div className="flex flex-col gap-4">
					<DialogDefaultHeader />

					<DialogTitle className="text-center text-2xl">
						{t("Select parameters for report building")}
					</DialogTitle>

					<ReportTypeSelector />

					<div className="border rounded-[10px] p-4 flex flex-col gap-4">
						<h3 className="text-center text-2xl">
							{t("Settings")}
						</h3>

						{type === ReportType.ByState && (
							<ByStateReportProperties
								onIsValid={(isValid: boolean) => {
									setIsValid(isValid);
								}}
							/>
						)}

						{type === ReportType.Journal && (
							<JournalReportProperties
								onIsValid={(isValid: boolean) => {
									setIsValid(isValid);
								}}
							/>
						)}

						{type === ReportType.SummaryEvents && (
							<SummaryEventsExtraProperties
								onIsValid={(isValid: boolean) => {
									setIsValid(isValid);
								}}
							/>
						)}
					</div>

					<div className="flex justify-stretch gap-4">
						<Button
							variant="default"
							className="w-full bg-[var(--primary-500)] text-white hover:bg-[var(--primary-600)]"
							onClick={build}
							disabled={!isValid}
						>
							{t("buildReport")}
						</Button>
					</div>
				</div>
			</DialogContent>
		</>
	);
}
