import { useNavigate, useSearchParams } from "@remix-run/react";
import {
  Dialog,
  DialogContent,
  DialogOverlay,
} from "../../components/ui/dialog";
import { useGetInvoiceAndShippingInfo } from "../../requestHandler/use-order-hooks";
import { InvoiceContent } from "../../components/cart/ReceiverInformation";
import sucess_pay from "../../assets/icons/cart/sucess_pay.svg";
import failure_pay from "../../assets/icons/cart/failure_pay.svg";
import { Button } from "../../components/ui/button";
import { CartItem } from "src/api/types";

interface InvoiceModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const InvoiceModal = ({ open, onOpenChange }: InvoiceModalProps) => {
  const [searchParams] = useSearchParams();
  const invoiceNumber = searchParams.get("invoice") || "";
  const shippingInfoId = searchParams.get("shippinginfo") || "";
  const successPay = searchParams.get("status") === "success";
  const {
    data: invoiceData,
    isLoading,
    isError,
    error,
  } = useGetInvoiceAndShippingInfo(invoiceNumber, shippingInfoId);
  const navigate = useNavigate();
  return (
    <Dialog
      open={open}
      onOpenChange={(open) => {
        onOpenChange(open);
        if (!open) {
          navigate("/");
        }
      }}
    >
      <DialogOverlay className="bg-BLACK/10" />
      <DialogContent
        className={`p-4 bg-WHITE rounded-[15px] w-[calc(100%-40px)]`}
      >
        <div className="flex flex-col gap-3 items-center w-full">
          {successPay ? (
            <>
              <SuccessPay />
              {isLoading ? (
                <p className="text-sm">در حال بارگزاری...</p>
              ) : isError ? (
                <div className="text-red-500">
                  <p className="text-sm">خطا در دریافت اطلاعات</p>
                  <p className="text-xs">{(error as Error)?.message}</p>
                </div>
              ) : invoiceData ? (
                <InvoiceContent
                  discountValue={
                    Number(invoiceData.invoice.discountValue) || null
                  }
                  selectedCourierInfo={{
                    estimatedDays:
                      invoiceData.shippingInfo.estimatedDeliveryDays,
                    deliveryPrice: Number(
                      invoiceData.shippingInfo.deliveryPrice
                    ),
                    seller: "",
                    courier: "",
                  }}
                  total={invoiceData.invoice.totalAmount || ""}
                  selectedAddressInfo={{
                    postalCode: invoiceData.shippingInfo.postalCode || "",
                    mainAddress: invoiceData.shippingInfo.mainAddress || "",
                    title: "",
                    receiverName: "",
                    phoneNumber: "",
                  }}
                  cartItems={
                    invoiceData.invoice.items?.map((item) => {
                      return {
                        ...item,
                        productVariant: item.variant,
                        priceAtPurchase: item.unitPrice,
                      } as CartItem;
                    }) || []
                  } //
                />
              ) : (
                <p className="text-sm">اطلاعاتی یافت نشد</p>
              )}
              <Button
                className="w-full bg-VITROWN_BLUE text-white"
                size={"lg"}
                variant="dark"
                onClick={() => {
                  navigate("/");
                  onOpenChange(false);
                }}
              >
                تایید
              </Button>
            </>
          ) : (
            <FailurePay onOpenChange={onOpenChange} />
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
};

const SuccessPay = () => {
  return (
    <div className="flex flex-col gap-4 items-center w-full px-4 border-b py-6">
      <div className="flex flex-col gap-4 items-center w-full px-2">
        <img
          src={sucess_pay}
          alt="invoice"
          className="w-10 h-10 rounded-full object-cover"
        />
        <p className="text-B16 text-center font-bold">سفارش با موفقیت ثبت شد</p>
        <p className="text-R12 text-center">
          وضعیت سفارش و موجودی کیف پول خود را در قسمت پروفایل مشاهده کنید.
        </p>
      </div>
    </div>
  );
};
const FailurePay = ({
  onOpenChange,
}: {
  onOpenChange: (open: boolean) => void;
}) => {
  const navigate = useNavigate();
  return (
    <div className="flex flex-col gap-4 items-center w-full px-4 py-6">
      <div className="flex flex-col gap-4 items-center w-full px-2">
        <img
          src={failure_pay}
          alt="invoice"
          className="w-10 h-10 rounded-full object-cover"
        />
        <p className="text-B16 text-center font-bold">
          پرداخت با خطا مواجه شد!
        </p>
        <p className="text-R12 text-center">
          در صورت کسر وجه، مبلغ حداکثر تا ۷۲ ساعت آینده به حساب شما بازگردانده
          خواهد شد.
        </p>
        <Button
          size={"lg"}
          variant="dark"
          className="bg-VITROWN_BLUE text-white"
          onClick={() => {
            onOpenChange(false);
            navigate("/");
          }}
        >
          متوجه شدم
        </Button>
      </div>
    </div>
  );
};

export default InvoiceModal;
