"use client";
import { useEffect, useState } from "react";
import Settings from "./store-settings";
import { useRouter } from "next/navigation";
import axios from "axios";

const API_URL = "https://ebay.backend.data4autos.com/api/ebay/inventory/locations";

export default function Page() {
  const router = useRouter()

  const [locations, setLocations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [payment, setPayment] = useState<any>(null);

  useEffect(() => {
    const role = localStorage.getItem("user_role");
    const sessionId = localStorage.getItem("payment_session");

    // ✅ Admins and Partners can access directly (skip payment check)
    if (role === "admin" || role === "partner") {
      return;
    }

    // 🚫 If no payment session, redirect to pricing
    if (!sessionId) {
      router.push("/pricing");
      return;
    }

    // ✅ Otherwise, check payment details
    const fetchPaymentDetails = async () => {
      try {
        const res: any = await axios.get(
          "https://ebay.backend.data4autos.com/api/payment/details",
          { params: { session_id: sessionId } }
        );
        setPayment(res.data.payment);
      } catch (err) {
        console.error("Error fetching payment details:", err);
      }
    };

    fetchPaymentDetails();
  }, [router]);

  useEffect(() => {
    const fetchLocations = async () => {
      try {
        const userId = typeof window !== 'undefined' ? sessionStorage.getItem('USERID') : null;
        const EBAYSTOREID = typeof window !== 'undefined' ? sessionStorage.getItem('EBAYSTOREID') : null;
        const res = await fetch(API_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ accessToken: "clientaccesstoken", userKey: EBAYSTOREID }),
        });
        const data = await res.json();
        setLocations(data.locations || []);
      } catch (err) {
        console.error("❌ Error fetching locations:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchLocations();
  }, []);

  const handleSaveExisting = () => {
    const selected = locations.find((loc) => loc.merchantLocationKey === selectedKey);
    console.log("✅ Selected Location:", selected);
  };

  const handleSaveNew = (payload: any) => {
    console.log("📦 New Location Payload:", payload);
  };


  if (loading)
    return (
      <div className="flex items-center justify-center min-h-[83vh] bg-gradient-to-br from-[#e0f7ff] to-white text-lg font-medium">
        ⏳ Loading eBay Locations...
      </div>
    );
  return (
    <div className="min-h-[83vh] flex items-center justify-center  bg-gradient-to-br from-[#00d1ff]/10 via-white to-[#00d1ff]/20 p-2  md:p-8">
      <div className="max-w-7xl mx-auto  backdrop-blur-md border border-white/40 shadow-2xl rounded-3xl p-3 md:p-8 transition-all duration-500">
        <h1 className="text-3xl font-bold text-center text-[#00d1ff] mb-3 drop-shadow-sm">
          eBay Locations
        </h1>

        {!showForm ? (
          <>
            {/* Locations Grid */}
            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {locations.map((loc, idx) => (
                <div
                  key={idx}
                  onClick={() => setSelectedKey(loc.merchantLocationKey)}
                  className={`relative p-6 rounded-2xl border cursor-pointer transform transition-all duration-300 ${selectedKey === loc.merchantLocationKey
                    ? "bg-gradient-to-br from-[#00d1ff] to-[#007bff] text-white shadow-lg scale-105"
                    : "bg-white hover:shadow-xl hover:-translate-y-1 border-gray-200"
                    }`}
                >
                  <div className="flex justify-between items-center">
                    <h2 className="text-lg font-semibold">{loc.merchantLocationKey || "Unnamed Location"}</h2>
                    {selectedKey === loc.merchantLocationKey && (
                      <span className="text-xs bg-white/30 px-2 py-1 rounded-md font-medium">
                        Selected
                      </span>
                    )}
                  </div>

                  <p
                    className={`mt-2 text-sm ${selectedKey === loc.merchantLocationKey ? "text-white/90" : "text-gray-600"
                      }`}
                  >
                    📞 {loc.phone || "N/A"}
                  </p>
                  <p
                    className={`text-sm ${selectedKey === loc.merchantLocationKey ? "text-white/90" : "text-gray-600"
                      }`}
                  >
                    📍 {loc.location?.address?.addressLine1},{" "}
                    {loc.location?.address?.city},{" "}
                    {loc.location?.address?.stateOrProvince}{" "}
                    {loc.location?.address?.postalCode}
                  </p>

                  <div className="mt-4 text-xs opacity-70">
                    Key: {loc.merchantLocationKey}
                  </div>
                </div>
              ))}
            </div>

            {/* Buttons */}
            <div className="mt-10 flex flex-wrap justify-center gap-6">
              <button
                onClick={handleSaveExisting}
                disabled={!selectedKey}
                className={`px-6 py-3 rounded-full text-white font-semibold transition-all shadow-md ${selectedKey
                  ? "bg-gradient-to-r from-[#00d1ff] to-[#007bff] hover:scale-105"
                  : "bg-gray-400 cursor-not-allowed"
                  }`}
              >
                Save Selected
              </button>

              <button
                onClick={() => setShowForm(true)}
                className="px-6 py-3 rounded-full font-semibold text-[#00d1ff] border border-[#00d1ff] hover:bg-[#00d1ff] hover:text-white transition-all shadow-sm"
              >
                + Create New Location
              </button>
            </div>
          </>
        ) : (
          <Settings onSave={handleSaveNew} />
        )}
      </div>
    </div>
  );
}
