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

interface CaptchaPoolInfo {
  available: boolean;
  reason?: 'headless_mode' | 'display_unavailable' | 'no_session';
  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 { t } = useTranslation('admin');
  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">{t('captcha.noAccessTitle')}</h1>
          <p className="text-sm text-slate-600">
            {t('captcha.noAccessBody')}
          </p>
        </div>
      </div>
    );
  }

  if (isLoading) {
    return (
      <div className="h-full flex items-center justify-center text-sm text-slate-500">
        {t('captcha.loading')}
      </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 dark:text-red-300">
          {t('captcha.fetchFailed', { 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-canvas 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 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/15 text-amber-800 dark:text-amber-300 animate-pulse">
              {t('captcha.pendingBadge')}
            </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-canvas text-slate-700 hover:bg-surface transition-colors disabled:opacity-50"
              title={t('captcha.resetTitle')}
            >
              {reset.isPending ? t('captcha.resetting') : t('captcha.resetButton')}
            </button>
          )}
        </div>
      </div>

      <div className="flex-1 min-h-0 p-3">
        {data?.available && data.novncPath ? (
          <div className="h-full bg-canvas 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"
                >
                  {t('captcha.openNewTab')}
                </a>
              </div>
            </div>
            {pip.isOpen ? (
              <div className="flex-1 w-full flex items-center justify-center bg-slate-50 text-xs text-slate-500">
                {t('captcha.pipActive')}
              </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-canvas 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">{t('captcha.poolNotRunningTitle')}</p>
              {data?.reason === 'headless_mode' ? (
                <p>
                  <Trans t={t} i18nKey="captcha.headlessMode" components={{ strong: <strong /> }} />
                </p>
              ) : data?.reason === 'display_unavailable' ? (
                <p>
                  {t('captcha.displayUnavailable')}
                </p>
              ) : (
                <p>
                  {t('captcha.noSession')}
                </p>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
