"use client";

import { cn } from "@/lib/utils";
import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHead,
  TableCell,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { ChevronUp, ChevronDown, PencilIcon, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type {
  InventoryProduct,
  SortKey,
  SortDirection,
  StockStatus,
} from "../types";
import {
  formatCurrency,
  getStockStatus,
  computeProfit,
  computeTotalSales,
} from "../lib/format-utils";

interface InventoryTableProps {
  products: InventoryProduct[];
  sortKey: SortKey;
  sortDirection: SortDirection;
  onSort: (key: SortKey) => void;
  page: number;
  pageSize: number;
  totalPages: number;
  onPageChange: (page: number) => void;
  onPageSizeChange: (pageSize: number) => void;
  onEdit: (product: InventoryProduct) => void;
  onDelete: (product: InventoryProduct) => void;
}

function SortableHeader({
  title,
  key,
  currentSortKey,
  currentSortDirection,
  onClick,
}: {
  title: string;
  key: SortKey;
  currentSortKey: SortKey;
  currentSortDirection: SortDirection;
  onClick: () => void;
}) {
  const isActive = currentSortKey === key;
  return (
    <TableHead
      className="cursor-pointer select-none hover:bg-muted/50"
      onClick={onClick}
    >
      <div className="flex items-center gap-1">
        <span>{title}</span>
        {isActive ? (
          currentSortDirection === "asc" ? (
            <ChevronUp className="h-4 w-4 text-primary" />
          ) : (
            <ChevronDown className="h-4 w-4 text-primary" />
          )
        ) : (
          <ChevronDown className="h-4 w-4 text-muted-foreground/50" />
        )}
      </div>
    </TableHead>
  );
}

function StockStatusBadge({ status }: { status: StockStatus }) {
  const variants: Record<
    StockStatus,
    "default" | "destructive" | "secondary" | "outline"
  > = {
    "in-stock": "default",
    "low-stock": "destructive",
    "out-of-stock": "secondary",
  };

  const labels: Record<StockStatus, string> = {
    "in-stock": "In Stock",
    "low-stock": "Low Stock",
    "out-of-stock": "Out of Stock",
  };

  return (
    <Badge variant={variants[status]} className="gap-1">
      <span
        className={cn(
          "h-1.5 w-1.5 rounded-full",
          status === "in-stock" && "bg-green-500",
          status === "low-stock" && "bg-yellow-500",
          status === "out-of-stock" && "bg-red-500",
        )}
      />
      {labels[status]}
    </Badge>
  );
}

export default function InventoryTable({
  products,
  sortKey,
  sortDirection,
  onSort,
  page,
  pageSize,
  totalPages,
  onPageChange,
  onPageSizeChange,
  onEdit,
  onDelete,
}: InventoryTableProps) {
  if (products.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <div className="h-12 w-12 text-muted-foreground/50 mb-4" />
        <p className="text-muted-foreground">No products found.</p>
        <p className="text-sm text-muted-foreground/70 mt-1">
          Try adjusting your search or filter.
        </p>
      </div>
    );
  }

  const paginatedProducts = products.slice(
    (page - 1) * pageSize,
    page * pageSize,
  );

  return (
    <div className="space-y-4">
      <div className="rounded-lg border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <SortableHeader
                title="Product"
                key="name"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("name")}
              />
              <SortableHeader
                title="Category"
                key="category"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("category")}
              />
              <SortableHeader
                title="Purchase Price"
                key="purchasePrice"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("purchasePrice")}
              />
              <SortableHeader
                title="Selling Price"
                key="sellingPrice"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("sellingPrice")}
              />
              <SortableHeader
                title="Stock"
                key="stock"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("stock")}
              />
              <SortableHeader
                title="Units Sold"
                key="unitsSold"
                currentSortKey={sortKey}
                currentSortDirection={sortDirection}
                onClick={() => onSort("unitsSold")}
              />
              <TableHead className="text-right">Total Sales</TableHead>
              <TableHead className="text-right">Profit</TableHead>
              <TableHead className="text-right">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {paginatedProducts.map((product) => {
              const stockStatus = getStockStatus(product.stock);
              const profit = computeProfit(product);
              const totalSales = computeTotalSales(product);

              return (
                <TableRow key={product.id}>
                  <TableCell className="font-medium">{product.name}</TableCell>
                  <TableCell>{product.category}</TableCell>
                  <TableCell className="font-mono">
                    {formatCurrency(product.purchasePrice)}
                  </TableCell>
                  <TableCell className="font-mono font-medium">
                    {formatCurrency(product.sellingPrice)}
                  </TableCell>
                  <TableCell>
                    <StockStatusBadge status={stockStatus} />
                  </TableCell>
                  <TableCell className="font-mono">
                    {product.unitsSold} Units
                  </TableCell>
                  <TableCell className="text-right font-mono font-medium">
                    {formatCurrency(totalSales)}
                  </TableCell>
                  <TableCell className="text-right font-mono">
                    {profit >= 0 ? (
                      <span className="text-green-600 dark:text-green-400">
                        {formatCurrency(profit)}
                      </span>
                    ) : (
                      <span className="text-red-600 dark:text-red-400">
                        {formatCurrency(profit)}
                      </span>
                    )}
                  </TableCell>
                  <TableCell className="text-center">
                    <Button
                      size="icon-xs"
                      variant="secondary"
                      onClick={() => onEdit(product)}
                      aria-label={`Edit ${product.name}`}
                    >
                      <PencilIcon />
                    </Button>
                    <Button
                      size="icon-xs"
                      variant="destructive"
                      onClick={() => onDelete(product)}
                      aria-label={`Delete ${product.name}`}
                    >
                      <Trash2 />
                    </Button>
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">
            Showing{" "}
            <span className="font-medium">
              {(page - 1) * pageSize + 1}–
              {Math.min(page * pageSize, products.length)}
            </span>{" "}
            of <span className="font-medium">{products.length}</span> products
          </span>
        </div>

        <div className="flex items-center gap-2">
          <Select
            items={[10, 25, 50, 100].map((size) => ({
              value: size.toString(),
              label: `${size} per page`,
            }))}
            value={pageSize.toString()}
            onValueChange={(val) => onPageSizeChange(Number(val))}
          >
            <SelectTrigger className="w-24 h-8">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {[10, 25, 50, 100].map((size) => (
                <SelectItem key={size} value={size.toString()}>
                  {size} per page
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(1)}
              disabled={page === 1}
              aria-label="First page"
            >
              <ChevronUp className="h-4 w-4 rotate-180" />
            </Button>
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(page - 1)}
              disabled={page === 1}
              aria-label="Previous page"
            >
              <ChevronUp className="h-4 w-4" />
            </Button>
            <span className="flex items-center px-3 text-sm font-medium">
              Page {page} of {totalPages}
            </span>
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(page + 1)}
              disabled={page === totalPages}
              aria-label="Next page"
            >
              <ChevronDown className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="icon"
              onClick={() => onPageChange(totalPages)}
              disabled={page === totalPages}
              aria-label="Last page"
            >
              <ChevronDown className="h-4 w-4 rotate-180" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
