"use client";

import { motion } from "framer-motion";
import Link from "next/link";
import { Eye, Printer } from "lucide-react";

/* ================= TYPES ================= */
type Item = {
  id: number;
  sku: string;
  name: string;
  category: string;
  unit: string;
  is_active: boolean;
  description: string;
  barcode: string | null;
};

export function ItemsTable({
  data,
  page,
  limit,
  selectedItems,
  toggleSelectItem,
}: {
  data: Item[];
  page: number;
  limit: number;
  selectedItems: number[];
  toggleSelectItem: (id: number) => void;
}) {

    // GANTI function handlePrintQr MENJADI INI

   // GANTI handlePrintQr MENJADI INI
// ukuran disamakan dengan print multiple (QR 120x120)

  const handlePrintQr = (item: Item) => {
      if (!item.barcode) {
        alert("QR Code / Barcode belum tersedia");
        return;
      }

      const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(
        item.barcode
      )}`;

      const win = window.open("", "_blank", "width=500,height=700");
      if (!win) return;

      win.document.write(`
        <html>
          <head>
            <title>Preview Print QR Code</title>

            <style>
              @page{
                size:A4 portrait;
                margin:8mm;
              }

              body{
                margin:0;
                padding:20px;
                font-family:Arial,sans-serif;
                background:#f5f7fa;
              }

              .wrapper{
                max-width:320px;
                margin:auto;
              }

              .card{
                background:white;
                border:1px solid #ddd;
                border-radius:10px;
                padding:10px;
                text-align:center;
                box-shadow:0 8px 24px rgba(0,0,0,.08);
              }

              h2{
                margin:0;
                font-size:13px;
                line-height:1.25;
                font-weight:700;
              }

              .sku{
                margin-top:4px;
                font-size:11px;
                color:#666;
              }

              img{
                width:120px;
                height:120px;
                margin:8px auto;
                display:block;
              }

              .barcode{
                font-size:11px;
                font-weight:700;
                word-break:break-all;
                line-height:1.15;
              }

              .btns{
                margin-top:14px;
                display:flex;
                gap:8px;
                justify-content:center;
              }

              button{
                border:none;
                padding:9px 14px;
                border-radius:8px;
                cursor:pointer;
                font-weight:600;
              }

              .print{
                background:#16a34a;
                color:white;
              }

              .close{
                background:#e5e7eb;
              }

              @media print{
                body{
                  background:white;
                  padding:0;
                }

                .btns{
                  display:none;
                }

                .card{
                  box-shadow:none;
                }
              }
            </style>
          </head>

          <body>
            <div class="wrapper">
              <div class="card">
                <h2>${item.name}</h2>
                <div class="sku">${item.sku}</div>

                <img src="${qrUrl}" />

                <div class="barcode">${item.barcode}</div>

                <div class="btns">
                  <button class="print" onclick="window.print()">
                    Print
                  </button>

                  <button class="close" onclick="window.close()">
                    Close
                  </button>
                </div>
              </div>
            </div>
          </body>
        </html>
      `);

      win.document.close();
    };


  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"
    >
      {/* DEPTH BACKGROUND */}
      <div className="absolute inset-0 translate-y-6 bg-green-300/20 blur-3xl rounded-3xl" />

      <div className="relative rounded-3xl bg-white/85 backdrop-blur-2xl border border-white/40 shadow-xl overflow-hidden">

      <div className="overflow-x-auto rounded-3xl">
        <table className="w-full min-w-[980px] text-sm">
          
          {/* ================= HEADER ================= */}
          <thead className="sticky top-0 z-10 bg-gradient-to-r from-green-50 via-white to-emerald-50 text-gray-600 border-b border-green-100">
            <tr>
              <th className="px-3 py-4 text-center w-12">
                <div className="flex justify-center">
                  #
                </div>
              </th>

              <th className="px-3 py-4 text-left w-16 font-semibold">No</th>

              <th className="px-3 py-4 text-left font-semibold whitespace-nowrap">
                SKU
              </th>

              <th className="px-3 py-4 text-left font-semibold min-w-[220px]">
                Nama Item
              </th>

              <th className="px-3 py-4 text-left font-semibold whitespace-nowrap">
                Kategori
              </th>

              <th className="px-3 py-4 text-left font-semibold min-w-[170px]">
                QR Code
              </th>

              <th className="px-3 py-4 text-center font-semibold whitespace-nowrap">
                Status
              </th>

              <th className="px-3 py-4 text-center font-semibold min-w-[210px]">
                Action
              </th>
            </tr>
          </thead>

          {/* ================= BODY ================= */}
          <tbody className="divide-y divide-green-50">
            {data.length === 0 ? (
              <tr>
                <td colSpan={8} className="py-14 px-4 text-center">
                  <div className="flex flex-col items-center gap-2 text-gray-400">
                    <div className="text-4xl">📦</div>
                    <p className="text-sm font-medium">Tidak ada data</p>
                  </div>
                </td>
              </tr>
            ) : (
              data.map((item, i) => {
                const no = (page - 1) * limit + i + 1;

                return (
                  <motion.tr
                    key={item.id}
                    initial={{ opacity: 0, y: 8 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.03 }}
                    className="group hover:bg-green-50/70 transition"
                  >
                    {/* CHECKBOX */}
                    <td className="px-3 py-4 text-center">
                      <input
                        type="checkbox"
                        checked={selectedItems.includes(item.id)}
                        onChange={() => toggleSelectItem(item.id)}
                        className="w-4 h-4 rounded border-gray-300 text-green-600 focus:ring-green-500"
                      />
                    </td>

                    {/* NO */}
                    <td className="px-3 py-4 text-gray-500 font-medium">
                      {no}
                    </td>

                    {/* SKU */}
                    <td className="px-3 py-4">
                      <span className="font-mono text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded-lg">
                        {item.sku}
                      </span>
                    </td>

                    {/* NAMA */}
                    <td className="px-3 py-4">
                      <div className="flex flex-col">
                        <span className="font-semibold text-green-900 leading-tight">
                          {item.name}
                        </span>

                        <span className="text-xs text-gray-500 mt-1">
                          {item.unit}
                        </span>
                      </div>
                    </td>

                    {/* KATEGORI */}
                    <td className="px-3 py-4">
                      <span className="inline-flex px-2.5 py-1 rounded-full text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-100">
                        {item.category}
                      </span>
                    </td>

                    {/* BARCODE */}
                    <td className="px-3 py-4">
                      <span className="font-mono text-xs text-gray-500 break-all">
                        {item.barcode || "-"}
                      </span>
                    </td>

                    {/* STATUS */}
                    <td className="px-3 py-4 text-center">
                      <span
                        className={`inline-flex px-3 py-1 rounded-full text-xs font-semibold ${
                          item.is_active
                            ? "bg-green-100 text-green-700"
                            : "bg-gray-200 text-gray-500"
                        }`}
                      >
                        {item.is_active ? "Active" : "Inactive"}
                      </span>
                    </td>

                    {/* ACTION */}
                    <td className="px-3 py-4">
                      <div className="flex flex-wrap justify-center gap-2">
                        <Link
                          href={`/items/${item.id}`}
                          className="inline-flex items-center gap-1 px-3 py-2 rounded-xl
                          bg-white border border-green-200
                          text-green-800 text-xs font-semibold
                          shadow-sm hover:shadow-md hover:-translate-y-[1px]
                          transition"
                        >
                          <Eye size={14} />
                          Details
                        </Link>

                        <button
                          onClick={() => handlePrintQr(item)}
                          className="inline-flex items-center gap-1 px-3 py-2 rounded-xl
                          bg-gradient-to-r from-indigo-500 to-blue-500
                          text-white text-xs font-semibold
                          shadow-sm hover:shadow-md hover:-translate-y-[1px]
                          transition"
                        >
                          <Printer size={14} />
                          Print QR
                        </button>
                      </div>
                    </td>
                  </motion.tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
      </div>
    </motion.div>
  );
}