import { DotsHorizontalIcon } from "@radix-ui/react-icons";
import { Link, useFetcher, useParams } from "@remix-run/react";
import { ColumnDef } from "@tanstack/react-table";
import { ChevronDown, ChevronRight, Eye, Trash } from "lucide-react";
import "react-json-view-lite/dist/index.css";
import { SquareArrowUpRight } from "~/components/icons/SquareArrowUpRight";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "~/components/ui/dropdown-menu";
import { calcPadding } from "~/pages/traces/constants/utils";
import { Row } from "~/pages/traces/types";
import { Routes } from "~/routes";
import { idShortener } from "../utils/idShortener";


export const COLUMNS: ColumnDef<Row>[] = [
  // {
  //   id: "select",
  //   header: ({ table }) => (
  //     <Checkbox
  //       checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
  //       onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
  //       aria-label="Select all"
  //     />
  //   ),
  //   cell: ({ row }) => (
  //     <Checkbox
  //       checked={row.getIsSelected()}
  //       onCheckedChange={(value) => row.toggleSelected(!!value)}
  //       aria-label="Select row"
  //     />
  //   ),
  //   enableSorting: false,
  //   enableHiding: false,
  // },
  {
    accessorKey: "name",
    header: "Name",
    cell: ({ row }) => {
      const { containerPadding, linkPadding } = calcPadding(row);

      const params = useParams();
      const name = row.getValue<Row["name"]>("name")?.substring(0, 15);
      const traceId = row.original.traceId;
      const logId = row.original.id;
      const traceVariant = idShortener(traceId || "").variant;
      const isTrace = row.original.type === "trace";

      const to = Routes.app.project.env.traceId({
        projectId: params.projectId!,
        envId: params.envId!,
        traceId,
        logId,
      });

      return (
        <div style={{ paddingLeft: containerPadding }}>
          {row.getCanExpand() ? (
            <button
              {...{
                onClick: row.getToggleExpandedHandler(),
                style: { cursor: "pointer", paddingRight: "8px" },
              }}
            >
              {row.getIsExpanded() ? <ChevronDown className={"h-4 w-4"} /> : <ChevronRight className={"h-4 w-4"} />}
            </button>
          ) : null}
          <Link style={{ paddingLeft: linkPadding }} to={to}>
            <Badge variant={isTrace ? traceVariant : "white"}>
              <SquareArrowUpRight />
              &nbsp;
              {name ?? ""}
              {name?.length !== row.original.name?.length && "..."}
            </Badge>
          </Link>
        </div>
      );
    },
  },
  {
    accessorKey: "startTime",
    header: "Start Time",
    cell: ({ row }) => {
      const date = row.getValue<Row["startTime"]>("startTime");
      return <div>{date ?? "—"}</div>;
    },
  },
  {
    accessorKey: "latency",
    header: "Latency",
    cell: ({ row }) => {
      const latency = row.getValue<Row["latency"]>("latency");
      return <div>{latency ? `${latency}s` : "—"}</div>;
    },
  },
  {
    accessorKey: "totalTokens",
    header: "Tokens",
    cell: ({ row }) => <div>{row.getValue<Row["totalTokens"]>("totalTokens") ?? "—"}</div>,
  },
  {
    accessorKey: "totalCost",
    header: "Cost",
    cell: ({ row }) => {
      const totalCost = row.getValue<Row["totalCost"]>("totalCost");
      return <div>{totalCost ? `$${totalCost}` : "—"}</div>;
    },
  },
  {
    accessorKey: "model",
    header: "Model",
    cell: ({ row }) => {
      const model = row.getValue<Row["model"]>("model");
      return <div>{model ?? "—"}</div>;
    },
  },
  {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const params = useParams();
      const fetcher = useFetcher();
      const traceId = row.getValue<Row["traceId"]>("traceId");

      const handleDelete = () => {
        fetcher.submit(null, {
          method: "DELETE",
          action: Routes.actions.trace.delete({
            projectId: params.projectId!,
            traceId,
          }),
        });
      };

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <DotsHorizontalIcon className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem className={"gap-2"} disabled>
              <Eye size={16} /> Quick View
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem className={"text-destructive gap-2"} onClick={handleDelete}>
              <Trash size={16} /> Delete Trace
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];
