"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 { useState } from "react";
import { useRouter } from "next/navigation";
import { generateShareToken } from "@/app/(sharing)/[token]/token";
import { ArrowUpDown, MoreHorizontalIcon } from "lucide-react";
import { chuni_score_playlog } from "@/prisma/schemas/artemis/generated/artemis";
import { chuni_static_music } from "@/prisma/schemas/artemis/generated/artemis";
import { getDifficultyText, getGrade } from "@/lib/helpers";
import { Skeleton } from "../ui/skeleton";

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

export const columns: ColumnDef<chunithm>[] = [
  {
    accessorKey: "title",
    header: "Title",

    cell: ({ row }) => {
      const jacketPath = row.original.jacketPath?.replace(".dds", ".png");
      const [isLoading, setIsLoading] = useState(true);
      return (
        <div className="flex w-[300px] items-center truncate font-medium">
          {!jacketPath ? (
            <Skeleton className="mr-2 inline-block h-8 w-8" />
          ) : (
            <img
              src={`/jacketArts/${jacketPath}`}
              alt="Jacket"
              className="mr-2 inline-block h-[40px] w-[40px]"
            />
          )}
          <span className="truncate">{row.original.title}</span>
        </div>
      );
    },
  },

  {
    accessorKey: "score",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Score
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    cell: ({ row }) => <div>{row.original.score?.toLocaleString()}</div>,
    sortingFn: (a, b) => {
      const highScore = a.original.score ?? 0;
      const lowScore = b.original.score ?? 0;

      return lowScore - highScore;
    },
  },
  {
    accessorKey: "isNew",
    header: "New",
    cell: ({ row }) => (
      <div className="font-medium">
        {row.original.isNewRecord && <span>New!!</span>}
      </div>
    ),
  },
  {
    accessorKey: "grade",
    header: "Grade",
    cell: ({ row }) => (
      <div className="font-medium"> {getGrade(row.original.score ?? 0)}</div>
    ),
  },
  {
    accessorKey: "userPlayDate",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          Date
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
  },
  {
    accessorKey: "difficulty",
    header: "Difficulty",
    cell: ({ row }) => (
      <div className="font-medium">
        {row.original.level}
        <br />
        {getDifficultyText(row.original.chartId)}
      </div>
    ),
  },
  {
    accessorKey: "FC / AJ",
    header: "FC / AJ",
    cell: ({ row }) => (
      <div className="font-medium">
        {!row.original.isAllJustice && row.original.isFullCombo && (
          <span>Full Combo</span>
        )}
        {row.original.isAllJustice && <span>All Justice</span>}
      </div>
    ),
    // sortingFn: (a, b) => {
    //   const isAllJustice = a.original.isAllJustice;
    //   const defaultSort = b.original.isAllJustice;

    //   if (isAllJustice && !defaultSort) return -1;
    //   if (!isAllJustice && defaultSort) return 1;
    //   return 0;
    // },
  },

  {
    accessorKey: "Attempts",
    header: "Attempts",

    cell: ({ row }) => (
      <div className="font-medium">{row.original.playCount}</div>
    ),
  },

  {
    id: "actions",
    header: () => <div className="pl-2 text-left">More</div>,
    cell: ({ row }) => {
      const [error, setError] = useState<string>("");
      // eslint-disable-next-line react-hooks/rules-of-hooks
      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}`);
          if (newTab) {
            newTab.focus();
          } 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={() =>
                song.title && navigator.clipboard.writeText(song.title)
              }
            >
              Copy song title
            </DropdownMenuItem> */}
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleGenerateShareToken}>
              Share Song
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
  },
];
