"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import api from "@/lib/api";
import toast from "react-hot-toast";

import {
  Plus,
  Pencil,
  Trash2,
} from "lucide-react";

export default function VendorProductsPage() {
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadProducts();
  }, []);

  const loadProducts = async () => {
    try {
      const token = localStorage.getItem("auth_token");

      const res = await api.get("/vendor/products", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      setProducts(res.data.data.data || []);
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  const deleteProduct = async (id: number) => {
    const confirmDelete = confirm(
      "Delete this product?"
    );

    if (!confirmDelete) return;

    try {
      const token = localStorage.getItem("auth_token");

      await api.delete(`/vendor/products/${id}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      loadProducts();
    } catch (error) {
      console.log(error);

      toast.error("Delete failed");
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        Loading Products...
      </div>
    );
  }

  return (
    <main className="min-h-screen bg-[#f7fff8] py-10">
      <section className="max-w-7xl mx-auto px-4">

        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-4xl font-black">
              Products
            </h1>

            <p className="text-slate-500 mt-2">
              Manage your products
            </p>
          </div>

          <Link
            href="/vendor/products/create"
            className="bg-green-600 text-white px-6 py-3 rounded-2xl font-bold flex items-center gap-2"
          >
            <Plus size={18} />
            Add Product
          </Link>
        </div>

        <div className="bg-white rounded-[2rem] border border-green-100 overflow-hidden">

          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-100">
                <th className="p-5 text-left">
                  Product
                </th>

                <th className="p-5 text-left">
                  Price
                </th>

                <th className="p-5 text-left">
                  Stock
                </th>

                <th className="p-5 text-left">
                  Type
                </th>

                <th className="p-5 text-left">
                  Status
                </th>

                <th className="p-5 text-right">
                  Action
                </th>
              </tr>
            </thead>

            <tbody>
              {products.map((product) => (
                <tr
                  key={product.id}
                  className="border-b border-slate-100"
                >
                  <td className="p-5">
                    <div className="flex items-center gap-4">
                      <img
                        src={
                          product.image ||
                          "/placeholder.jpg"
                        }
                        className="w-16 h-16 rounded-xl object-cover"
                      />

                      <div>
                        <h3 className="font-bold">
                          {product.name}
                        </h3>

                        <p className="text-sm text-slate-500">
                          {product.slug}
                        </p>
                      </div>
                    </div>
                  </td>

                  <td className="p-5">
                    ৳{product.price}
                  </td>

                  <td className="p-5">
                    {product.stock_quantity}
                  </td>

                  <td className="p-5 capitalize">
                    {product.product_type}
                  </td>

                  <td className="p-5">
                    <StatusBadge
                      status={product.status}
                    />
                  </td>

                  <td className="p-5">
                    <div className="flex justify-end gap-3">

                      <Link
                        href={`/vendor/products/${product.id}/edit`}
                        className="w-10 h-10 rounded-xl bg-blue-50 text-blue-600 flex items-center justify-center"
                      >
                        <Pencil size={18} />
                      </Link>

                      <button
                        onClick={() =>
                          deleteProduct(product.id)
                        }
                        className="w-10 h-10 rounded-xl bg-red-50 text-red-600 flex items-center justify-center"
                      >
                        <Trash2 size={18} />
                      </button>

                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

        </div>
      </section>
    </main>
  );
}

function StatusBadge({
  status,
}: {
  status: string;
}) {
  const colors: any = {
    published:
      "bg-green-100 text-green-700",

    pending:
      "bg-yellow-100 text-yellow-700",

    rejected:
      "bg-red-100 text-red-700",

    draft:
      "bg-slate-100 text-slate-700",
  };

  return (
    <span
      className={`px-3 py-1 rounded-full text-xs font-bold ${colors[status]}`}
    >
      {status}
    </span>
  );
}