import { useMemo, useState } from "react"
import { useParams } from "react-router"
import { Link } from "react-router-dom"
import { GetUserCards } from "../../api/card"
import WithDataFetching from "../../components/withdatafetching"
import Card from "../../types/card"

export default function XpCenter() {
  const { slug = "gigiz22" } = useParams()

  return (
    <WithDataFetching<Card[]>
      queryKey={["user", slug, "cards"]}
      queryFn={() => GetUserCards(slug)}
      refetchOnWindowFocus={false}
    >
      {(data) => <CardList cards={data} />}
    </WithDataFetching>
  )
}

function CardList({ cards }: { cards: Card[] }) {
  const [sortConfig, setSortConfig] = useState<{
    key: string
    direction: "asc" | "desc"
  } | null>(null)

  const [hideMaxLevelUp, setHideMaxLevelUp] = useState(false)

  const filteredCards = useMemo(() => {
    return hideMaxLevelUp
      ? cards.filter(
          (card) => card.levelUpAppliedCount < card.maxLevelUpAppliedCount
        )
      : cards
  }, [cards, hideMaxLevelUp])

  const sortedCards = useMemo(() => {
    let sortableCards = filteredCards.map((card) => ({
      ...card,
      xpNeeded:
        card.xpNeededForNextGrade > card.xp
          ? card.xpNeededForNextGrade - card.xp
          : "N/A",
      xpPercentage:
        card.xpNeededForNextGrade > card.xp
          ? ((card.xpNeededForNextGrade - card.xp) * 100) /
            (card.xpNeededForNextGrade - card.xpNeededForCurrentGrade)
          : "N/A",
    }))

    if (sortConfig !== null) {
      sortableCards.sort((a, b) => {
        const key = sortConfig.key as keyof typeof a
        if (a[key] < b[key]) {
          return sortConfig.direction === "asc" ? -1 : 1
        }
        if (a[key] > b[key]) {
          return sortConfig.direction === "asc" ? 1 : -1
        }
        return 0
      })
    }
    return sortableCards
  }, [filteredCards, sortConfig])

  const requestSort = (key: string) => {
    let direction: "asc" | "desc" = "asc"
    if (
      sortConfig &&
      sortConfig.key === key &&
      sortConfig.direction === "asc"
    ) {
      direction = "desc"
    }
    setSortConfig({ key, direction })
  }

  const getSortIndicator = (key: string) => {
    if (!sortConfig || sortConfig.key !== key) return null
    return sortConfig.direction === "asc" ? "↑" : "↓"
  }

  return (
    <>
      <div className="flex w-full items-center justify-end p-3">
        <label className="inline-flex items-center">
          <input
            type="checkbox"
            checked={hideMaxLevelUp}
            onChange={() => setHideMaxLevelUp(!hideMaxLevelUp)}
          />
          <span className="ml-2">Hide cards with max level up applied</span>
        </label>
      </div>
      <table className="min-w-full">
        <thead className="bg-gray-50">
          <tr>
            <th
              scope="col"
              className="px-6 py-3 text-left text-xs font-medium uppercase text-gray-500"
            ></th>
            <th
              scope="col"
              className="px-6 py-3 text-left text-xs font-medium uppercase text-gray-500"
            >
              Player
            </th>
            <th
              scope="col"
              className="w-auto cursor-pointer px-6 py-3 text-center text-xs font-medium uppercase text-gray-500"
              onClick={() => requestSort("grade")}
            >
              Grade{" "}
              <span className="ml-1 align-middle">
                {getSortIndicator("grade")}
              </span>
            </th>
            <th
              scope="col"
              className="cursor-pointer px-6 py-3 text-center text-xs font-medium uppercase  text-gray-500"
              onClick={() => requestSort("xp")}
            >
              XP{" "}
              <span className="ml-1 align-middle">
                {getSortIndicator("xp")}
              </span>
            </th>
            <th
              scope="col"
              className="cursor-pointer px-6 py-3 text-center text-xs font-medium uppercase text-gray-500"
              onClick={() => requestSort("xpNeeded")}
            >
              XP Needed for Next Grade{" "}
              <span className="ml-1 align-middle">
                {getSortIndicator("xpNeeded")}
              </span>
            </th>
            <th
              scope="col"
              className="cursor-pointer px-6 py-3 text-center text-xs font-medium uppercase text-gray-500"
              onClick={() => requestSort("xpPercentage")}
            >
              % Until next grade{" "}
              <span className="ml-1 align-middle">
                {getSortIndicator("xpPercentage")}
              </span>
            </th>
            <th
              scope="col"
              className="cursor-pointer px-6 py-3 text-center text-xs font-medium uppercase text-gray-500"
            >
              Level up applied
            </th>
          </tr>
        </thead>
        <tbody className="divide-y-2 divide-gray-200 bg-white">
          {sortedCards.map((card) => (
            <tr key={card.id}>
              <td className="px-3 py-1">
                <a
                  href={`https://sorare.com/fr/football/cards/${card.slug}`}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img className="h-16" src={card.pictureUrl} alt={card.name} />
                </a>
              </td>
              <td className="border-r-2 border-neutral-200 px-3 py-1">
                <Link to={`/player/${card.playerSlug}`}>
                  <div className="flex items-center">
                    <div className="text-md font-secondary font-semibold text-neutral-900">
                      {card.playerDisplayName}
                    </div>
                  </div>
                </Link>
              </td>
              <td className="w-auto border-r border-neutral-200 px-3 py-1 text-center">
                <div className="text-sm text-neutral-900">{card.grade}</div>
              </td>
              <td className="border-r-2 border-neutral-200 px-3 py-1 text-center">
                <div className="text-sm text-neutral-900">{card.xp}</div>
              </td>
              <td className="border-r-2 border-neutral-200 px-3 py-1 text-center">
                <div className="text-sm text-neutral-900">{card.xpNeeded}</div>
              </td>
              <td className="border-r-2 border-neutral-200 px-3 py-1 text-center">
                <div className="text-sm text-neutral-900">
                  {card.xpPercentage !== "N/A"
                    ? `${Number(card.xpPercentage).toFixed(0)}%`
                    : "N/A"}
                </div>
              </td>
              <td className="px-3 py-1 text-center">
                <div className="text-sm text-neutral-900">
                  {card.levelUpAppliedCount} / {card.maxLevelUpAppliedCount}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  )
}
