"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { GudangTable } from "./GudangTable";
import { Select3D } from "../components/Select3D";
import { Plus } from "lucide-react";

import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Loading from "../components/Loading";


/* ================= TYPES ================= */
type Location = {
  id: number;
  code: string;
  name: string;
  type: "WAREHOUSE" | "STORE" | "TRANSIT";
  address: string;
  total_items: number;
  total_sku: number; // ✅ TAMBAH
};

/* ================= PAGE ================= */
export default function GudangPage() {

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;

  const [data, setData] = useState<Location[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);

  const [search, setSearch] = useState<string>("");
  const [type, setType] = useState<string>("");

  const [page, setPage] = useState<number>(1);
  const [limit] = useState<number>(10);

  /* ================= RESET PAGE ================= */
  useEffect(() => {
    setPage(1);
  }, [search, type]);


  /* ================= FETCH DATA ================= */
  async function fetchData() {
    try {
      setLoading(true);

      const res = await fetch(
        `/api/gudang?search=${encodeURIComponent(
          search
        )}&type=${type}&page=${page}&limit=${limit}`,
        {
          cache: "no-store",
        }
      );

      console.log("📡 RESPONSE:", res);

      if (!res.ok) {
        throw new Error("Failed to fetch data");
      }

      const json = await res.json();
      console.log("📦 JSON:", json);

      const safeData: Location[] = (json.locations || []).map((item: any) => ({
        id: item.id,
        code: item.code,
        name: item.name,
        type: item.type,
        address: item.address,
        total_items: Number(item.total_items ?? 0),
        total_sku: Number(item.total_sku ?? 0), // ✅ TAMBAH
      }));

      setData(safeData);
      setTotal(Number(json.total ?? 0));
    } catch (err) {
      console.error("❌ Fetch error:", err);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    // 1. tunggu session selesai load
    if (status === "loading") return;

    // 2. kalau belum login
    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }

    fetchData();
  }, [search, type, page, limit, status, router]);
    // optional safety (biar tidak flash UI)
  if (!session) return null;
  const totalPage = Math.max(1, Math.ceil(total / limit));

  return (
    <div className="space-y-6">

      {/* ================= HEADER ================= */}
      <motion.div
        initial={{ opacity: 0, y: 15 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-4xl overflow-hidden"
      >
        {/* BG */}
        <div className="absolute inset-0 bg-linear-to-br from-green-200 via-emerald-100 to-lime-100" />
        <div className="absolute inset-0 bg-white/40 backdrop-blur-3xl" />

        {/* CONTENT */}
        <div className="relative z-10 p-6 rounded-4xl border border-white/40 bg-white/60 backdrop-blur-2xl shadow-xl">
          
          <div className="flex flex-col md:flex-row md:justify-between gap-6">

            {/* LEFT */}
            <div>
              <h1 className="text-2xl font-bold text-green-900">
                🔄 Mutasi Stock
              </h1>
              <p className="text-sm text-gray-600">
                Total Data: <b>{total}</b>
              </p>
            </div>

            {/* RIGHT FILTER + BUTTON */}
            <div className="flex flex-col sm:flex-row gap-3 items-end sm:items-center">

              {/* SEARCH */}
              <Input
                value={search}
                onChange={setSearch}
                placeholder="Cari kode / nama..."
              />

              {/* SELECT 3D */}
              <Select3D
                value={type}
                onChange={setType}
                placeholder="Semua Tipe"
                options={[
                  { label: "Semua Tipe", value: "" },
                  { label: "WAREHOUSE", value: "WAREHOUSE" },
                  { label: "STORE", value: "STORE" },
                  { label: "TRANSIT", value: "TRANSIT" },
                ]}
              />

              {/* ✅ ADD BUTTON */}
              <button
                onClick={() => router.push("/gudang/create")}
                className="flex items-center gap-2 px-4 py-2 rounded-xl 
                bg-linear-to-r from-green-600 to-emerald-500 
                text-white text-sm font-medium shadow-lg 
                hover:scale-[1.02] transition"
              >
                <Plus className="w-4 h-4" />
                Tambah Gudang
              </button>

            </div>
          </div>
        </div>
      </motion.div>

      {/* ================= LOADING ================= */}
      {loading && (
        <Loading pageName="Data Gudang"/>
      )}

      {/* ================= TABLE ================= */}
      <GudangTable data={data} page={page} limit={limit} />

      {/* ================= PAGINATION ================= */}
      <div className="flex justify-between items-center">

        <button
          disabled={page === 1}
          onClick={() => setPage((p) => p - 1)}
          className="px-4 py-2 rounded-xl bg-white shadow-md hover:shadow-lg disabled:opacity-50"
        >
          ← Previous
        </button>

        <span className="text-sm text-gray-600">
          Page {page} / {totalPage}
        </span>

        <button
          disabled={page >= totalPage}
          onClick={() => setPage((p) => p + 1)}
          className="px-4 py-2 rounded-xl bg-white shadow-md hover:shadow-lg disabled:opacity-50"
        >
          Next →
        </button>

      </div>

    </div>
  );
}

/* ================= INPUT ================= */
type InputProps = {
  value: string;
  onChange: (val: string) => void;
  placeholder?: string;
};

function Input({ value, onChange, placeholder }: InputProps) {
  return (
    <input
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      className="w-56 px-3 py-2 rounded-xl border border-green-200 text-sm
      focus:outline-none focus:ring-2 focus:ring-green-400 bg-white/80"
    />
  );
}