import Button from "@/components/Button";
import DefaulModal from "@/components/DefaulModal";
import Input from "@/components/Input";
import { toast } from "@/components/Toast";
import { clx, extractErrorMessage } from "@/helpers/utils";
import { usePurchaseInitate } from "@/pages/catalogue/hooks/useCatalogueData";
import { Receipt1 } from "iconsax-react";
import { useState, type FC } from "react";

const CATALOG_COUNTS = [1, 2, 3, 5, 10];

const BuyCatalog: FC = () => {
  const [showModal, setShowModal] = useState<boolean>(false);
  const [count, setCount] = useState<number>(0);
  const { mutate, isPending } = usePurchaseInitate();

  const handlePurchaseInitate = () => {
    if (count > 0) {
      mutate(
        { count: count },
        {
          onSuccess: (data) => {
            console.log(data);
            // TODO منتقل بشه به صفحه صورت حساب
          },
          onError: (error) => {
            toast(extractErrorMessage(error), "error");
          },
        },
      );
    } else {
      toast("تعداد را انتخاب کنید");
    }
  };

  return (
    <div className="px-4">
      <div className="flex justify-center">
        <Button onClick={() => setShowModal(true)} className="w-fit px-5">
          خرید کاتالوگ
        </Button>
      </div>

      <DefaulModal
        open={showModal}
        close={() => setShowModal(false)}
        isHeader
        title_header="خرید کاتالوگ"
      >
        <div>
          <div className="mt-8 text-sm">تعداد کاتالوگ مورد نظر را انتخاب کنید</div>
          <div className="mt-4 flex flex-wrap gap-4">
            {CATALOG_COUNTS.map((item) => (
              <div
                key={item}
                onClick={() => setCount(item)}
                className={clx(
                  "flex h-10 cursor-pointer items-center rounded-lg border border-[#EBEDF5] bg-[#EBEDF5] px-6 text-xs",
                  count === item && "border-black",
                )}
              >
                {item} عدد
              </div>
            ))}
          </div>

          <div className="mt-8">
            <Input
              label="تعداد"
              className="bg-white/50"
              type="number"
              value={count}
              onChange={(e) => setCount(+e.target.value)}
            />
          </div>

          <div className="mt-24 flex justify-end">
            <Button
              disabled={isPending}
              onClick={handlePurchaseInitate}
              className="w-auto px-8"
              variant="secondary"
            >
              <div className="flex items-center gap-2">
                <Receipt1 size={18} color="black" />
                صدور صورتحساب
              </div>
            </Button>
          </div>
        </div>
      </DefaulModal>
    </div>
  );
};

export default BuyCatalog;
