"use client";

import { ColumnDef } from "@tanstack/react-table";
import { MoreHorizontal } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { generateShareToken } from "@/app/(sharing)/[token]/token";
export type Song = {
  title: string;
  artist: string;
  score?: number | null;
  userPlayDate: string | null;
  isFullCombo: boolean | null;
  isAllJustice: boolean | null;
  id: number;
};

export const columns: ColumnDef<Song>[] = [
  {
    accessorKey: "title",
    header: "Title",
    cell: ({ row }) => (
      <div>
        <div className="font-medium ">
          {row.original.title}
          <span className="space-x-2 pl-2">
            {row.original.isFullCombo && (
              <Badge className="rounded-sm">Full Combo</Badge>
            )}
            {row.original.isAllJustice && (
              <Badge className="rounded-sm  bg-yellow-500 text-black">
                All Justice
              </Badge>
            )}
          </span>
        </div>

        <div className="text-sm text-muted-foreground truncate inline-block w-[200px] ">
          {row.original.artist}
        </div>
      </div>
    ),
  },
  {
    accessorKey: "score",
    header: "Score",
    cell: ({ row }) => row.original.score?.toLocaleString(),
  },
  {
    accessorKey: "userPlayDate",
    header: "Date",
  },
  {
    id: "actions",
    header: () => <div className="text-left pl-2">More</div>,
    cell: ({ row }) => {
      const song = row.original;
      const [error, setError] = useState<string>("");
      const router = useRouter();

      const handleGenerateShareToken = async () => {
        const { token, error } = await generateShareToken(row.original.id);
        if (error) {
          setError(error);
        } else {
          router.push(`/${token}/${row.original.id}`);
        }
      };

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuLabel>Actions</DropdownMenuLabel>
            <DropdownMenuItem
              onClick={() => navigator.clipboard.writeText(song.title)}
            >
              Copy song title
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleGenerateShareToken}>
              View details
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];
