"use client";

import { useMemo, useState, useCallback, useTransition } from "react";
import { useRouter } from "next/navigation";
import { InventoryHeader } from "./components/inventory-header";
import { SummaryCards } from "./components/summary-cards";
import InventoryToolbar from "./components/inventory-toolbar";
import InventoryTable from "./components/inventory-table";
import type {
  InventoryProduct,
  SortKey,
  SortDirection,
  Category,
} from "./types";
import {
  formatCurrency,
  computeProfit,
  computeTotalSales,
  getDateRange,
} from "./lib/format-utils";
import { deleteProduct, getInventoryProducts } from "@/lib/actions/products";

const DEFAULT_PAGE_SIZE = 10;

interface InventoryClientProps {
  products: InventoryProduct[];
  /** Categories used by the filter dropdown and add-product form. */
  categories: Category[];
}

export function InventoryClient({
  products: initialProducts,
  categories,
}: InventoryClientProps) {
  const router = useRouter();
  const [, startTransition] = useTransition();

  // Local list so a delete disappears immediately while the action revalidates.
  const [list, setList] = useState(initialProducts);

  // ── Filters ──
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [dateRangeValue, setDateRangeValue] = useState("all");
  const [dateRangeLabel, setDateRangeLabel] = useState("All Time");

  // ── Table State ──
  const [sortKey, setSortKey] = useState<SortKey>("lastUpdated");
  const [sortDirection, setSortDirection] = useState<SortDirection>("desc");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);

  // ── Derived: filtered products ──
  const filteredProducts = useMemo(() => {
    const q = searchQuery.toLowerCase().trim();

    let result = list.filter((product) => {
      const matchesSearch =
        q === "" ||
        product.name.toLowerCase().includes(q) ||
        product.sku.toLowerCase().includes(q) ||
        product.category.toLowerCase().includes(q);

      const matchesCategory =
        selectedCategory === "all" || product.categoryId === selectedCategory;
      const matchesDate = dateRangeValue === "all" || product.unitsSold > 0;

      return matchesSearch && matchesCategory && matchesDate;
    });

    // Sorting
    result = [...result].sort((a, b) => {
      let aVal: string | number;
      let bVal: string | number;

      switch (sortKey) {
        case "totalSales":
          aVal = computeTotalSales(a);
          bVal = computeTotalSales(b);
          break;
        case "totalProfit":
          aVal = computeProfit(a);
          bVal = computeProfit(b);
          break;
        default:
          aVal = a[sortKey as Exclude<SortKey, "totalSales" | "totalProfit">];
          bVal = b[sortKey as Exclude<SortKey, "totalSales" | "totalProfit">];
      }

      if (typeof aVal === "string") {
        aVal = aVal.toLowerCase();
        bVal = (bVal as string).toLowerCase();
      }

      if (aVal < bVal) return sortDirection === "asc" ? -1 : 1;
      if (aVal > bVal) return sortDirection === "asc" ? 1 : -1;
      return 0;
    });

    return result;
  }, [
    list,
    searchQuery,
    selectedCategory,
    dateRangeValue,
    sortKey,
    sortDirection,
  ]);

  // ── Pagination ──
  const totalPages = Math.ceil(filteredProducts.length / pageSize) || 1;

  // ── Handlers ──
  const handleSort = useCallback((key: SortKey) => {
    setSortKey((prev) => {
      if (prev === key) {
        setSortDirection((d) => (d === "asc" ? "desc" : "asc"));
      } else {
        setSortDirection("asc");
      }
      return key;
    });
    setPage(1);
  }, []);

  const handleDateRangeChange = useCallback((preset: string) => {
    setDateRangeValue(preset);
    if (preset === "all") {
      setDateRangeLabel("All Time");
      startTransition(() => {
        void getInventoryProducts().then(setList);
      });
    } else {
      const range = getDateRange(preset);
      const presetInfo = DATE_RANGE_PRESETS.find((p) => p.value === preset);
      setDateRangeLabel(presetInfo?.label ?? "All Time");
      startTransition(() => {
        void getInventoryProducts(range).then(setList);
      });
    }
    setPage(1);
  }, []);

  const handleEdit = useCallback(
    (product: InventoryProduct) => {
      router.push(`/admin/dashboard/inventory/add?edit=true&id=${product.id}`);
    },
    [router],
  );

  const handleDelete = useCallback(
    (product: InventoryProduct) => {
      if (!window.confirm(`Delete "${product.name}"? This cannot be undone.`)) {
        return;
      }
      setList((prev) => prev.filter((p) => p.id !== product.id));
      startTransition(() => {
        void deleteProduct(product.id);
      });
    },
    [startTransition],
  );

  const handleExport = useCallback(() => {
    const headers = [
      "ID",
      "Name",
      "Category",
      "Purchase Price",
      "Selling Price",
      "Stock",
      "Units Sold",
      "Total Sales",
      "Total Cost",
      "Profit",
    ];

    const rows = filteredProducts.map((p) => [
      p.id,
      p.name,
      p.category,
      formatCurrency(p.purchasePrice),
      formatCurrency(p.sellingPrice),
      p.stock.toString(),
      p.unitsSold.toString(),
      formatCurrency(computeTotalSales(p)),
      formatCurrency(p.purchasePrice * p.unitsSold),
      formatCurrency(computeProfit(p)),
    ]);

    const csvContent = [headers, ...rows]
      .map((row) => row.map((cell) => `"${cell}"`).join(","))
      .join("\n");

    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute(
      "download",
      `inventory-export-${new Date().toISOString().split("T")[0]}.csv`,
    );
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }, [filteredProducts]);

  return (
    <div className="flex flex-col gap-6">
      {/* Header */}
      <InventoryHeader dateRangeLabel={dateRangeLabel} />

      {/* Summary Cards */}
      <SummaryCards products={filteredProducts} />

      {/* Toolbar */}
      <InventoryToolbar
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        selectedCategory={selectedCategory}
        onCategoryChange={(cat) => {
          setSelectedCategory(cat);
          setPage(1);
        }}
        dateRangeValue={dateRangeValue}
        onDateRangeChange={handleDateRangeChange}
        onExport={handleExport}
        categories={categories}
      />

      {/* Table */}
      <InventoryTable
        products={filteredProducts}
        sortKey={sortKey}
        sortDirection={sortDirection}
        onSort={handleSort}
        page={page}
        pageSize={pageSize}
        totalPages={totalPages}
        onPageChange={setPage}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPage(1);
        }}
        onEdit={handleEdit}
        onDelete={handleDelete}
      />
    </div>
  );
}

const DATE_RANGE_PRESETS = [
  { value: "all", label: "All Time" },
  { value: "today", label: "Today" },
  { value: "yesterday", label: "Yesterday" },
  { value: "last-7", label: "Last 7 Days" },
  { value: "last-30", label: "Last 30 Days" },
  { value: "this-month", label: "This Month" },
  { value: "last-month", label: "Last Month" },
];
