import { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown, ChevronDown, ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

interface Product {
  pid: string;
  sku: string;
  title: string;
  total_sold: number;
}

export interface ForecastItem {
  category: string;
  categoryPath: string;
  totalSold: number;
  numProducts: number;
  avgTotalSold: number;
  minSold: number;
  maxSold: number;
  products?: Product[];
}

export const columns: ColumnDef<ForecastItem>[] = [
  {
    id: "expander",
    header: () => null,
    cell: ({ row }) => {
      return row.getCanExpand() ? (
        <Button
          variant="ghost"
          onClick={() => row.toggleExpanded()}
          className="p-0 h-auto"
        >
          {row.getIsExpanded() ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        </Button>
      ) : null;
    },
  },
  {
    accessorKey: "category",
    header: "Category",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">{row.original.category}</div>
        {row.original.categoryPath && (
          <div className="text-sm text-muted-foreground">
            {row.original.categoryPath}
          </div>
        )}
      </div>
    ),
  },
  {
    accessorKey: "avgTotalSold",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          className="whitespace-nowrap"
        >
          Avg Total Sold
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => {
      const value = row.getValue("avgTotalSold") as number;
      return value?.toFixed(2) || "0.00";
    },
  },
  {
    accessorKey: "minSold",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          className="whitespace-nowrap"
        >
          Min Sold
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => {
      const value = row.getValue("minSold") as number;
      return value?.toLocaleString() || "0";
    },
  },
  {
    accessorKey: "maxSold",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          className="whitespace-nowrap"
        >
          Max Sold
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => {
      const value = row.getValue("maxSold") as number;
      return value?.toLocaleString() || "0";
    },
  },
  {
    accessorKey: "totalSold",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Total Sold
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => {
      const value = row.getValue("totalSold") as number;
      return value?.toLocaleString() || "0";
    },
  },
  {
    accessorKey: "numProducts",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
          className="whitespace-nowrap"
        >
          # Products
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => {
      const value = row.getValue("numProducts") as number;
      return value?.toLocaleString() || "0";
    },
  },
];

export const renderSubComponent = ({ row }: { row: any }) => {
  const products = row.original.products || [];
  
  return (
    <ScrollArea className="h-[400px] w-full rounded-md border p-4">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Product</TableHead>
            <TableHead className="text-right">Sold</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {products.map((product: Product) => (
            <TableRow key={product.pid}>
              <TableCell>
                <a
                  href={`https://backend.acherryontop.com/product/${product.pid}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="hover:underline"
                >
                  {product.title}
                </a>
                <div className="text-sm text-muted-foreground">{product.sku}</div>
              </TableCell>
              <TableCell className="text-right">{product.total_sold?.toLocaleString?.() ?? product.total_sold}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </ScrollArea>
  );
};
