"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";

import { chuni_score_playlog } from "@/prisma/schemas/artemis/generated/artemis";
import { chuni_static_music } from "@/prisma/schemas/artemis/generated/artemis";
import { getGrade } from "@/lib/helpers";

type includesPlayCount = chuni_score_playlog &
  chuni_static_music & { playCount: number };

export const columns: ColumnDef<includesPlayCount>[] = [
  {
    accessorKey: "title",
    header: "Title",
    cell: ({ row }) => {
      const jacketPath = row.original.jacketPath?.replace(".dds", ".png");
      return (
        <div className="font-medium w-[200px] truncate">
          {jacketPath && (
            <img
              src={`/jackets/${jacketPath}`}
              alt="Jacket"
              className="w-8 h-8 inline-block mr-2"
            />
          )}
          {row.original.title}
        </div>
      );
    },
  },

  {
    accessorKey: "score",
    header: "Score",
    cell: ({ row }) => (
      <div>
        {row.original.score?.toLocaleString()}
        <span className="pl-2"> {getGrade(row.original.score ?? 0)}</span>
        {row.original.isNewRecord && <span className="pl-2 ">New!!</span>}
      </div>
    ),
  },
  {
    accessorKey: "userPlayDate",
    header: "Date",
  },

  {
    accessorKey: "FC / AJ",
    header: "FC / AJ",
    cell: ({ row }) => (
      <div>
        <div className="font-medium">
          {!row.original.isAllJustice && row.original.isFullCombo && (
            <span>Full Combo</span>
          )}
          {row.original.isAllJustice && <span>All Justice</span>}
        </div>
      </div>
    ),
  },
  {
    accessorKey: "Attempts",
    header: "Attempts",
    cell: ({ row }) => (
      <div className="font-medium">{row.original.playCount}</div>
    ),
  },
  {
    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 {
          const newTab = window.open(`/${token}/${row.original.id}`, "_blank");
          if (newTab) {
            newTab.focus();
          } else {
            // Handle popup blocker or inability to open new tab
            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={() =>
                song.title && navigator.clipboard.writeText(song.title)
              }
            >
              Copy song title
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleGenerateShareToken}>
              Share Song
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];
