'use client';

import { useEffect, useState } from 'react';
import { apiUrl } from '@/lib/constants';
import { getAdminToken, setAdminToken } from '@/lib/adminAuth';

interface AdminAccessGateProps {
  children: React.ReactNode;
}

export default function AdminAccessGate({ children }: AdminAccessGateProps) {
  const [tokenInput, setTokenInput] = useState('');
  const [verified, setVerified] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    const saved = getAdminToken();
    if (saved) {
      setTokenInput(saved);
      verifyToken(saved);
    }
  }, []);

  const verifyToken = async (tokenToVerify: string) => {
    if (!tokenToVerify) {
      setError('请输入 admin token');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch(`${apiUrl}/auth/verify?token=${encodeURIComponent(tokenToVerify)}`, {
        headers: { 'x-admin-token': tokenToVerify },
      });

      if (!response.ok) {
        setVerified(false);
        setError('Token 验证失败，请重试');
        return;
      }

      setAdminToken(tokenToVerify);
      setVerified(true);
      setError('');
    } catch (err) {
      console.error('Error verifying token', err);
      setError('无法验证 token，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  if (verified) {
    return <>{children}</>;
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-background text-text-primary p-6">
      <div className="w-full max-w-md bg-surface/80 border border-surface-hover rounded-2xl shadow-2xl p-6 space-y-5">
        <div>
          <p className="text-sm uppercase tracking-wide text-text-secondary">Private Space Access</p>
          <h1 className="text-2xl font-bold mt-1">Enter Admin Token</h1>
          <p className="text-sm text-text-secondary mt-2">
            这个站点是私有的，访问前需要输入管理员 token。
          </p>
        </div>

        <div className="space-y-3">
          <label className="block text-sm text-text-secondary">Admin token</label>
          <input
            type="password"
            className="input w-full"
            placeholder="例如：my-secret-token"
            value={tokenInput}
            onChange={(e) => setTokenInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                verifyToken(tokenInput);
              }
            }}
            disabled={loading}
          />
          {error && <p className="text-red-400 text-sm">{error}</p>}
        </div>

        <button
          className="btn btn-primary w-full"
          onClick={() => verifyToken(tokenInput)}
          disabled={loading}
        >
          {loading ? '验证中...' : '进入我的空间'}
        </button>

        <p className="text-xs text-text-secondary text-center">
          如需重置或更换 token，请刷新页面重新输入。
        </p>
      </div>
    </div>
  );
}
