import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { POLLING } from '../lib/constants.js';
import { usePictureInPicture } from '../lib/usePictureInPicture.js';
import { PipButton } from '../components/browser/PipButton.js';

interface CaptchaPoolInfo {
  available: boolean;
  sessionId?: string;
  novncPath?: string;
  display?: string;
  captchaPending?: boolean;
  createdAt?: string;
}

const CAPTCHA_POOL_QUERY_KEY = ['admin', 'captcha-pool'] as const;

function useCaptchaPool() {
  return useQuery<CaptchaPoolInfo>({
    queryKey: CAPTCHA_POOL_QUERY_KEY,
    queryFn: async () => {
      const r = await fetch('/api/local/browser/sessions/captcha-pool');
      if (r.status === 403) {
        throw new Error('forbidden');
      }
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json() as Promise<CaptchaPoolInfo>;
    },
    refetchInterval: POLLING.FAST,
    refetchOnWindowFocus: true,
  });
}

function useResetPool() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const r = await fetch('/api/local/browser/sessions/captcha-pool', {
        method: 'DELETE',
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    },
    onSettled: () => {
      qc.invalidateQueries({ queryKey: CAPTCHA_POOL_QUERY_KEY });
    },
  });
}

export function AdminCaptchaPage({ isAdmin }: { isAdmin: boolean }) {
  const { data, isLoading, isError, error } = useCaptchaPool();
  const reset = useResetPool();
  const pip = usePictureInPicture(data?.novncPath ?? null, 'noVNC — CAPTCHA Pool');

  if (!isAdmin) {
    return (
      <div className="h-full flex items-center justify-center p-8">
        <div className="max-w-md text-center">
          <h1 className="text-lg font-semibold text-slate-900 mb-2">アクセス権がありません</h1>
          <p className="text-sm text-slate-600">
            CAPTCHA Pool は admin 権限を持つユーザーのみが利用できます。
          </p>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="h-full flex items-center justify-center text-sm text-slate-500">
        読み込み中…
      </div>
    );
  }

  if (isError) {
    const msg = error instanceof Error ? error.message : String(error);
    return (
      <div className="h-full flex items-center justify-center p-8">
        <div className="max-w-md text-center text-sm text-red-700">
          CAPTCHA Pool の取得に失敗しました: {msg}
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col bg-surface">
      <div className="flex items-center justify-between border-b border-hairline bg-white px-4 py-3 gap-3">
        <div className="flex items-center gap-2">
          <h1 className="text-base font-semibold text-slate-900">CAPTCHA Pool</h1>
          <span className="text-2xs font-mono text-slate-400">admin</span>
          {data?.available && data.captchaPending && (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-2xs font-medium border border-amber-300 bg-amber-50 text-amber-800 animate-pulse">
              ⚠ CAPTCHA 待ち
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          {data?.available && (
            <button
              type="button"
              onClick={() => reset.mutate()}
              disabled={reset.isPending}
              className="px-3 py-1.5 rounded-md text-xs font-medium border border-hairline bg-white text-slate-700 hover:bg-surface transition-colors disabled:opacity-50"
              title="Pool を destroy する。次に WebSearch が CAPTCHA を踏むと自動的に再生成される"
            >
              {reset.isPending ? 'リセット中…' : 'Pool をリセット'}
            </button>
          )}
        </div>
      </div>

      <div className="flex-1 min-h-0 p-3">
        {data?.available && data.novncPath ? (
          <div className="h-full bg-white border border-hairline rounded-md overflow-hidden flex flex-col">
            <div className="border-b border-hairline px-3 py-2 text-2xs text-slate-500 flex items-center justify-between gap-2">
              <span className="truncate">display: {data.display ?? '-'} / sessionId: <span className="font-mono">{data.sessionId}</span></span>
              <div className="flex items-center gap-2">
                <PipButton pip={pip} />
                <a
                  href={data.novncPath}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-2xs text-accent hover:underline"
                >
                  新しいタブで開く ↗
                </a>
              </div>
            </div>
            {pip.isOpen ? (
              <div className="flex-1 w-full flex items-center justify-center bg-slate-50 text-xs text-slate-500">
                PiP ウィンドウで表示中。閉じるとここに戻ります。
              </div>
            ) : (
              <iframe
                src={data.novncPath}
                title="CAPTCHA Pool noVNC"
                className="flex-1 w-full border-0"
                allow="clipboard-read; clipboard-write"
              />
            )}
          </div>
        ) : (
          <div className="h-full bg-white border border-hairline rounded-md flex items-center justify-center p-8">
            <div className="max-w-md text-center text-sm text-slate-600">
              <p className="font-medium text-slate-800 mb-1">Pool は現在起動していません</p>
              <p>
                WebSearch が CAPTCHA を踏むか、admin が手動でセッションを起動した時点で
                noVNC が表示されます (5 秒ポーリング中)。
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
