'use client';

import { useEffect, useRef, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { getAnalysisRequest } from '@/lib/api';
import { translateApiErrorMessage, translateRequestStatus } from '@/lib/ui-text';

export function ResultRequestWatcher({
  requestId,
  snapshotId,
  stablePath,
}: {
  requestId: string;
  snapshotId: string;
  stablePath?: string | null;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [status, setStatus] = useState('PENDING');
  const [error, setError] = useState<string | null>(null);
  const timeoutRef = useRef<number | null>(null);

  useEffect(() => {
    let cancelled = false;

    const replaceWithError = (message: string) => {
      if (stablePath) {
        const target = `${stablePath}?refreshError=${encodeURIComponent(message)}`;
        router.replace(target);
        return;
      }

      router.replace(`/result/${snapshotId}?refreshError=${encodeURIComponent(message)}`);
    };

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

        router.replace(stablePath);
        return;
      }

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

      router.refresh();
    };

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

        setStatus(data.status);

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

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

        timeoutRef.current = window.setTimeout(() => {
          void poll();
        }, 2000);
      } catch (err) {
        if (cancelled) return;
        const message = translateApiErrorMessage(
          err instanceof Error ? err.message : 'Failed to check analysis status.',
        );
        setError(message);
        replaceWithError(message);
      }
    };

    void poll();

    return () => {
      cancelled = true;
      if (timeoutRef.current) {
        window.clearTimeout(timeoutRef.current);
      }
    };
  }, [pathname, requestId, router, snapshotId, stablePath]);

  return (
    <div className="rounded-[10px] border border-[#4a5a88] bg-[#1f2a41] px-4 py-3 text-left shadow-[0_10px_30px_rgba(0,0,0,0.18)]">
      <div className="flex flex-wrap items-center gap-3">
        <span className="inline-flex h-2.5 w-2.5 animate-pulse rounded-full bg-[#6fd8ff]" />
        <span className="text-[13px] font-black tracking-[0.18em] text-[#8eb8ff]">
          GGTI 갱신 중
        </span>
        <span className="rounded-full bg-white/6 px-3 py-1 text-[12px] font-semibold text-white">
          상태: {translateRequestStatus(status)}
        </span>
      </div>
      <p className="mt-2 text-[13px] leading-6 text-[#c8d4e7]">
        전적 레이아웃은 먼저 보여드리고, 분석 지표와 GGTI 요약만 백그라운드에서 다시
        계산하고 있습니다.
      </p>
      {error ? <p className="mt-2 text-[12px] font-semibold text-[#ff98a7]">{error}</p> : null}
    </div>
  );
}
