"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 { 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="font-medium w-[300px] truncate">
          {isLoading || !jacketPath ? (
            <Skeleton className="w-8 h-8 inline-block mr-2" />
          ) : (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={`/jacketArt/${jacketPath}`}
              alt="Jacket"
              className="w-8 h-8 inline-block mr-2"
            />
          )}
          <div className="flex-1">{row.original.title}</div>
        </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;

      if (highScore < lowScore) return 1;
      if (highScore > lowScore) return -1;
      // TODO: FIGURE OUT DEFAULT SORT
      return 0;
    },
  },
  {
    accessorKey: "isNew",
    header: "Up Score",
    cell: ({ row }) => (
      <div>
        {row.original.isNewRecord && <span className="pl-2 ">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}</div>,
  },
  {
    accessorKey: "FC / AJ",
    header: ({ column }) => {
      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          FC/AJ
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      );
    },
    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="text-left pl-2">More</div>,
    cell: ({ row }) => {
      const song = row.original;
      // eslint-disable-next-line react-hooks/rules-of-hooks
      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}`, "_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>
      );
    },
  },
];
