"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import { Search, Sprout } from "lucide-react";
import { useSession } from "next-auth/react";
import Loading from "../../components/Loading";

/* ================= TYPES ================= */
type Item = {
  id: number;
  name: string;
  sku: string;
};

type Location = {
  id: number;
  name: string;
};

/* ================= PAGE ================= */
export default function CreateInventoryPage() {

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;

  const [items, setItems] = useState<Item[]>([]);
  const [locations, setLocations] = useState<Location[]>([]);

  const [item_id, setItemId] = useState("");
  const [location_id, setLocationId] = useState("");
  const [quantity, setQuantity] = useState(0);

  const [searchItem, setSearchItem] = useState("");
  const [loading, setLoading] = useState(false);
  const [loadingItems, setLoadingItems] = useState(false);

  const [mode, setMode] = useState<"new" | "existing">("new");

  /* ================= DEBOUNCE SEARCH ================= */
  useEffect(() => {
    const t = setTimeout(() => {
      fetchItems(searchItem);
    }, 400);

    return () => clearTimeout(t);
  }, [searchItem]);

  async function fetchItems(search = "") {
    try {
      setLoadingItems(true);

      const res = await fetch(
        `/api/items?search=${encodeURIComponent(search)}&limit=20`,
        { cache: "no-store" }
      );

      const json = await res.json();
      setItems(json.items || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoadingItems(false);
    }
  }

  useEffect(() => {
    // 1. tunggu session selesai load
    if (status === "loading") return;

    // 2. kalau belum login
    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }

    const allowedRoles = ["ADMIN"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/inventory");
      return;
    }

    const fetchLoc = async () => {
      const res = await fetch("/api/gudang");
      const json = await res.json();
      setLocations(json.locations || []);
    };

    fetchLoc();
    fetchItems("");
  }, [status, currentUser, router]);

  useEffect(() => {
    const checkExisting = async () => {
      if (!item_id || !location_id) return;

      const res = await fetch(
        `/api/inventory?item_id=${item_id}&location_id=${location_id}`
      );
      const json = await res.json();

      if (json.data?.length > 0) {
        setMode("existing");
      } else {
        setMode("new");
      }
    };

    checkExisting();
  }, [item_id, location_id]);

    // optional safety (biar tidak flash UI)
  if (!session) return null;
  
  async function handleSubmit() {
    if (!item_id || !location_id || quantity <= 0) {
      alert("Lengkapi data terlebih dahulu");
      return;
    }

    try {
      setLoading(true);

      const res = await fetch("/api/inventory", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          item_id: Number(item_id),
          location_id: Number(location_id),
          quantity: Number(quantity),
        }),
      });

      if (!res.ok) throw new Error("Failed");

      alert(
        mode === "existing"
          ? "Stock berhasil ditambahkan 🌱"
          : "Inventory baru berhasil dibuat 🌱"
      );

      router.push("/inventory");
    } catch (err) {
      console.error(err);
      alert("Gagal menyimpan inventory");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="p-6 space-y-6">

      {/* ================= HEADER ================= */}
      <motion.div
        initial={{ opacity: 0, y: 40, scale: 0.97 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        className="relative rounded-[36px] overflow-hidden"
      >
        <div className="absolute inset-0 bg-linear-to-br from-green-500 via-emerald-400 to-lime-300" />
        <div className="absolute inset-0 bg-black/15" />
        <div className="absolute inset-0 backdrop-blur-3xl" />

        <div className="absolute -top-10 -left-10 w-40 h-40 bg-white/20 rounded-full blur-3xl" />

        <div className="relative p-8 border border-white/30 rounded-[36px]
        shadow-[0_25px_80px_rgba(0,0,0,0.2)]">

          <div className="flex items-center gap-3">
            <div className="p-3 rounded-2xl bg-white/30 shadow-inner">
              <Sprout className="w-7 h-7 text-green-900" />
            </div>

            <h1 className="text-3xl font-bold text-green-900 tracking-tight">
              Tambah Inventory
            </h1>
          </div>

          <p className="text-sm text-green-900/70 mt-3">
            {mode === "existing"
              ? "Mode tambah stok (existing item)"
              : "Buat inventory baru"}
          </p>
        </div>
      </motion.div>

      {/* ================= FORM ================= */}
      <motion.div
        initial={{ opacity: 0, scale: 0.96 }}
        animate={{ opacity: 1, scale: 1 }}
        className="relative rounded-[36px] p-[1.5px]
        bg-linear-to-br from-green-200 via-white to-green-100"
      >
        <div className="absolute inset-0 rounded-[36px]
        shadow-[0_30px_80px_rgba(0,0,0,0.12)]" />

        <div className="relative rounded-[34px] bg-white/80 backdrop-blur-2xl
        border border-white/60
        shadow-[inset_0_1px_0_rgba(255,255,255,0.6),0_10px_40px_rgba(0,0,0,0.1)]
        p-7 space-y-6">

          {/* ================= ITEM ================= */}
          <div>
            <label className="text-xs text-gray-600">Barang</label>

            <div className="relative mt-1">
              <Search className="absolute left-3 top-3.5 w-4 h-4 text-gray-400" />

              <div className="rounded-xl p-px bg-linear-to-br from-green-200 via-white to-green-100">
                <input
                  value={searchItem}
                  onChange={(e) => setSearchItem(e.target.value)}
                  placeholder="Cari SKU / nama barang..."
                  className="w-full pl-9 pr-3 py-3 rounded-xl
                  bg-white/95
                  shadow-[inset_0_3px_8px_rgba(0,0,0,0.08),0_6px_20px_rgba(0,0,0,0.05)]
                  focus:outline-none
                  focus:ring-2 focus:ring-green-400/60
                  transition-all"
                />
              </div>
            </div>

            {/* SELECT 3D */}
            <div className="mt-2 relative rounded-xl p-px
              bg-linear-to-br from-emerald-200 via-white to-green-100">

              <div className="rounded-xl bg-white/95
              shadow-[inset_0_3px_8px_rgba(0,0,0,0.08),0_6px_20px_rgba(0,0,0,0.05)]">

                <select
                  value={item_id}
                  onChange={(e) => setItemId(e.target.value)}
                  className="w-full px-4 py-3 rounded-xl
                  bg-transparent appearance-none
                  focus:outline-none
                  focus:ring-2 focus:ring-emerald-400/60"
                >
                  <option value="">Pilih Barang</option>
                  {loadingItems && <option disabled>Loading...</option>}
                  {items.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.sku} - {item.name}
                    </option>
                  ))}
                </select>

                <div className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
                  ▾
                </div>
              </div>
            </div>
          </div>

          {/* ================= LOCATION ================= */}
          <div>
            <label className="text-xs text-gray-600">Gudang</label>

            <div className="relative rounded-xl p-px
            bg-linear-to-br from-green-200 via-white to-green-100">

              <div className="rounded-xl bg-white/95
              shadow-[inset_0_3px_8px_rgba(0,0,0,0.08),0_6px_20px_rgba(0,0,0,0.05)]">

                <select
                  value={location_id}
                  onChange={(e) => setLocationId(e.target.value)}
                  className="w-full px-4 py-3 rounded-xl
                  bg-transparent appearance-none
                  focus:outline-none
                  focus:ring-2 focus:ring-green-400/60"
                >
                  <option value="">Pilih Gudang</option>
                  {locations.map((loc) => (
                    <option key={loc.id} value={loc.id}>
                      {loc.name}
                    </option>
                  ))}
                </select>

                <div className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400">
                  ▾
                </div>
              </div>
            </div>
          </div>

          {/* ================= QTY ================= */}
          <div>
            <label className="text-xs text-gray-600">Quantity</label>

            <div className="rounded-xl p-px
            bg-linear-to-br from-green-200 via-white to-green-100">

              <input
                type="number"
                value={quantity}
                onChange={(e) => setQuantity(Number(e.target.value))}
                className="w-full px-4 py-3 rounded-xl
                bg-white/95
                shadow-[inset_0_3px_10px_rgba(0,0,0,0.08),0_6px_20px_rgba(0,0,0,0.05)]
                focus:outline-none
                focus:ring-2 focus:ring-green-400/60
                transition-all"
                placeholder="Jumlah stok"
              />
            </div>
          </div>

          {/* ================= INFO MODE ================= */}
          <div className={`p-4 rounded-2xl text-sm font-medium
            shadow-inner border
            ${mode === "existing"
              ? "bg-yellow-100/80 text-yellow-800 border-yellow-200"
              : "bg-green-100/80 text-green-800 border-green-200"}
          `}>
            {mode === "existing"
              ? "⚠️ Item sudah ada → stok akan ditambahkan"
              : "✅ Item baru → akan dibuat inventory baru"}
          </div>

          {/* ================= BUTTON ================= */}
          <button
            onClick={handleSubmit}
            disabled={loading}
            className="
            w-full py-3 rounded-2xl
            bg-linear-to-r from-emerald-600 to-green-500
            text-white font-semibold
            shadow-[0_12px_30px_rgba(16,185,129,0.5)]
            hover:shadow-[0_18px_45px_rgba(16,185,129,0.7)]
            hover:-translate-y-[1px]
            active:translate-y-[1px]
            transition-all duration-200
            "
          >
            {loading ? "Menyimpan..." : "Simpan Inventory 🌱"}
          </button>

        </div>
      </motion.div>
    </div>
  );
}