import { UseDownloader } from "@/lib/hooks/useDownloader/types";
import {
  Button,
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Label,
  Progress,
} from "@/ui";
import { t } from "i18next";
import { useEffect, useId } from "react";

type DownloadQuoteDialogProps = Omit<UseDownloader, "download"> & {
  onFinishDownload: () => void;
};

export const DownloadQuoteDialog = (props: DownloadQuoteDialogProps) => {
  const { percentage, cancel, error, isInProgress, onFinishDownload } = props;
  const panelId = useId();

  useEffect(() => {
    if (isInProgress && !error && percentage === 100) {
      if (onFinishDownload) {
        onFinishDownload();
      }
    }
  }, [percentage, isInProgress, error, onFinishDownload]);

  return (
    <Dialog open={isInProgress}>
      <DialogContent className='sm:max-w-md'>
        <DialogHeader>
          <DialogTitle>{t("quotes.downloading_dialog.title")}</DialogTitle>
          <DialogDescription>{t("quotes.downloading_dialog.description")}</DialogDescription>
        </DialogHeader>
        <div className='mb-4 space-y-2' id={panelId}>
          <Label>
            {t("quotes.downloading_dialog.progress.label", {
              status: t(
                isInProgress
                  ? "quotes.downloading_dialog.progress.status_in_progress"
                  : "quotes.downloading_dialog.progress.status_stopped"
              ),
            })}
          </Label>
          <Progress
            value={percentage}
            max={100}
            getValueLabel={() => t("quotes.downloading_dialog.progress.label", {})}
          />
          {error && <p>Error: {JSON.stringify(error)}</p>}
        </div>
        <DialogFooter className='sm:justify-end'>
          <DialogClose asChild>
            <Button type='button' variant='secondary' onClick={() => cancel()}>
              {t("quotes.downloading_dialog.cancel_button")}
            </Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
