"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  PageHeader,
  Panel,
  AdminButton,
  StatCard,
  StatusBadge,
  FilterBar,
  SearchInput,
  SelectFilter,
  EmptyState,
} from "@/components/admin/ui";
import { formatCurrency, lowStockThreshold } from "@/components/admin/adminNav";
import { DUPLICATE_STORAGE_KEY, duplicateProductValues } from "@/components/admin/ProductForm";
import { useAuth } from "@/context/AuthContext";
import { useStore } from "@/context/StoreContext";
import { api, ApiError, mediaOrPlaceholder } from "@/lib/api";
import type { ProductRecord } from "@/data/ecommerceStore";
import { toast } from "sonner";

type StockFilter = "all" | "in_stock" | "low" | "out";
type StatusFilter = "all" | "active" | "inactive";
type FeaturedFilter = "all" | "yes" | "no";

export default function AdminProductsPage() {
  const router = useRouter();
  const { token } = useAuth();
  const { store, refreshStore } = useStore();
  const [search, setSearch] = useState("");
  const [categoryId, setCategoryId] = useState("all");
  const [brandId, setBrandId] = useState("all");
  const [status, setStatus] = useState<StatusFilter>("all");
  const [stock, setStock] = useState<StockFilter>("all");
  const [featured, setFeatured] = useState<FeaturedFilter>("all");
  const [selected, setSelected] = useState<string[]>([]);
  const [bulkStatus, setBulkStatus] = useState<"active" | "inactive">("active");
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [preview, setPreview] = useState<ProductRecord | null>(null);

  const categoryMap = useMemo(
    () => Object.fromEntries(store.categories.map((c) => [c.id, c.name])),
    [store.categories],
  );
  const brandMap = useMemo(
    () => Object.fromEntries(store.brands.map((b) => [b.id, b.name])),
    [store.brands],
  );

  const imageFor = (productId: string) => {
    const img =
      store.product_images.find((i) => i.product_id === productId && i.is_main) ||
      store.product_images.find((i) => i.product_id === productId);
    return mediaOrPlaceholder(img?.image);
  };

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return store.products.filter((p) => {
      if (categoryId !== "all" && p.category_id !== categoryId) return false;
      if (brandId !== "all" && p.brand_id !== brandId) return false;
      if (status !== "all" && p.status !== status) return false;
      if (featured === "yes" && !p.featured) return false;
      if (featured === "no" && p.featured) return false;
      if (stock === "in_stock" && p.stock <= 0) return false;
      if (stock === "low" && !(p.stock > 0 && p.stock <= lowStockThreshold)) return false;
      if (stock === "out" && p.stock > 0) return false;
      if (!q) return true;
      return (
        p.name.toLowerCase().includes(q) ||
        p.sku.toLowerCase().includes(q) ||
        (brandMap[p.brand_id] || "").toLowerCase().includes(q) ||
        (categoryMap[p.category_id] || "").toLowerCase().includes(q)
      );
    });
  }, [store.products, search, categoryId, brandId, status, stock, featured, brandMap, categoryMap]);

  const stats = useMemo(() => {
    const products = store.products;
    return {
      total: products.length,
      active: products.filter((p) => p.status === "active").length,
      low: products.filter((p) => p.stock > 0 && p.stock <= lowStockThreshold).length,
      out: products.filter((p) => p.stock <= 0).length,
    };
  }, [store.products]);

  const allVisibleSelected = filtered.length > 0 && filtered.every((p) => selected.includes(p.id));

  const toggleAll = () => {
    if (allVisibleSelected) {
      setSelected((prev) => prev.filter((id) => !filtered.some((p) => p.id === id)));
    } else {
      setSelected((prev) => Array.from(new Set([...prev, ...filtered.map((p) => p.id)])));
    }
  };

  const toggleOne = (id: string) => {
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  const runWithFeedback = async (fn: () => Promise<void>, success: string) => {
    setBusy(true);
    setError("");
    setMessage("");
    try {
      await fn();
      await refreshStore();
      setMessage(success);
      toast.success(success);
    } catch (err) {
      const message = err instanceof ApiError ? err.message : "Action failed.";
      setError(message);
      toast.error(message);
    } finally {
      setBusy(false);
    }
  };

  const deleteProduct = (id: string) =>
    runWithFeedback(async () => {
      await api.admin.deleteProduct(id, token);
      setSelected((prev) => prev.filter((x) => x !== id));
    }, "Product deleted.");

  const archiveProduct = (id: string) =>
    runWithFeedback(async () => {
      await api.admin.updateProduct(id, { status: "inactive" }, token);
    }, "Product archived (inactive).");

  const duplicateProduct = (product: ProductRecord) => {
    sessionStorage.setItem(DUPLICATE_STORAGE_KEY, JSON.stringify(duplicateProductValues(product)));
    router.push("/admin/products/new?duplicate=1");
  };

  const applyBulk = (action: "delete" | "publish" | "unpublish" | "status") => {
    if (!selected.length) {
      setError("Select at least one product.");
      return;
    }
    void runWithFeedback(async () => {
      if (action === "delete") {
        await Promise.all(selected.map((id) => api.admin.deleteProduct(id, token)));
        setSelected([]);
        return;
      }
      const nextStatus =
        action === "publish" ? "active" : action === "unpublish" ? "inactive" : bulkStatus;
      await Promise.all(selected.map((id) => api.admin.updateProduct(id, { status: nextStatus }, token)));
    }, `Bulk ${action} applied to ${selected.length} product(s).`);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Products"
        description="Manage catalog items, inventory status, and merchandising flags."
        actions={<AdminButton href="/admin/products/new">Add Product</AdminButton>}
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Total Products" value={stats.total} />
        <StatCard label="Active" value={stats.active} tone="success" />
        <StatCard label="Low Stock" value={stats.low} tone="warning" hint={`≤ ${lowStockThreshold}`} />
        <StatCard label="Out of Stock" value={stats.out} tone="danger" />
      </div>

      {(message || error) && (
        <div
          className={`rounded-xl border px-4 py-3 text-sm ${
            error
              ? "border-destructive/30 bg-destructive/10 text-destructive"
              : "border-emerald-200 bg-emerald-50 text-emerald-800"
          }`}
        >
          {error || message}
        </div>
      )}

      <Panel title="Product catalog" description={`${filtered.length} matching products`}>
        <FilterBar>
          <SearchInput value={search} onChange={setSearch} placeholder="Search name, SKU, brand…" />
          <SelectFilter
            value={categoryId}
            onChange={setCategoryId}
            options={[
              { value: "all", label: "All categories" },
              ...store.categories.map((c) => ({ value: c.id, label: c.name })),
            ]}
          />
          <SelectFilter
            value={brandId}
            onChange={setBrandId}
            options={[
              { value: "all", label: "All brands" },
              ...store.brands.map((b) => ({ value: b.id, label: b.name })),
            ]}
          />
          <SelectFilter
            value={status}
            onChange={(v) => setStatus(v as StatusFilter)}
            options={[
              { value: "all", label: "All statuses" },
              { value: "active", label: "Active" },
              { value: "inactive", label: "Inactive" },
            ]}
          />
          <SelectFilter
            value={stock}
            onChange={(v) => setStock(v as StockFilter)}
            options={[
              { value: "all", label: "All stock" },
              { value: "in_stock", label: "In stock" },
              { value: "low", label: "Low stock" },
              { value: "out", label: "Out of stock" },
            ]}
          />
          <SelectFilter
            value={featured}
            onChange={(v) => setFeatured(v as FeaturedFilter)}
            options={[
              { value: "all", label: "Featured: all" },
              { value: "yes", label: "Featured" },
              { value: "no", label: "Not featured" },
            ]}
          />
        </FilterBar>

        {selected.length > 0 ? (
          <div className="mb-4 flex flex-wrap items-center gap-2 rounded-xl border border-border bg-secondary/40 px-3 py-2.5">
            <span className="text-xs font-semibold">{selected.length} selected</span>
            <AdminButton onClick={() => applyBulk("delete")} variant="danger">
              Delete
            </AdminButton>
            <AdminButton onClick={() => applyBulk("publish")} variant="secondary">
              Publish
            </AdminButton>
            <AdminButton onClick={() => applyBulk("unpublish")} variant="secondary">
              Unpublish
            </AdminButton>
            <SelectFilter
              value={bulkStatus}
              onChange={(v) => setBulkStatus(v as "active" | "inactive")}
              options={[
                { value: "active", label: "Active" },
                { value: "inactive", label: "Inactive" },
              ]}
            />
            <AdminButton onClick={() => applyBulk("status")} variant="secondary">
              Change Status
            </AdminButton>
            <AdminButton onClick={() => setSelected([])} variant="ghost">
              Clear
            </AdminButton>
            {busy ? <span className="text-xs text-muted-foreground">Working…</span> : null}
          </div>
        ) : null}

        {filtered.length === 0 ? (
          <EmptyState title="No products found" description="Try adjusting filters or add a new product." />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[1100px] text-left text-sm">
              <thead>
                <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                  <th className="py-2 pr-2">
                    <input type="checkbox" checked={allVisibleSelected} onChange={toggleAll} />
                  </th>
                  <th className="py-2 pr-3">Image</th>
                  <th className="py-2 pr-3">SKU</th>
                  <th className="py-2 pr-3">Name</th>
                  <th className="py-2 pr-3">Brand</th>
                  <th className="py-2 pr-3">Category</th>
                  <th className="py-2 pr-3">Price</th>
                  <th className="py-2 pr-3">Sale</th>
                  <th className="py-2 pr-3">Stock</th>
                  <th className="py-2 pr-3">Status</th>
                  <th className="py-2 pr-3">Featured</th>
                  <th className="py-2 pr-3">Created</th>
                  <th className="py-2">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((product) => (
                  <tr key={product.id} className="border-b border-border/70 align-middle">
                    <td className="py-2.5 pr-2">
                      <input
                        type="checkbox"
                        checked={selected.includes(product.id)}
                        onChange={() => toggleOne(product.id)}
                      />
                    </td>
                    <td className="py-2.5 pr-3">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={imageFor(product.id)}
                        alt=""
                        className="h-10 w-10 rounded-lg object-cover border border-border"
                      />
                    </td>
                    <td className="py-2.5 pr-3 font-mono text-xs">{product.sku}</td>
                    <td className="py-2.5 pr-3 font-medium">{product.name}</td>
                    <td className="py-2.5 pr-3 text-muted-foreground">{brandMap[product.brand_id] || "—"}</td>
                    <td className="py-2.5 pr-3 text-muted-foreground">
                      {categoryMap[product.category_id] || "—"}
                    </td>
                    <td className="py-2.5 pr-3">{formatCurrency(product.selling_price)}</td>
                    <td className="py-2.5 pr-3">
                      {product.sale_price != null ? formatCurrency(product.sale_price) : "—"}
                    </td>
                    <td className="py-2.5 pr-3">
                      <span
                        className={
                          product.stock <= 0
                            ? "text-destructive font-semibold"
                            : product.stock <= lowStockThreshold
                              ? "text-amber-700 font-semibold"
                              : ""
                        }
                      >
                        {product.stock}
                      </span>
                    </td>
                    <td className="py-2.5 pr-3">
                      <StatusBadge status={product.status} />
                    </td>
                    <td className="py-2.5 pr-3">
                      {product.featured ? <StatusBadge status="featured" /> : "—"}
                    </td>
                    <td className="py-2.5 pr-3 text-xs text-muted-foreground">
                      {product.created_at ? new Date(product.created_at).toLocaleDateString() : "—"}
                    </td>
                    <td className="py-2.5">
                      <div className="flex flex-wrap gap-1">
                        <Link href={`/product/${product.id}`} className="text-xs font-semibold text-accent hover:underline">
                          View
                        </Link>
                        <span className="text-muted-foreground">·</span>
                        <Link
                          href={`/admin/products/${product.id}`}
                          className="text-xs font-semibold text-accent hover:underline"
                        >
                          Edit
                        </Link>
                        <span className="text-muted-foreground">·</span>
                        <button
                          type="button"
                          className="text-xs font-semibold text-accent hover:underline"
                          onClick={() => duplicateProduct(product)}
                        >
                          Duplicate
                        </button>
                        <span className="text-muted-foreground">·</span>
                        <button
                          type="button"
                          className="text-xs font-semibold text-accent hover:underline"
                          onClick={() => setPreview(product)}
                        >
                          Preview
                        </button>
                        <span className="text-muted-foreground">·</span>
                        <button
                          type="button"
                          className="text-xs font-semibold text-amber-700 hover:underline"
                          onClick={() => void archiveProduct(product.id)}
                        >
                          Archive
                        </button>
                        <span className="text-muted-foreground">·</span>
                        <button
                          type="button"
                          className="text-xs font-semibold text-destructive hover:underline"
                          onClick={() => {
                            if (window.confirm(`Delete “${product.name}”?`)) void deleteProduct(product.id);
                          }}
                        >
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <p className="mt-4 text-xs text-muted-foreground">
          Showing {filtered.length} of {store.products.length} products
          {selected.length ? ` · ${selected.length} selected` : ""}
        </p>
      </Panel>

      {preview ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-Blue/40 p-4"
          onClick={() => setPreview(null)}
        >
          <div
            className="w-full max-w-md rounded-2xl border border-border bg-white p-5 shadow-xl"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex gap-4">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={imageFor(preview.id)}
                alt=""
                className="h-24 w-24 rounded-xl object-cover border border-border"
              />
              <div>
                <p className="text-xs text-muted-foreground">{preview.sku}</p>
                <h3 className="text-lg font-bold">{preview.name}</h3>
                <p className="mt-1 text-sm text-muted-foreground">
                  {brandMap[preview.brand_id]} · {categoryMap[preview.category_id]}
                </p>
                <p className="mt-2 font-semibold">
                  {formatCurrency(preview.sale_price ?? preview.selling_price)}
                </p>
              </div>
            </div>
            <p className="mt-4 line-clamp-4 text-sm text-muted-foreground">
              {preview.description || "No description."}
            </p>
            <div className="mt-4 flex flex-wrap gap-2">
              <StatusBadge status={preview.status} />
              {preview.featured ? <StatusBadge status="featured" /> : null}
              <span className="text-xs text-muted-foreground self-center">Stock: {preview.stock}</span>
            </div>
            <div className="mt-5 flex gap-2">
              <AdminButton href={`/product/${preview.id}`}>Open storefront</AdminButton>
              <AdminButton href={`/admin/products/${preview.id}`} variant="secondary">
                Edit
              </AdminButton>
              <AdminButton onClick={() => setPreview(null)} variant="ghost">
                Close
              </AdminButton>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
