/* eslint-disable @next/next/no-img-element */
'use client';

import { useEffect, useState } from 'react';

import { ArrowRight, ExternalLink, Home, Lightbulb, Minus, Plus } from 'lucide-react';
import { Range, getTrackBackground } from 'react-range';

import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Text } from '@/components/ui/typography';
import { cn } from '@/lib/utils';
import { buildMediaUrl } from '@/utils/images';

import { Link } from '@/i18n/navigation';

import GameMenu, { CountUp } from './GameMenu';
import GameStage, { GAME_CONTROLS_OFFSET, GAME_HOME_POSITION, gameGlass } from './GameStage';

export interface YearItem {
  id: string;
  title: string;
  creator: string | null;
  place: string | null;
  category: string;
  year: number;
  imageId: number;
}
interface RoundResult {
  item: YearItem;
  guess: number;
  score: number;
  hintCount: number;
}
type Phase = 'intro' | 'guessing' | 'revealed' | 'finished';
const ROUND_COUNT = 5;
const MAX_SCORE = 5000;
const MAX_TOTAL = ROUND_COUNT * MAX_SCORE;
const YEAR_SCALE = 8;
// The new hint scoring is not comparable to the earlier game's records.
const BEST_SCORE_KEY = 'mikor-keszult-best-v2';
const formatNumber = (value: number) => value.toLocaleString('hu-HU');
const maskYears = (title: string) => title.replace(/\b(19|20)\d{2}\b/g, '····');

function shuffle<T>(list: T[]): T[] {
  const copy = [...list];
  for (let i = copy.length - 1; i > 0; i -= 1) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}
/** One creation from each of five different decades. */
function pickRounds(items: YearItem[]): YearItem[] {
  const byDecade = new Map<number, YearItem[]>();
  for (const item of items) {
    if (!item.creator?.trim()) continue;
    const decade = Math.floor(item.year / 10) * 10;
    const list = byDecade.get(decade) ?? [];
    list.push(item);
    byDecade.set(decade, list);
  }
  return shuffle([...byDecade.values()])
    .slice(0, ROUND_COUNT)
    .map((list) => list[Math.floor(Math.random() * list.length)]);
}
function readBestScore(): number | null {
  try {
    const value = Number(window.localStorage.getItem(BEST_SCORE_KEY));
    return Number.isFinite(value) && value > 0 ? value : null;
  } catch {
    return null;
  }
}
function verdict(score: number): string {
  const share = score / MAX_TOTAL;
  if (share >= 0.85) return 'Ön élő kultúrtörténeti lexikon!';
  if (share >= 0.6) return 'Nagyon jó korérzék, alig tévedett.';
  if (share >= 0.35) return 'Szép eredmény, az évtizedek már kirajzolódnak.';
  return 'Az idő relatív. Nézzen bele az alkotásokba, és próbálja újra!';
}
function roundMessage(difference: number): string {
  if (difference === 0) return 'Telitalálat!';
  if (difference <= 2) return 'Majdnem pontosan!';
  if (difference <= 5) return 'Nagyon közel!';
  if (difference <= 12) return 'Közel jár az évtizedhez.';
  return 'Ez most messze volt.';
}
function DecadeAxis({ firstYear, lastYear }: { firstYear: number; lastYear: number }) {
  const ticks: number[] = [];
  for (let year = Math.ceil(firstYear / 10) * 10; year <= lastYear; year += 10) ticks.push(year);
  return (
    <div className="relative mx-2 mt-3 h-4">
      {ticks.map((year) => (
        <Text
          key={year}
          as="span"
          variant="caption"
          tone="muted"
          className="absolute -translate-x-1/2"
          style={{ left: `${((year - firstYear) / (lastYear - firstYear)) * 100}%` }}
        >
          {year}
        </Text>
      ))}
    </div>
  );
}
function RevealTimeline({
  firstYear,
  lastYear,
  guess,
  answer,
}: {
  firstYear: number;
  lastYear: number;
  guess: number;
  answer: number;
}) {
  const position = (year: number) => ((year - firstYear) / (lastYear - firstYear)) * 100;
  return (
    <div className="relative mx-2 h-1.5 bg-[#151720]/15" aria-hidden>
      <div
        className="absolute inset-y-0 bg-mma-yellow"
        style={{
          left: `${position(Math.min(guess, answer))}%`,
          width: `${Math.abs(position(guess) - position(answer))}%`,
        }}
      />
      <div
        className="absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-mma-yellow shadow"
        style={{ left: `${position(guess)}%` }}
      />
      <div
        className="absolute bottom-full mb-1 -translate-x-1/2 bg-[#151720] px-2 py-0.5 font-slab text-sm font-bold text-white"
        style={{ left: `${position(answer)}%` }}
      >
        {answer}
      </div>
      <div
        className="absolute top-1/2 h-5 w-1.5 -translate-x-1/2 -translate-y-1/2 bg-[#151720]"
        style={{ left: `${position(answer)}%` }}
      />
    </div>
  );
}

