"use client";

import { SuccessModal } from "@/app/components/shipping/ShippingSuccessModal";
import AlertModal from "@/app/components/ui/AlertModal";
import { InternalButton } from "@/app/components/ui/Button";
import NotAvailable from "@/app/components/ui/NotAvailable";
import { updateSession } from "@/app/lib/api/inventory";
import { saveShipping } from "@/app/lib/api/shipping";
import { useAppDispatch } from "@/app/lib/hooks";
import { updateUser } from "@/app/store/authSlice";
import { User } from "@/constants/types";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";

// ✅ add this near top (inside component)

const ShippingPage = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"error" | "success">("error");
  const [modalMsg, setModalMsg] = useState("");

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [shipping, setShipping] = useState(20);
  const [discount, setDiscount] = useState(0);
  const [finalTotal, setFinalTotal] = useState("0.00");
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Partial<Record<FormKeys, boolean>>>(
    {},
  );
  const [summary, setSummary] = useState({
    selectedCount: 0,
    totalValue: "0.00",
    cards: "",
    bulkCount: 0,
    bulkPrice: 0,
  });
  const router = useRouter();

  // 🟦 Form State
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    address: "",
    country: "",
    state: "",
    city: "",
    zip: "",
  });

  const dispatch = useAppDispatch();
  const user = useSelector((state: any) => state.auth.user) as User | null;
  type FormKeys = keyof typeof formData;

  type FormErrors = Partial<Record<FormKeys, string>>;

  // basic validators
  const validateField = (name: FormKeys, value: string): string => {
    const v = value.trim();

    if (!v) return "This field is required";

    if (name === "email") {
      const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
      if (!ok) return "Please enter a valid email";
    }

    if (name === "phone") {
      // simple: allow +, digits, spaces, -, ()
      const ok = /^[+]?[\d\s\-()]{7,20}$/.test(v);
      if (!ok) return "Please enter a valid phone number";
    }

    if (name === "zip") {
      // simple: 3-10 alphanumeric
      const ok = /^[A-Za-z0-9\- ]{3,10}$/.test(v);
      if (!ok) return "Please enter a valid ZIP / postal code";
    }

    if (name === "name") {
      if (v.length < 2) return "Name must be at least 2 characters";
    }

    if (name === "address") {
      if (v.length < 5) return "Address must be at least 5 characters";
    }

    return "";
  };

  const validateAll = (data: typeof formData) => {
    const nextErrors: FormErrors = {};
    (Object.keys(data) as FormKeys[]).forEach((key) => {
      const msg = validateField(key, data[key]);
      if (msg) nextErrors[key] = msg;
    });
    return nextErrors;
  };

  // ✅ update your existing handleChange
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const key = name as FormKeys;

    setFormData((prev) => ({ ...prev, [key]: value }));

    // live validate after touched
    if (touched[key]) {
      const msg = validateField(key, value);
      setErrors((prev) => ({ ...prev, [key]: msg || undefined }));
    }
  };

  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    const key = name as FormKeys;

    setTouched((prev) => ({ ...prev, [key]: true }));

    const msg = validateField(key, value);
    setErrors((prev) => ({ ...prev, [key]: msg || undefined }));
  };

  const resetAllShippingData = () => {
    console.log("cliked removed data");
    // Clear only shipping-related keys
    localStorage.removeItem("selectedCount");
    localStorage.removeItem("totalValue");
    localStorage.removeItem("bulkCount");
    localStorage.removeItem("bulkPrice");
    localStorage.removeItem("cards");

    // ✅ UI instantly reset
    setSummary({
      selectedCount: 0,
      totalValue: "0.00",
      cards: "",
      bulkCount: 0,
      bulkPrice: 0,
    });

    // Reset React state
    setFormData({
      name: "",
      email: "",
      phone: "",
      address: "",
      country: "",
      state: "",
      city: "",
      zip: "",
    });

    setShipping(20);
    setDiscount(0);
    setFinalTotal("0.00");

    setError(null);
    setSuccess(null);

    // Optional: small delay for closing modal animation
    setTimeout(() => {
      setShowSuccessModal(false);
    }, 200);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!summary.cards) {
      console.log("cards not available");
      return;
    }

    // mark all touched so errors show
    const allTouched: Partial<Record<FormKeys, boolean>> = {};
    (Object.keys(formData) as FormKeys[]).forEach(
      (k) => (allTouched[k] = true),
    );
    setTouched(allTouched);

    const nextErrors = validateAll(formData);
    setErrors(nextErrors);

    if (Object.keys(nextErrors).length > 0) return; // ❌ stop submit

    setLoading(true);
    setError(null);
    setSuccess(null);

    if (!user) return;

    const payload = {
      ...formData,
      cards: summary.cards,
      user_id: user.userId,
    };

    try {
      const data = await saveShipping(user?.userId, user.token, payload);
      console.log("data", data);
      if (data.resp === "success") {
        dispatch(updateUser({ coins: data?.coins, gems: data?.gems }));
        await updateSession({ coins: data?.coins, gems: data?.gems });
        if (data?.msg == "verify") {
          const u = data?.url;
          window.open(u);
        } else {
          setShowSuccessModal(true);
          setTimeout(() => {
            // resetAllShippingData();
          }, 3000);
        }
      } else {
        setModalType("error");
        setModalMsg(data.msg || "something went wrong");
        setModalOpen(true);
        setError("Something went wrong. Try again.");
      }
    } catch (err) {
      console.log(err);
      setError("Network error — please try again.");
    }

    setLoading(false);
  };

  const backtoWithdraw = () => {
    router.push("/withdraw");
  };

  useEffect(() => {
    if (typeof window === "undefined") return;
    setSummary({
      selectedCount: Number(localStorage.getItem("selectedCount") ?? "0"),
      totalValue: localStorage.getItem("totalValue") ?? "0.00",
      cards: localStorage.getItem("cards") ?? "",
      bulkCount: Number(localStorage.getItem("bulkCount") ?? "0"),
      bulkPrice: Number(localStorage.getItem("bulkPrice") ?? "0.00"),
    });
  }, []);

  useEffect(() => {
    const cardsTotal = parseFloat(String(summary.totalValue)) || 0;
    const surcharge = Number(summary.bulkPrice) || 0;

    const nextShipping = cardsTotal >= 100 ? 0 : 20;
    setShipping(nextShipping);

    setFinalTotal((nextShipping + surcharge).toFixed(2));
  }, [summary.totalValue, summary.bulkPrice]);

  return (
    <div className="min-h-screen bg-black text-white">
      {user?.activeMode === "gems" ? (
        <NotAvailable />
      ) : (
        <>
          {/* Header */}
          <div className="z-10">
            <div className="container mx-auto py-4">
              <div className="flex items-center gap-4">
                <button
                  onClick={backtoWithdraw}
                  className="cursor-pointer text-xs md:text-base p-2 px-2 md:px-3 font-extrabold text-white bg-(--color-gray) hover:text-white italic font-sofia transition"
                >
                  &lt; BACK
                </button>
                <h1 className="text-sm md:text-xl font-extrabold italic">
                  SHIPPING DETAILS
                </h1>
              </div>
            </div>
          </div>

          {/* Content */}
          <div className="container mx-auto pb-16">
            {/* Order summary */}
            <div className="mt-6 md:mt-10 flex justify-center">
              <div className="w-full max-w-md bg-(--color-naviBlue) rounded-3xl border border-[#c9d3e6] px-6 py-6 md:px-8 md:py-8 text-sm md:text-base font-sofia">
                <h2 className="text-center font-extrabold italic tracking-wide mb-6 text-lg md:text-3xl">
                  SHIPPING ORDER
                </h2>

                <div className="grid grid-cols-3 text-xs md:text-xl font-bold mb-3">
                  <span>Items</span>
                  <span className="text-center">Quantity</span>
                  <span className="text-right">Price</span>
                </div>

                <div className="grid grid-cols-3 items-center mb-3">
                  <span>Cards</span>
                  <div className="flex justify-center">
                    <div className="w-14 md:w-16 text-center bg-white text-black rounded-md py-1 font-bold">
                      {summary.selectedCount}
                    </div>
                  </div>
                  <span className="text-right">${summary.totalValue}</span>
                </div>

                <div className="grid grid-cols-3 items-center mb-3 opacity-70">
                  <span>Bulk Cards</span>
                  <div className="flex justify-center">
                    <div className="w-14 md:w-16 text-center bg-white text-black rounded-md py-1 font-bold">
                      {summary.bulkCount}
                    </div>
                  </div>
                  <span className="text-right">${summary.bulkPrice}</span>
                </div>

                <div className="grid grid-cols-3 items-center mb-6">
                  <span>Shipping</span>
                  <div className="flex justify-center">
                    <div className="w-14 md:w-16 text-center bg-white text-black rounded-md py-1 font-bold">
                      {shipping === 0 ? "FREE" : "1"}
                    </div>
                  </div>
                  <span className="text-right">${shipping.toFixed(2)}</span>
                </div>
                {/* Discount / total */}
                <div className="flex justify-between items-center mb-1 text-xs md:text-xl">
                  <span className="font-extrabold italic">DISCOUNT</span>
                  <span className="font-bold">$ 0</span>
                </div>
                <div className="flex justify-between items-center text-sm md:text-xl mt-1">
                  <span className="font-extrabold italic">TOTAL</span>
                  <span className="font-extrabold text-(--color-blue)">
                    ${finalTotal}
                  </span>
                </div>
              </div>
            </div>

            {/* Form */}
            <form
              onSubmit={handleSubmit}
              className="mt-10 text-xs md:text-xl font-sofia"
            >
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {[
                  { label: "Address", name: "address" },
                  { label: "Full Name", name: "name" },
                  { label: "Email", name: "email", type: "email" },
                  { label: "Phone", name: "phone" },
                  { label: "Country", name: "country" },
                  { label: "State", name: "state" },
                  { label: "City", name: "city" },
                  { label: "Zip", name: "zip" },
                ].map((field) => {
                  const fieldName = field.name as FormKeys;
                  const fieldError = errors[fieldName];
                  const showError = touched[fieldName] && fieldError;
                  return (
                    <div
                      key={field.name}
                      className={`
        ${field.name === "address" ? "md:col-span-2" : ""}
      `}
                    >
                      <label className="block font-bold text-sm md:text-base font-sofia mb-1">
                        {field.label}
                      </label>

                      <input
                        name={field.name}
                        type={field.type || "text"}
                        value={(formData as any)[field.name]}
                        onChange={handleChange}
                        onBlur={handleBlur}
                        className={`w-full px-5 py-2 bg-[#161E2A] text-[#DBFAFF] font-onest text-sm md:text-base border placeholder:text-gray-400 outline-none
    ${showError ? "border-red-500" : "border-[#29313D]"}
  `}
                        placeholder={field.label}
                      />

                      {showError && (
                        <p className="mt-1 text-xs md:text-sm text-red-400 font-onest">
                          {fieldError}
                        </p>
                      )}
                    </div>
                  );
                })}
              </div>
              <div className="flex items-center flex-col md:flex-row mt-4 bg-[#161E2A] p-3 justify-between gap-3">
                <h1 className="font-bold text-base md:text-xl">
                  WITHDRAWING {summary.selectedCount} CARDS
                </h1>

                <InternalButton
                  disabled={loading || summary.selectedCount === 0}
                >
                  {summary.selectedCount === 0
                    ? "NO CARDS SELECTED"
                    : loading
                      ? "Processing..."
                      : "CONFIRM WITHDRAWAL"}
                </InternalButton>
              </div>
            </form>
          </div>

          {/* <ErrorModal message={error} onClose={() => setError(null)} /> */}

          <SuccessModal
            open={showSuccessModal}
            onClose={() => {
              setShowSuccessModal(false);
              resetAllShippingData();
              router.push("/withdraw"); // or wherever you want to send them
            }}
          />
        </>
      )}
      <AlertModal
        open={modalOpen}
        type={modalType}
        message={modalMsg}
        onClose={() => setModalOpen(false)}
      />
    </div>
  );
};

export default ShippingPage;
