import { useState, useCallback, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Dashboard from './Dashboard';
import {
  verifyAdminToken,
  setStoredAdminToken,
  getStoredAdminToken,
  getAdminConfig,
  updateAdminMonitorConfig,
} from '../services/api';
import AdminGroupsPanel from '../components/AdminGroupsPanel';

const INTERVAL_OPTIONS = [
  { minutes: 10, label: '10 分钟' },
  { minutes: 20, label: '20 分钟' },
  { minutes: 30, label: '30 分钟' },
  { minutes: 60, label: '1 小时' },
  { minutes: 180, label: '3 小时' },
  { minutes: 360, label: '6 小时' },
];

function AdminScheduleToolbar({ onLogout }) {
  const [intervalMinutes, setIntervalMinutes] = useState(30);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState('');
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setErr('');
    try {
      const c = await getAdminConfig();
      setIntervalMinutes(c.interval_minutes);
    } catch (e) {
      setErr(e.message || '加载配置失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function handleSave(e) {
    e.preventDefault();
    setSaving(true);
    setErr('');
    try {
      await updateAdminMonitorConfig({ interval_minutes: intervalMinutes });
      await load();
    } catch (e) {
      setErr(e.message || '保存失败');
    } finally {
      setSaving(false);
    }
  }

  return (
    <section className="bg-white/90 backdrop-blur border border-emerald-100 rounded-xl shadow-sm p-4 sm:p-5">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">
        <div>
          <h2 className="text-sm font-semibold text-gray-800">全局检测周期</h2>
          <p className="text-xs text-gray-500 mt-0.5">
            所有站点共用同一轮询间隔，保存后立即调整后台定时器（仍会先跑完上一轮逻辑）。
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={onLogout}
            className="text-xs px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50"
          >
            退出登录
          </button>
          <Link
            to="/"
            className="text-xs px-3 py-1.5 rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200"
          >
            公开页
          </Link>
        </div>
      </div>

      {loading ? (
        <p className="text-sm text-gray-500">加载中…</p>
      ) : (
        <form onSubmit={handleSave} className="flex flex-col sm:flex-row sm:items-end gap-3">
          <label className="flex flex-col gap-1 text-xs text-gray-600 flex-1 sm:max-w-xs">
            检测间隔
            <select
              value={intervalMinutes}
              onChange={(e) => setIntervalMinutes(Number(e.target.value))}
              className="mt-0.5 px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-800 bg-white focus:ring-2 focus:ring-emerald-500 outline-none"
            >
              {INTERVAL_OPTIONS.map((o) => (
                <option key={o.minutes} value={o.minutes}>
                  {o.label}
                </option>
              ))}
            </select>
          </label>
          <button
            type="submit"
            disabled={saving}
            className="px-4 py-2 text-sm font-medium text-white bg-emerald-600 rounded-lg hover:bg-emerald-700 disabled:opacity-60"
          >
            {saving ? '保存中…' : '保存周期'}
          </button>
        </form>
      )}
      {err ? <p className="text-xs text-red-600 mt-3">{err}</p> : null}
    </section>
  );
}

export default function AdminPanel() {
  const [authed, setAuthed] = useState(() => !!getStoredAdminToken());
  const [tokenInput, setTokenInput] = useState('');
  const [loginErr, setLoginErr] = useState('');
  const [loggingIn, setLoggingIn] = useState(false);

  async function handleLogin(e) {
    e.preventDefault();
    const t = tokenInput.trim();
    if (!t) {
      setLoginErr('请输入管理员令牌');
      return;
    }
    setLoggingIn(true);
    setLoginErr('');
    try {
      await verifyAdminToken(t);
      setStoredAdminToken(t);
      setAuthed(true);
      setTokenInput('');
    } catch (err) {
      setLoginErr(err.message || '登录失败');
    } finally {
      setLoggingIn(false);
    }
  }

  function handleLogout() {
    setStoredAdminToken(null);
    setAuthed(false);
  }

  if (!authed) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-md bg-white rounded-2xl shadow-lg border border-gray-100 p-6 sm:p-8">
          <div className="flex items-center gap-3 mb-6">
            <div className="w-11 h-11 rounded-xl overflow-hidden shadow">
              <img src="/logo.png" alt="" className="w-full h-full object-cover" />
            </div>
            <div>
              <h1 className="text-lg font-bold text-gray-900">萌芽Ping · 管理后台</h1>
              <p className="text-xs text-gray-500">请输入与服务端 ADMIN_TOKEN 一致的口令</p>
            </div>
          </div>
          <form onSubmit={handleLogin} className="space-y-4">
            <label className="block text-xs font-medium text-gray-600">
              管理员令牌
              <input
                type="password"
                autoComplete="off"
                value={tokenInput}
                onChange={(e) => setTokenInput(e.target.value)}
                className="mt-1 w-full px-3 py-2 rounded-lg border border-gray-200 text-sm focus:ring-2 focus:ring-emerald-500 outline-none"
                placeholder="环境变量 ADMIN_TOKEN"
              />
            </label>
            {loginErr ? <p className="text-xs text-red-600">{loginErr}</p> : null}
            <button
              type="submit"
              disabled={loggingIn}
              className="w-full py-2.5 text-sm font-medium text-white bg-emerald-600 rounded-lg hover:bg-emerald-700 disabled:opacity-60"
            >
              {loggingIn ? '验证中…' : '进入管理'}
            </button>
          </form>
          <p className="text-center mt-5">
            <Link to="/" className="text-sm text-emerald-700 hover:underline">
              ← 返回公开页
            </Link>
          </p>
        </div>
      </div>
    );
  }

  return (
    <Dashboard
      readOnly={false}
      topSlot={
        <>
          <AdminScheduleToolbar onLogout={handleLogout} />
          <div className="mt-4">
            <AdminGroupsPanel />
          </div>
        </>
      }
    />
  );
}
