"use client";
import React, { useState } from "react";
import {
  FormButton,
  FormInput,
  FormMobileNuber,
} from "@/app/components/form/forms";
import DialogModal from "@/app/components/common/DialogModal";
import TextArea from "../form/TextArea";
import { SingleChip } from "../chips";
import Cookies from "js-cookie";
import LoginForm from "../auth/loginForm";
import SignupForm from "../auth/signupForm";

const RangeOptions = [
  { id: "blk_opt_1", range: "11-25", price: "330", value: "BOR_1" },
  { id: "blk_opt_2", range: "26-50", price: "320", value: "BOR_2" },
  { id: "blk_opt_3", range: "51-100", price: "310", value: "BOR_3" },
  { id: "blk_opt_4", range: "101-250", price: "290", value: "BOR_4" },
  { id: "blk_opt_5", range: "250-500", price: "275", value: "BOR_5" },
  { id: "blk_opt_6", range: "500+", price: "--", value: "BOR_6" },
];

type ModalKey = string | null;
interface PDPBulkOrderProps {
  bulkOrderData: any;
  showButtonOnly?: boolean;
}

export default function PDPBulkOrder({
  bulkOrderData,
  showButtonOnly = false,
}: PDPBulkOrderProps) {
  const [openModal, setOpenModal] = useState<ModalKey>(null);
  const [productType, setProductType] = useState<string>("product_as_it");
  const [howMany, setHowMany] = useState("");
  const [price, setPrice] = useState("");
  const [tellUs, setTellUs] = useState("");
  const [bonusAddOns, setBonusAddOns] = useState<string[]>([]);

  const closeAllModals = () => {
    setOpenModal(null);
  };

  const openSpecificModal = (modalKey: ModalKey) => {
    setProductType("product_as_it");
    setHowMany("");
    setPrice("");
    setTellUs("");
    setBonusAddOns([]);
    closeAllModals();
    setTimeout(() => {
      setOpenModal(modalKey);
    }, 50);
  };

  const handleBonusClick = (label: string) => {
    setBonusAddOns((prev) =>
      prev.includes(label)
        ? prev.filter((item) => item !== label)
        : [...prev, label],
    );
  };

  const handleSubmit = async () => {
    const token = Cookies.get("token");

    const payload = {
      product_id: bulkOrderData?.product_id,
      order_type:
        productType === "product_as_it"
          ? "Order this design as is"
          : "Customize this design for your brand",
      how_many_piece: howMany,
      price,
      tell_us: tellUs,
      bonus_add_ons: bonusAddOns.join(","),
    };

    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/bulkorder/save`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (res.ok) {
        alert("bulk order request added succefully!");
        closeAllModals();
      } else {
        alert(data?.message || "Something went wrong");
      }
    } catch (err) {
      console.error(err);
      alert("Error submitting request");
    }
  };

  return (
    <>
      {showButtonOnly ? (
        <div className="my-2 w-full flex flex-col items-center justify-center align-middle">
          <button
            onClick={() => {
              const token = Cookies.get("token");
              if (token) {
                openSpecificModal("bulk_order_request");
              } else {
                openSpecificModal("show_login_modal");
              }
            }}
            className="border-1 w-full text-sm tracking-wider px-6 py-3 font-medium uppercase duration-300 hover:bg-gray-900 hover:text-white"
          >
            Bulk Order
          </button>
        </div>
      ) : (
        <div className="relative flex w-full bg-linear-to-r from-blue-50 to-teal-100">
          <div className="flex h-full w-full flex-col">
            <span className="mob-noise absolute top-0 left-0 z-10 h-full w-full"></span>
            <div className="relative z-20 flex h-full w-full flex-col">
              <div className="flex flex-col justify-center p-5 text-center">
                <p className="font-macropolo text-3xl uppercase">Bulk order</p>
                <p className="mt-2 text-xs">
                  Are you a store, or wholesaler? Get special pricing and design
                  support on orders of 10+ pieces—crafted with the same care,
                  just scaled for you.
                </p>
              </div>
              <div className="mb-8 flex items-center justify-center align-middle">
                <button
                  onClick={() => {
                    const token = Cookies.get("token");
                    if (token) {
                      openSpecificModal("bulk_order_request");
                    } else {
                      openSpecificModal("show_login_modal");
                    }
                  }}
                  className="border-1 border-dashed px-6 py-3 font-medium uppercase duration-300 hover:bg-teal-600 hover:text-white"
                >
                  Large Order Request
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      <DialogModal
        name="bulk_order_request"
        isOpen={openModal === "bulk_order_request"}
        onClose={closeAllModals}
        size="xl"
        title=""
        subtitle=""
        showFooter={false}
      >
        <div>
          <div className="flex flex-col gap-4 pb-8">
            <h1 className="med">Large Order Request</h1>
            <p className="font-bogart text-base font-light">
              Are you a store, boutique, wholesaler, or event organizer looking
              to bring Morni to more people? Whether you are curating a
              collection, outfitting a team, or wanting to display our designs,
              we offer <span className="font-medium">special pricing</span> and{" "}
              <span className="font-medium">
                customization options for orders of 5 pieces or more
              </span>
              .
            </p>
            <p className="font-bogart text-base font-light">
              We work directly with you to{" "}
              <span className="font-medium">scale your vision—with</span> the
              same care and craftsmanship we bring to every piece.
            </p>
          </div>
          <div className="mob-noise p-4 md:p-8">
            <div className="flex w-full flex-col gap-2">
              <h4>What would you like to do? </h4>
              <div className="flex flex-col gap-2">
                <label
                  htmlFor="product_as_it"
                  className="font-bogart flex cursor-pointer flex-row items-center gap-2 py-2 align-middle text-lg/2 font-medium text-gray-900"
                >
                  <input
                    id="product_as_it"
                    name="product_order_type"
                    type="radio"
                    value="product_as_it"
                    checked={productType === "product_as_it"}
                    onChange={(e) => setProductType(e.target.value)}
                    className="relative size-6 appearance-none rounded-full border border-gray-950 bg-white before:absolute before:inset-1 before:rounded-full before:bg-white not-checked:before:hidden checked:border-gray-950 checked:bg-gray-950"
                  />
                  <span className="relative pt-1.5">
                    Order this design as is
                  </span>
                </label>
                <label
                  htmlFor="product_with_customization"
                  className="font-bogart flex cursor-pointer flex-row gap-2 py-2 text-lg/2 font-medium text-gray-900"
                >
                  <div>
                    <input
                      id="product_with_customization"
                      name="product_order_type"
                      type="radio"
                      value="product_with_customization"
                      onChange={(e) => setProductType(e.target.value)}
                      className="relative -top-1.5 size-6 appearance-none rounded-full border border-gray-950 bg-white before:absolute before:inset-1 before:rounded-full before:bg-white not-checked:before:hidden checked:border-gray-950 checked:bg-gray-950"
                    />
                  </div>
                  <div className="flex flex-col gap-3">
                    <span className="relative pt-1.5">
                      Customize this design for your brand
                    </span>
                  </div>
                </label>
              </div>
              <div className="mt-5 hidden">
                <h4>How many pieces are you interested in?</h4>
              </div>
              <div className="hidden grid-cols-1 gap-1 md:grid-cols-3 md:gap-4">
                {bulkOrderData &&
                  Object.entries(
                    bulkOrderData.wholesale_tiers as Record<string, string>,
                  ).map(([range, price], index) => {
                    return (
                      <label
                        key={index}
                        className="grid grid-cols-8 items-center gap-1 bg-white p-3 align-middle duration-300 hover:bg-teal-600/20 md:p-5"
                      >
                        <div className="col-span-1">
                          <input
                            type="radio"
                            name="notification-method"
                            className="size-6 appearance-none rounded-full border-2 border-gray-300 bg-white checked:border-teal-600 checked:bg-teal-600"
                            onChange={() => {
                              setHowMany(range);
                              setPrice(price);
                            }}
                          />
                        </div>
                        <div className="col-span-7">
                          <div className="grid grid-cols-2">
                            <span>{range}</span>
                            <span className="font-bogart text-right font-medium uppercase">
                              $ {price}
                            </span>
                          </div>
                        </div>
                      </label>
                    );
                  })}
              </div>
            </div>
            <div className="mt-10">
              <h4>Tell us about your business or project</h4>
              <TextArea
                label=""
                name="bulk_order_about_project"
                maxLength={1000}
                placeholder="Describe your thoughts here..."
                showLimitMessage={true}
                value={tellUs}
                required={false}
                onChange={(e) => setTellUs(e.target.value)}
              />
            </div>
            <div className="mt-10">
              <h4>Bonus Add-ons (Optional)</h4>
              <div className="flex flex-wrap gap-2">
                <SingleChip
                  id="add_ons_add_brand_label"
                  label="Add your brand label"
                  value=""
                  onClick={() => handleBonusClick("Add your brand label")}
                />
                <SingleChip
                  id="add_ons_bts"
                  label="Get full BTS content"
                  value=""
                  onClick={() => handleBonusClick("Get full BTS content")}
                />
                <SingleChip
                  id="add_ons_add_need_help_visualizing"
                  label="Need help visualizing? Let our team assist"
                  value=""
                  onClick={() =>
                    handleBonusClick(
                      "Need help visualizing? Let our team assist",
                    )
                  }
                />
              </div>
            </div>
            <div className="flex w-full flex-col pb-15 md:w-[50%]">
              <div className="">
                <FormButton
                  id="btn_design_buy"
                  label="Send Request"
                  type="button"
                  color="teal"
                  hairline="teal"
                  onClick={handleSubmit}
                  disabled={false}
                />
              </div>
            </div>
          </div>
        </div>
      </DialogModal>
      <DialogModal
        name="show_login_modal"
        isOpen={openModal === "show_login_modal"}
        onClose={closeAllModals}
        size="md"
        title=""
        subtitle=""
        showFooter={false}
      >
        <div className="flex w-full flex-col">
          <LoginForm />
          <div className="flex flex-col items-center justify-center py-10">
            <button
              className="btn-outline"
              onClick={() => openSpecificModal("show_signup_modal")}
            >
              Sign Up
            </button>
          </div>
        </div>
      </DialogModal>
      <DialogModal
        name="show_signup_modal"
        isOpen={openModal === "show_signup_modal"}
        onClose={closeAllModals}
        size="md"
        title=""
        subtitle=""
        showFooter={false}
      >
        <div className="flex w-full flex-col">
          <SignupForm />
          <div className="flex flex-col items-center justify-center py-10">
            <button
              className="btn-outline"
              onClick={() => openSpecificModal("show_login_modal")}
            >
              Log In
            </button>
          </div>
        </div>
      </DialogModal>
    </>
  );
}
