"use client";

import { ActionButtonWithTooltip } from "@/components/ui/action-button";
import { ButtonWithTooltip } from "@/components/ui/button";
import LoadingSpinner from "@/components/ui/spinner";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "@/components/ui/use-toast";
import { api } from "@/lib/trpc";
import { Check, KeyRound, Pencil, Trash, FilePlus, X } from "lucide-react";
import { useSession } from "next-auth/react";
import AddLabelDialog from "./AddLabelDialog";

export default function LabelsView() {
  const { data: session } = useSession();
  const { data: labels } = api.labels.list.useQuery();
  const { data: labelStats } = api.labels.labelStats.useQuery();

  const LabelsTable = ({ labels }) => (
    <Table>
      <TableHeader className="bg-gray-200">
        <TableHead>Code</TableHead>
        <TableHead>Name</TableHead>
        <TableHead>Description</TableHead>
        <TableHead>Entries With Label</TableHead>
        <TableHead>Actions</TableHead>
      </TableHeader>
      <TableBody>
        {labels.labels.map((l) => (
          <TableRow key={l.id} >
            <TableCell className="py-1">{l.code}</TableCell>
            <TableCell className="py-1">{l.name}</TableCell>
            <TableCell className="py-1">{l.description}</TableCell>
            <TableCell className="py-1">
              {labelStats[l.id].numEntries}
            </TableCell>
            <TableCell className="flex gap-1 py-1">
              <ActionButtonWithTooltip
                tooltip="Delete label"
                variant="outline"
                onClick={() => deleteLabel({ labelId: l.id })}
                loading={false}
              >
                <Trash size={16} color="red" />
              </ActionButtonWithTooltip>
              <AddLabelDialog labelId={l.id} >
                <ButtonWithTooltip
                  tooltip="Edit"
                  variant="outline"
                >
                  <Pencil size={16} color="red" />
                </ButtonWithTooltip>
              </AddLabelDialog>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table >
  );

  return (
    <>
      <div className="mb-2 flex items-center justify-between text-xl font-medium">
        <span>All Labels</span>
        <AddLabelDialog>
          <ButtonWithTooltip tooltip="Create Label" variant="outline">
            <FilePlus size={16} />
          </ButtonWithTooltip>
        </AddLabelDialog>
      </div>

      {labels === undefined ? (
        <LoadingSpinner />
      ) : (
        <LabelsTable labels={labels} />
      )}
    </>
  );
}
