"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { ExternalLink, Eye, EyeOff, Pencil, Trash2 } from "lucide-react";
import ProductThumb from "@/components/app/product-thumb";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { statusBadgeClass, type Category, type Product } from "./types";

type Props = {
  app: string;
  products: Product[];
  categories: Category[];
  togglingId: string | null;
  onToggleStatus: (product: Product) => void;
  onRemove: (product: Product) => void;
};

export default function ProductListTab({
  app,
  products,
  categories,
  togglingId,
  onToggleStatus,
  onRemove,
}: Props) {
  const [categoryFilter, setCategoryFilter] = useState("");
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return products.filter((p) => {
      if (categoryFilter && !(p.categories || []).some((c) => c._id === categoryFilter)) {
        return false;
      }
      if (q && !p.title.toLowerCase().includes(q) && !p.slug.toLowerCase().includes(q)) {
        return false;
      }
      return true;
    });
  }, [products, categoryFilter, query]);

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
          <Input
            className="max-w-xs"
            placeholder="Search products…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <select
            className="h-10 rounded-md border bg-background px-3 text-sm"
            value={categoryFilter}
            onChange={(e) => setCategoryFilter(e.target.value)}
          >
            <option value="">All categories</option>
            {categories.map((c) => (
              <option key={c._id} value={c._id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>
        <Button asChild>
          <Link href={`/${app}/admin/products/new`}>Add product</Link>
        </Button>
      </div>
      <div className="overflow-hidden rounded-lg border bg-white">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Product</TableHead>
              <TableHead>Price</TableHead>
              <TableHead>Status</TableHead>
              <TableHead>Views</TableHead>
              <TableHead className="w-[200px]" />
            </TableRow>
          </TableHeader>
          <TableBody>
            {filtered.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} className="py-10 text-center text-slate-400">
                  No products{categoryFilter || query ? " match these filters" : " yet"}.
                </TableCell>
              </TableRow>
            ) : (
              filtered.map((p) => (
                <TableRow key={p._id}>
                  <TableCell className="font-medium">
                    <div className="flex items-center gap-2">
                      <ProductThumb src={p.images?.[0]} alt={p.title} size="md" />
                      <div className="min-w-0">
                        <p className="truncate">{p.title}</p>
                        <p className="text-xs text-slate-400">{p.slug}</p>
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    {p.salePrice != null && p.salePrice >= 0 ? (
                      <span>
                        <span className="font-semibold text-primary">{p.salePrice}</span>
                        <span className="ml-2 text-slate-400 line-through">{p.price}</span>
                      </span>
                    ) : (
                      p.price
                    )}
                  </TableCell>
                  <TableCell>
                    <span className={statusBadgeClass(p.status)}>{p.status}</span>
                  </TableCell>
                  <TableCell className="text-slate-500">{p.viewsTotal || 0}</TableCell>
                  <TableCell>
                    <div className="flex justify-end gap-2">
                      {p.slug ? (
                        <Button
                          variant="outline"
                          size="icon"
                          asChild={p.status === "published"}
                          disabled={p.status !== "published"}
                          title={
                            p.status === "published"
                              ? "View on website"
                              : "Publish to view on website"
                          }
                        >
                          {p.status === "published" ? (
                            <Link
                              href={`/products/${p.slug}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              aria-label="View on website"
                            >
                              <ExternalLink className="size-4" />
                            </Link>
                          ) : (
                            <ExternalLink className="size-4" />
                          )}
                        </Button>
                      ) : null}
                      <Button
                        variant="outline"
                        size="sm"
                        disabled={togglingId === p._id}
                        onClick={() => onToggleStatus(p)}
                        title={p.status === "published" ? "Unpublish" : "Publish"}
                      >
                        {p.status === "published" ? (
                          <EyeOff className="size-4" />
                        ) : (
                          <Eye className="size-4" />
                        )}
                      </Button>
                      <Button variant="outline" size="icon" asChild>
                        <Link href={`/${app}/admin/products/${p._id}/edit`} aria-label="Edit product">
                          <Pencil className="size-4" />
                        </Link>
                      </Button>
                      <Button variant="outline" size="icon" onClick={() => onRemove(p)}>
                        <Trash2 className="size-4 text-red-600" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
