"use client";

import { motion } from "framer-motion";
import { Pencil, Trash2, Eye, Printer } from "lucide-react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useSession } from "next-auth/react";
import { formatNumber } from "../components/formatNumber";
type Inventory = {
  item_id: number;
  location_id: number;

  sku: string;
  name: string;
  category: string;
  unit: string;

  location_name: string;

  quantity: number;
  reserved_quantity: number;

  barcode?: string | null;
};

export function InventoryTable({
  data,
  page,
  limit,
  selectedItems,
  toggleSelectItem,
  handlePrintQr,
}: {
  data: Inventory[];
  page: number;
  limit: number;
  selectedItems: string[];
  toggleSelectItem: (key: string) => void;
  handlePrintQr: (
    type: "single" | "selected" | "all",
    row?: Inventory
  ) => void;
}) {

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;
  const allowedRoles = ["ADMIN", "OPERATOR", "SUPERVISOR"];

  const allowed = allowedRoles.includes(currentUser?.role) ? true : false;

  /* ================= DELETE HANDLER ================= */
  const handleDelete = async (item: Inventory) => {
    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/satuan");
      return;
    }

    const confirmDelete = confirm(
      `Hapus inventory ${item.name} di ${item.location_name}?`
    );

    if (!confirmDelete) return;

    try {
      await fetch(
        `/api/inventory?item_id=${item.item_id}&location_id=${item.location_id}`,
        {
          method: "DELETE",
        }
      );

      alert("Berhasil dihapus");
      router.refresh();
    } catch (err) {
      console.error(err);
      alert("Gagal menghapus data");
    }
  };

    // optional safety (biar tidak flash UI)
  if (!session) return null;

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.98 }}
      animate={{ opacity: 1, scale: 1 }}
      className="relative rounded-3xl p-px bg-linear-to-br from-green-200/40 to-transparent"
    >
      <div className="relative rounded-3xl bg-white/85 backdrop-blur-2xl border border-white/40 shadow-xl overflow-hidden">

        <div className="overflow-x-auto">
          <table className="w-full text-sm">

            {/* ================= HEADER ================= */}
            <thead className="bg-linear-to-r from-green-50 to-emerald-50 text-gray-600">
              <tr>
                <th className="px-4 py-4 text-center w-10">#</th>
                <th className="px-4 py-4 text-right font-semibold w-14">No</th>
                <th className="px-5 py-4 text-left font-semibold w-35">SKU</th>
                <th className="px-5 py-4 text-left font-semibold min-w-55">Produk</th>
                <th className="px-5 py-4 text-left font-semibold w-55">Gudang</th>
                <th className="px-5 py-4 text-right font-semibold">Stok</th>
                <th className="px-5 py-4 text-right font-semibold">Reserved</th>
                <th className="px-5 py-4 text-right font-semibold">Available</th>

                {/* ✅ ACTION COLUMN */}
                <th className="px-5 py-4 text-center font-semibold w-30">
                  Action
                </th>
              </tr>
            </thead>

            {/* ================= BODY ================= */}
            <tbody>
              {data.length === 0 ? (
                <tr>
                  <td colSpan={8} className="text-center py-10 text-gray-400">
                    Tidak ada data stok
                  </td>
                </tr>
              ) : (
                data.map((row, i) => {
                  const available =
                    row.quantity - row.reserved_quantity;

                  const no = (page - 1) * limit + i + 1;

                  return (
                    <motion.tr
                      key={i}
                      initial={{ opacity: 0, y: 8 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: i * 0.03 }}
                      className="border-t border-green-50 hover:bg-green-50/60 transition"
                    >
                      <td className="px-4 py-4 text-center">
                        <input
                          type="checkbox"
                          checked={selectedItems.includes(
                            `${row.item_id}-${row.location_id}`
                          )}
                          onChange={() =>
                            toggleSelectItem(
                              `${row.item_id}-${row.location_id}`
                            )
                          }
                          className="w-4 h-4"
                        />
                      </td>
                      {/* NO */}
                      <td className="px-4 py-4 text-right text-gray-400 text-xs font-medium">
                        {no}
                      </td>

                      {/* SKU */}
                      <td className="px-5 py-4">
                        <span className="font-mono text-xs text-gray-500 break-all">
                          {row.sku}
                        </span>
                      </td>

                      {/* PRODUK */}
                      <td className="px-5 py-4">
                        <div className="font-semibold text-green-900 leading-tight line-clamp-2">
                          {row.name}
                        </div>
                        <div className="text-xs text-gray-500 mt-0.5 truncate">
                          {row.category} • {row.unit}
                        </div>
                      </td>

                      {/* GUDANG */}
                      <td className="px-5 py-4">
                        <span className="px-3 py-1 rounded-full bg-green-100 text-green-700 text-xs font-medium inline-block max-w-[200px] truncate">
                          {row.location_name}
                        </span>
                      </td>

                      {/* STOK */}
                      <td className="px-5 py-4 text-right font-semibold text-green-800">
                        {formatNumber(row.quantity)}
                      </td>

                      {/* RESERVED */}
                      <td className="px-5 py-4 text-right text-yellow-600 font-medium">
                        {formatNumber(row.reserved_quantity)}
                      </td>

                      {/* AVAILABLE */}
                      <td className="px-5 py-4 text-right">
                        <span
                          className={`inline-block min-w-17.5 text-right font-bold px-3 py-1 rounded-lg
                          ${
                            available <= 0
                              ? "bg-red-100 text-red-600"
                              : available < 10
                              ? "bg-yellow-100 text-yellow-700"
                              : "bg-green-100 text-green-700"
                          }`}
                        >
                          {formatNumber(available)}
                        </span>
                      </td>

                      {/* ================= ACTION ================= */}
                     <td className="px-5 py-4 text-right">
                          <div className="flex gap-2 justify-end">

                          <Link
                                // href={`/inventory/${row.item_id}/${row.location_id}`}
                                href={`/inventory/${row.location_id}/${row.item_id}`}
                                className="p-2 rounded-lg bg-green-100 text-green-600"
                              >
                                <Eye className="w-4 h-4" />
                          </Link>
                          {allowed && (
                            <Link
                              href={`/inventory/edit/${row.item_id}/${row.location_id}`}
                              className="p-2 rounded-lg bg-blue-100 text-blue-600"
                            >
                              <Pencil className="w-4 h-4" />
                            </Link>
                          )}
                       
                            {/* <button className="p-2 rounded-lg bg-red-100 text-red-600">
                              <Trash2 className="w-4 h-4" />
                            </button> */}
                            {row.barcode && (
                          <button
                            onClick={() => handlePrintQr("single", row)}
                            className="p-2 rounded-lg bg-indigo-100 text-indigo-600"
                          >
                            <Printer className="w-4 h-4" />
                          </button>
                        )}

                          </div>
                        </td>
                    </motion.tr>
                  );
                })
              )}
            </tbody>

          </table>
        </div>
      </div>
    </motion.div>
  );
}