import { type FormEvent, useEffect, useState } from 'react';
import { Button, Card, Title } from 'animal-island-ui';

import type { ConsoleAuthDataSource, ConsoleAuthStatus } from './console-auth.js';
import { createConsoleAuthApiDataSource } from './console-auth.js';

export function ConsoleAuthSettings({
  dataSource,
}: {
  readonly dataSource?: ConsoleAuthDataSource;
}) {
  const [source] = useState(() => dataSource ?? createConsoleAuthApiDataSource());
  const [status, setStatus] = useState<ConsoleAuthStatus>();
  const [enabled, setEnabled] = useState(false);
  const [password, setPassword] = useState('');
  const [confirmation, setConfirmation] = useState('');
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState('');
  const [error, setError] = useState('');

  useEffect(() => {
    let active = true;
    void source.status().then(
      (next) => {
        if (!active) return;
        setStatus(next);
        setEnabled(next.protectionEnabled);
      },
      () => {
        if (active) setError('无法读取密码保护设置。');
      },
    );
    return () => {
      active = false;
    };
  }, [source]);

  const save = async (event: FormEvent) => {
    event.preventDefault();
    if (!status || saving) return;
    setNotice('');
    setError('');
    if (enabled && !status.configured) {
      if (password.length < 8 || !/[A-Za-z]/u.test(password) || !/\d/u.test(password)) {
        setError('密码至少 8 位，并同时包含字母和数字。');
        return;
      }
      if (password !== confirmation) {
        setError('两次输入的密码不一致。');
        return;
      }
    }
    setSaving(true);
    try {
      const input =
        enabled && !status.configured ? { enabled: true, newPassword: password } : { enabled };
      const next = await source.update(input);
      setStatus(next);
      setEnabled(next.protectionEnabled);
      setPassword('');
      setConfirmation('');
      setNotice(next.protectionEnabled ? '密码保护已启用。' : '密码保护已关闭。');
    } catch {
      setError('保存失败，请确认当前登录状态后重试。');
    } finally {
      setSaving(false);
    }
  };

  return (
    <section className="settings-page" aria-labelledby="password-protection-title">
      <header className="page-heading">
        <p className="eyebrow">SYSTEM SETTINGS</p>
        <h1 id="password-protection-title">
          <Title color="app-green">密码保护</Title>
        </h1>
        <p>可在当前管理台直接完成首次密码设置；请在可信网络中初始化并妥善保管密码。</p>
        <p>当前部署为 HTTP，仅适用于可信内网；公网使用必须在前置代理启用 HTTPS。</p>
        <p>参考单实例 SimAdmin 的访问方式，为整个聚合工作台增加统一登录保护。</p>
      </header>
      {error && !status ? <p role="alert">{error}</p> : null}
      {status ? (
        <Card pattern="default" className="settings-card">
          <form className="auth-settings" onSubmit={(event) => void save(event)}>
            <label className="toggle-row">
              <span>
                <strong>启用密码保护</strong>
                <small>启用后，访问实例、短信和设置前都需要先登录。</small>
              </span>
              <input
                type="checkbox"
                checked={enabled}
                onChange={(event) => {
                  setEnabled(event.target.checked);
                  setNotice('');
                }}
              />
            </label>
            {enabled && !status.configured ? (
              <div className="auth-password-fields">
                <label htmlFor="new-console-password">设置访问密码</label>
                <input
                  id="new-console-password"
                  type="password"
                  autoComplete="new-password"
                  value={password}
                  onChange={(event) => setPassword(event.target.value)}
                />
                <label htmlFor="confirm-console-password">确认访问密码</label>
                <input
                  id="confirm-console-password"
                  type="password"
                  autoComplete="new-password"
                  value={confirmation}
                  onChange={(event) => setConfirmation(event.target.value)}
                />
                <small>至少 8 位，同时包含字母和数字。密码仅保存为不可逆哈希。</small>
              </div>
            ) : null}
            {status.configured ? <p>访问密码已配置，不会在页面或 API 中回显。</p> : null}
            {error ? <p role="alert">{error}</p> : null}
            {notice ? <p role="status">{notice}</p> : null}
            <Button htmlType="submit" type="primary" disabled={saving} loading={saving}>
              {saving ? '正在保存…' : '保存密码保护设置'}
            </Button>
            {status.protectionEnabled && status.authenticated ? (
              <Button
                htmlType="button"
                onClick={() => {
                  void source.logout().then(() => window.location.reload());
                }}
              >
                退出登录
              </Button>
            ) : null}
          </form>
        </Card>
      ) : !error ? (
        <p role="status">正在读取设置…</p>
      ) : null}
    </section>
  );
}
