import {
  Dialog,
  DialogBody,
  DialogHeader,
  IconButton,
  Typography,
} from "@material-tailwind/react";
import React, { useEffect, useState } from "react";

import { useInvoice } from "../hooks/useInvoice";
import { _useScopedI18n } from "../i18n/client";
import { handleDownload } from "../utils/app.util";
import { notification } from "../utils/notifications.util";
import AppLoadingComponent from "./AppLoadingComponent";

type CreditNote = {
  id: number;
  identifier: string;
  creditNoteInvoiceUrl?: string;
  type?: string;
};

type RequestCreditNoteInvoiceDialogProps = {
  open: boolean;
  creditNotes: CreditNote[];
  setOpen: (value: boolean) => void;
};

export function RequestCreditNoteInvoiceDialog({
  open,
  creditNotes,
  setOpen,
}: RequestCreditNoteInvoiceDialogProps) {
  const scopeT = _useScopedI18n("invoice.requestProcessingDialog");
  const { generateCreditNoteInvoiceAPI } = useInvoice();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [, setAttemptCount] = useState(0);
  const [allAttemptsFailed, setAllAttemptsFailed] = useState(false);

  useEffect(() => {
    let timeoutIds: NodeJS.Timeout[] = [];

    if (creditNotes[currentIndex]) {
      const firstCallTimeout = setTimeout(() => {
        generateCreditNoteInvoiceAPI.mutate({
          creditNote: creditNotes[currentIndex].identifier,
          type: creditNotes[currentIndex].type,
        });
        setAttemptCount(1);
      }, 2000);
      timeoutIds.push(firstCallTimeout);

      const secondCallTimeout = setTimeout(() => {
        generateCreditNoteInvoiceAPI.mutate({
          creditNote: creditNotes[currentIndex].identifier,
          type: creditNotes[currentIndex].type,
        });
        setAttemptCount(2);
      }, 5000);
      timeoutIds.push(secondCallTimeout);

      const thirdCallTimeout = setTimeout(() => {
        generateCreditNoteInvoiceAPI.mutate({
          creditNote: creditNotes[currentIndex].identifier,
          type: creditNotes[currentIndex].type,
        });
        setAttemptCount(3);
      }, 7000);
      timeoutIds.push(thirdCallTimeout);

      const checkAttemptsTimeout = setTimeout(() => {
        if (
          !generateCreditNoteInvoiceAPI.isSuccess ||
          !generateCreditNoteInvoiceAPI.data?.data?.invoiceUrl
        ) {
          setAllAttemptsFailed(true);
        }
      }, 8000);
      timeoutIds.push(checkAttemptsTimeout);
    }

    return () => {
      timeoutIds.forEach((id) => clearTimeout(id));
    };
  }, [currentIndex, creditNotes, generateCreditNoteInvoiceAPI]);

  useEffect(() => {
    if (
      generateCreditNoteInvoiceAPI?.isSuccess &&
      generateCreditNoteInvoiceAPI.data?.link
    ) {
      handleDownload(
        generateCreditNoteInvoiceAPI.data?.link,
        creditNotes[currentIndex]?.identifier?.toString() || "",
      );

      // Move to next credit note if available
      if (currentIndex < creditNotes.length - 1) {
        setCurrentIndex(currentIndex + 1);
        setAllAttemptsFailed(false);
        setAttemptCount(0);
      } else {
        setOpen(false);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [generateCreditNoteInvoiceAPI?.isSuccess]);

  useEffect(() => {
    if (generateCreditNoteInvoiceAPI?.isError) {
      notification.notifyError("something went wrong.");
      setOpen(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [generateCreditNoteInvoiceAPI?.isError]);

  return (
    <>
      <Dialog open={open} size="xs" handler={() => {}} className="p-2 md:p-5">
        <DialogHeader className="p-0">
          <div className="text-right size-full">
            <IconButton
              color="blue-gray"
              size="sm"
              variant="text"
              onClick={() => setOpen(false)}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
                className="h-5 w-5"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </IconButton>
          </div>
        </DialogHeader>
        <DialogBody className="flex flex-col items-center gap-8 text-center">
          {allAttemptsFailed ? (
            <>
              <div>
                <Typography
                  variant="h3"
                  className="text-xl text-black-500 mb-4"
                >
                  {scopeT("failedTitle") ||
                    "Unable to Generate Credit Note Invoice"}
                </Typography>
                <Typography
                  variant="lead"
                  className="text-sm font-medium text-slate-500 mb-6"
                >
                  {scopeT("failedMessage") ||
                    "We couldn't generate your credit note invoice at this time. Please try again."}
                </Typography>
              </div>

              <div className="bg-gray-50 py-4 px-9 border border-slate-100 rounded-lg">
                <Typography
                  variant="h6"
                  className="text-xs leading-5 font-medium text-black-500"
                >
                  Credit Note ID: {creditNotes[currentIndex]?.identifier}
                </Typography>
              </div>
            </>
          ) : (
            <>
              <div>
                <AppLoadingComponent />
                <Typography variant="h3" className="text-xl text-black-500">
                  Generating Credit Note Invoice {currentIndex + 1} of{" "}
                  {creditNotes.length}...
                </Typography>
              </div>

              <div className="bg-gray-50 py-4 px-9 border border-slate-100 rounded-lg">
                <Typography
                  variant="h6"
                  className="text-xs leading-5 font-medium text-black-500"
                >
                  Credit Note ID: {creditNotes[currentIndex]?.identifier}
                </Typography>
              </div>

              <div>
                <Typography
                  variant="lead"
                  className="text-sm font-medium text-slate-500 mb-3"
                >
                  {scopeT("subTitle")}
                </Typography>

                <Typography
                  variant="lead"
                  className="text-sm font-medium text-slate-500"
                >
                  {scopeT("message")}
                </Typography>
              </div>
            </>
          )}
        </DialogBody>
      </Dialog>
    </>
  );
}
