'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { getAnalysisRequest, refreshAnalysis } from '@/lib/api';
import { buildSummonerDetailPath } from '@/lib/routes';
import { translateApiErrorMessage, translateRequestStatus } from '@/lib/ui-text';

export function SearchStatus({
  requestId,
  gameName,
  tagLine,
  autoStart = false,
  stablePath,
}: {
  requestId: string | null;
  gameName: string | null;
  tagLine: string | null;
  autoStart?: boolean;
  stablePath?: string | null;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [activeRequestId, setActiveRequestId] = useState<string | null>(requestId);
  const [status, setStatus] = useState<string>('PENDING');
  const [error, setError] = useState<string | null>(null);

  const resolvedStablePath = useMemo(() => {
    if (stablePath) return stablePath;
    if (!gameName || !tagLine) return null;
    return buildSummonerDetailPath(gameName, tagLine);
  }, [gameName, stablePath, tagLine]);

  useEffect(() => {
    setActiveRequestId(requestId);
  }, [requestId]);

  useEffect(() => {
    if (!autoStart || activeRequestId || !gameName || !tagLine) return;
    let cancelled = false;

    void refreshAnalysis({
      gameName,
      tagLine,
      region: 'KR',
    })
      .then((data) => {
        if (!cancelled) {
          setActiveRequestId(String(data.requestId));
        }
      })
      .catch((err) => {
        if (!cancelled) {
          setError(
            translateApiErrorMessage(
              err instanceof Error ? err.message : 'Failed to request analysis refresh.',
            ),
          );
        }
      });

    return () => {
      cancelled = true;
    };
  }, [activeRequestId, autoStart, gameName, tagLine]);

  useEffect(() => {
    if (!activeRequestId) return;
    let cancelled = false;

    const finishWithStableRoute = (latestSnapshotId: string | null) => {
      if (resolvedStablePath) {
        if (pathname === resolvedStablePath) {
          router.refresh();
          return;
        }

        router.replace(resolvedStablePath);
        return;
      }

      if (latestSnapshotId) {
        router.replace(`/result/${latestSnapshotId}`);
      }
    };

    const poll = async () => {
      try {
        const data = await getAnalysisRequest(activeRequestId);
        if (cancelled) return;

        setStatus(data.status);

        if (data.status === 'DONE') {
          finishWithStableRoute(data.latestSnapshotId);
          return;
        }

        if (data.status === 'FAILED') {
          setError(translateApiErrorMessage(data.errorMessage ?? 'Analysis request failed.'));
          return;
        }

        window.setTimeout(poll, 2500);
      } catch (err) {
        if (!cancelled) {
          setError(
            translateApiErrorMessage(
              err instanceof Error ? err.message : 'Failed to check analysis status.',
            ),
          );
        }
      }
    };

    void poll();

    return () => {
      cancelled = true;
    };
  }, [activeRequestId, pathname, resolvedStablePath, router]);

  return (
    <main className="mx-auto max-w-4xl px-4 pb-20 pt-10">
      <section className="result-hero rounded-[2rem]">
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_18%_24%,rgba(74,215,226,0.18),transparent_24%),radial-gradient(circle_at_86%_20%,rgba(216,173,83,0.18),transparent_28%),linear-gradient(135deg,#121926_0%,#1d142f_100%)]" />
        <div className="relative z-[2] px-7 py-9 md:px-10">
          <p className="text-sm font-black tracking-[0.24em] text-[#d8ad53]">분석 진행 중</p>
          <h1 className="mt-3 text-5xl font-black tracking-[-0.06em] text-white">
            {gameName ? `${gameName}${tagLine ? `#${tagLine}` : ''}` : '플레이어 검색을 준비하고 있습니다'}
          </h1>
          <p className="mt-5 max-w-2xl text-lg leading-8 text-[#c8d4e5]">
            최신 경기 기록을 먼저 모아두고, 플레이 성향과 GGTI 결과를 다시 계산하고 있습니다.
            준비가 끝나면 현재 소환사 상세 페이지에서 최신 결과가 바로 반영됩니다.
          </p>
          <div className="mt-8 grid gap-4 sm:grid-cols-3">
            <StepCard
              step="1"
              title="전적 수집"
              body="최신 경기 ID와 과거 매치 데이터를 계정 기준으로 빠르게 수집합니다."
              active={status === 'COLLECTING_MATCHES' || status === 'PENDING'}
            />
            <StepCard
              step="2"
              title="성향 계산"
              body="모인 전적을 기준으로 플레이 성향 지표와 경기 패턴을 다시 계산합니다."
              active={status === 'CALCULATING'}
            />
            <StepCard
              step="3"
              title="GGTI 생성"
              body="최신 전적을 바탕으로 GGTI 요약과 해설을 생성하고 결과를 갱신합니다."
              active={status === 'GENERATING_AI'}
            />
          </div>
          <div className="mt-8 flex flex-wrap gap-3">
            <span className="rounded-2xl border border-white/10 bg-white/5 px-5 py-3 text-sm font-black text-white">
              상태: {translateRequestStatus(status)}
            </span>
            <Link href="/" className="inline-flex rounded-2xl bg-[#d8ad53] px-5 py-3 font-black text-[#111722]">
              홈으로
            </Link>
          </div>
          {error ? <p className="mt-4 text-sm font-bold text-[#ff7088]">{error}</p> : null}
        </div>
      </section>
    </main>
  );
}

function StepCard({
  step,
  title,
  body,
  active,
}: {
  step: string;
  title: string;
  body: string;
  active: boolean;
}) {
  return (
    <div
      className={`rounded-2xl border p-4 ${
        active ? 'border-[#5ce1e6]/30 bg-[#10222a]' : 'border-white/8 bg-black/18'
      }`}
    >
      <p className="text-sm font-black text-[#d8ad53]">단계 {step}</p>
      <p className="mt-2 text-lg font-black text-white">{title}</p>
      <p className="mt-2 text-sm leading-6 text-[#9fb0c7]">{body}</p>
    </div>
  );
}
