'use client';

import { useState, useTransition } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { refreshAnalysis } from '@/lib/api';
import { buildSummonerDetailPath } from '@/lib/routes';
import { translateApiErrorMessage } from '@/lib/ui-text';

export function ResultRefreshButton({
  snapshotId,
  gameName,
  tagLine,
  stablePath,
}: {
  snapshotId: string;
  gameName: string;
  tagLine: string;
  stablePath?: string | null;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();
  const [message, setMessage] = useState<string | null>(null);
  const resolvedStablePath =
    stablePath ?? buildSummonerDetailPath(gameName || 'unknown', tagLine || 'KR1');

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-wrap gap-3">
        <button
          type="button"
          onClick={() =>
            startTransition(async () => {
              try {
                setMessage(null);
                await refreshAnalysis({
                  snapshotId,
                  gameName,
                  tagLine,
                  region: 'KR',
                });

                if (pathname === resolvedStablePath) {
                  router.refresh();
                  return;
                }

                router.replace(resolvedStablePath);
              } catch (error) {
                setMessage(
                  translateApiErrorMessage(
                    error instanceof Error ? error.message : 'Refresh request failed',
                  ),
                );
              }
            })
          }
          className="inline-flex min-w-[110px] items-center justify-center rounded-xl bg-[#4f6edb] px-5 py-3 text-sm font-black text-white transition hover:brightness-110 disabled:opacity-60"
          disabled={isPending}
        >
          {isPending ? (
            <span className="inline-flex items-center gap-2">
              <span className="h-4 w-4 animate-spin rounded-full border-2 border-white/25 border-t-white" />
              갱신 중
            </span>
          ) : (
            '전적 갱신'
          )}
        </button>
      </div>
      {message ? <p className="text-xs font-bold text-[#6fd8ff]">{message}</p> : null}
    </div>
  );
}