export default function YearGame({
  items,
  firstYear,
  lastYear,
}: {
  items: YearItem[];
  firstYear: number;
  lastYear: number;
}) {
  const startGuess = Math.round((firstYear + lastYear) / 2);
  const [phase, setPhase] = useState<Phase>('intro');
  const [rounds, setRounds] = useState<YearItem[]>([]);
  const [roundIndex, setRoundIndex] = useState(0);
  const [guess, setGuess] = useState(startGuess);
  const [hintsUsed, setHintsUsed] = useState(0);
  const [results, setResults] = useState<RoundResult[]>([]);
  const [bestScore, setBestScore] = useState<number | null>(null);
  useEffect(() => {
    setBestScore(readBestScore());
  }, []);
  const item = rounds[roundIndex];
  const result = phase === 'revealed' ? results[roundIndex] : null;
  const totalScore = results.reduce((sum, round) => sum + round.score, 0);
  const availableHints = item
    ? [
        { label: 'Alkotó', value: maskYears(item.creator ?? ''), penalty: 0.1 },
        { label: 'Cím', value: maskYears(item.title), penalty: 0.15 },
      ]
    : [];
  const usedHints = availableHints.slice(0, hintsUsed);
  const hintPenalty = usedHints.reduce((sum, hint) => sum + hint.penalty, 0);
  const clampYear = (year: number) => Math.min(lastYear, Math.max(firstYear, year));
  const resetRound = () => {
    setGuess(startGuess);
    setHintsUsed(0);
    setPhase('guessing');
  };
  const startGame = () => {
    setRounds(pickRounds(items));
    setRoundIndex(0);
    setResults([]);
    resetRound();
  };
  const submitGuess = () => {
    if (!item || phase !== 'guessing') return;
    setResults((current) => [
      ...current,
      {
        item,
        guess,
        hintCount: hintsUsed,
        score: Math.round(
          MAX_SCORE * (1 - hintPenalty) * Math.exp(-Math.abs(guess - item.year) / YEAR_SCALE)
        ),
      },
    ]);
    setPhase('revealed');
  };
  const nextRound = () => {
    if (roundIndex + 1 >= rounds.length) {
      if (bestScore === null || totalScore > bestScore) {
        try {
          window.localStorage.setItem(BEST_SCORE_KEY, String(totalScore));
        } catch {
          /* Storage is optional. */
        }
        setBestScore(totalScore);
      }
      setPhase('finished');
      return;
    }
    setRoundIndex((index) => index + 1);
    resetRound();
  };
  const backToIntro = () => {
    setPhase('intro');
    setRounds([]);
    setResults([]);
    setHintsUsed(0);
  };
  const enoughDecades =
    new Set(
      items.filter((entry) => entry.creator?.trim()).map((entry) => Math.floor(entry.year / 10))
    ).size >= ROUND_COUNT;
  const menu = phase === 'intro' || phase === 'finished' || !enoughDecades;
  const difference = result ? Math.abs(result.guess - item.year) : 0;

  return (
    <GameStage menu={menu}>
      {!enoughDecades ? (
        <Text tone="inherit" className="relative p-10">
          Nincs elég képes alkotás öt különböző évtizedből a játékhoz.
        </Text>
      ) : menu ? (
        <GameMenu
          phase={phase === 'finished' ? 'finished' : 'intro'}
          title="Mikor készült?"
          description="Öt alkotás, öt évtized. Állítsa be az évet, és ha elakad, kérjen segítséget! A segítségek csökkentik az elérhető pontszámot."
          totalScore={totalScore}
          bestScore={bestScore}
          message={verdict(totalScore)}
          results={results.map((round) => ({
            ...round,
            detail:
              Math.abs(round.guess - round.item.year) +
              ' év eltérés' +
              (round.hintCount ? ' · ' + round.hintCount + ' segítséggel' : ''),
          }))}
          startGame={startGame}
          backToIntro={backToIntro}
        />
      ) : item ? (
        <>
          <div className="relative h-[46svh] min-h-[300px] overflow-hidden lg:absolute lg:inset-0 lg:h-auto">
            <img
              src={buildMediaUrl(item.imageId, 'w640')}
              alt=""
              aria-hidden
              className="absolute inset-0 h-full w-full scale-110 object-cover opacity-40 blur-2xl"
            />
            <img
              key={item.id}
              src={buildMediaUrl(item.imageId, 'w1024')}
              alt="A kitalálandó alkotás"
              className="relative h-full w-full object-contain p-4 pb-16 pt-16 duration-500 animate-in fade-in lg:p-16 lg:pr-[420px]"
            />
            <div
              aria-hidden
              className="pointer-events-none absolute inset-x-0 top-0 h-28 bg-gradient-to-b from-black/60 to-transparent"
            />
            {!result && hintsUsed < availableHints.length ? (
              <div className="absolute bottom-3 left-3 z-20 sm:bottom-4 sm:left-4">
                <Button
                  inverted
                  variant="quiet"
                  className={cn(gameGlass, 'text-white')}
                  onClick={() =>
                    setHintsUsed((count) => Math.min(availableHints.length, count + 1))
                  }
                >
                  <Lightbulb /> Segítség {hintsUsed + 1}/{availableHints.length}
                </Button>
              </div>
            ) : null}
          </div>
          <div className="pointer-events-none absolute inset-x-0 top-0 z-20 p-3 pt-16 sm:p-4 sm:pt-16">
            <div className="flex max-w-full flex-col items-start gap-2 sm:max-w-sm">
              <Badge variant="accent" size="sm">
                {item.category}
              </Badge>
              {!result
                ? usedHints.map((hint) => (
                    <div
                      key={hint.label}
                      className={cn(
                        gameGlass,
                        'px-3 py-2 duration-300 animate-in fade-in slide-in-from-left-2'
                      )}
                    >
                      <span className="block text-[10px] font-semibold uppercase tracking-[0.2em] text-white/55">
                        {hint.label}
                      </span>
                      <span className="mt-0.5 block text-sm font-semibold leading-snug">
                        {hint.value}
                      </span>
                    </div>
                  ))
                : null}
            </div>
            <div className={cn('absolute flex items-start gap-2', GAME_CONTROLS_OFFSET)}>
              <div className={cn(gameGlass, 'flex h-10 items-center gap-3 px-3')}>
                <ol
                  className="flex items-center gap-1.5"
                  aria-label={`${roundIndex + 1}. kör / ${rounds.length}`}
                >
                  {rounds.map((round, index) => (
                    <li
                      key={round.id}
                      className={cn(
                        'size-2 rounded-full',
                        index < results.length
                          ? 'bg-mma-yellow'
                          : index === roundIndex
                            ? 'bg-white'
                            : 'bg-white/25'
                      )}
                    />
                  ))}
                </ol>
                <span className="font-slab text-lg font-bold leading-none">
                  {formatNumber(totalScore)}
                </span>
              </div>
            </div>
            <Button
              inverted
              variant="quiet"
              size="icon"
              className={cn(gameGlass, GAME_HOME_POSITION, 'pointer-events-auto text-white')}
              onClick={backToIntro}
              aria-label="Vissza a kezdőképernyőre"
              title="Vissza a kezdőképernyőre"
            >
              <Home />
            </Button>
          </div>
          <div className="relative z-30 p-3 lg:absolute lg:bottom-4 lg:right-4 lg:w-[380px] lg:p-0">
            <div className="bg-white p-5 text-[#151720] shadow-2xl sm:p-6">
              {result ? (
                <div aria-live="polite">
                  <Text variant="meta" tone="muted">
                    {roundMessage(difference)}
                  </Text>
                  <h2 className="mt-2 font-slab text-xl font-bold leading-tight">{item.title}</h2>
                  <Text variant="bodySm" tone="muted" className="mt-2">
                    {[item.creator, item.place].filter(Boolean).join(' · ')}
                  </Text>
                  <Link
                    href={{ pathname: '/alkotas/[id]', params: { id: item.id } }}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-2 inline-flex items-center gap-1 text-xs font-semibold hover:underline"
                  >
                    Az alkotás oldala <ExternalLink size={12} />
                  </Link>
                  <div className="mt-5">
                    <CountUp value={result.score} className="font-slab text-4xl font-bold" />
                    <span className="ml-2 text-sm">pont</span>
                  </div>
                  <Text variant="caption" tone="muted">
                    {difference} év eltérés
                    {result.hintCount ? ' · ' + result.hintCount + ' segítséggel' : ''}
                  </Text>
                  <Text variant="bodySm" className="mt-3">
                    Tipp: {result.guess} · Helyes év: <strong>{item.year}</strong>
                  </Text>
                  <div className="mt-10">
                    <RevealTimeline
                      firstYear={firstYear}
                      lastYear={lastYear}
                      guess={result.guess}
                      answer={item.year}
                    />
                    <DecadeAxis firstYear={firstYear} lastYear={lastYear} />
                  </div>
                  <Button size="lg" className="mt-6 w-full" onClick={nextRound}>
                    {roundIndex + 1 >= rounds.length ? 'Eredmény' : 'Következő kör'} <ArrowRight />
                  </Button>
                </div>
              ) : (
                <>
                  <Text variant="meta" tone="muted">
                    Melyik évben készült?
                  </Text>
                  <div className="mt-4 flex items-center justify-between gap-3">
                    <Button
                      size="icon"
                      variant="quiet"
                      aria-label="Egy évvel korábban"
                      disabled={guess <= firstYear}
                      onClick={() => setGuess((year) => clampYear(year - 1))}
                    >
                      <Minus />
                    </Button>
                    <span className="font-slab text-5xl font-bold leading-none">{guess}</span>
                    <Button
                      size="icon"
                      variant="quiet"
                      aria-label="Egy évvel később"
                      disabled={guess >= lastYear}
                      onClick={() => setGuess((year) => clampYear(year + 1))}
                    >
                      <Plus />
                    </Button>
                  </div>
                  <div className="mt-6 px-2 py-2">
                    <Range
                      values={[guess]}
                      min={firstYear}
                      max={lastYear}
                      step={1}
                      onChange={(values) => setGuess(values[0])}
                      renderTrack={({ props, children }) => (
                        <div
                          {...props}
                          className="h-1.5 w-full"
                          style={{
                            ...props.style,
                            background: getTrackBackground({
                              values: [guess],
                              colors: ['#151720', 'rgba(21,23,32,0.16)'],
                              min: firstYear,
                              max: lastYear,
                            }),
                          }}
                        >
                          {children}
                        </div>
                      )}
                      renderThumb={({ props }) => {
                        const { key, ...rest } = props;
                        return (
                          <div
                            key={key}
                            {...rest}
                            aria-label="Évszám"
                            className="size-6 rounded-full border-2 border-white bg-mma-yellow shadow focus:outline-none focus-visible:ring-2 focus-visible:ring-mma-blue"
                          />
                        );
                      }}
                    />
                  </div>
                  <DecadeAxis firstYear={firstYear} lastYear={lastYear} />
                  <Text variant="caption" tone="muted" className="mt-4">
                    Állítsa be az évet a csúszkával vagy a nyílbillentyűkkel. A segítségek
                    csökkentik az elérhető pontszámot.
                  </Text>
                  <Button size="lg" className="mt-5 w-full" onClick={submitGuess}>
                    Tippelek
                  </Button>
                </>
              )}
            </div>
          </div>
        </>
      ) : null}
    </GameStage>
  );
}
