/*
 * W12 시스템관리 — 인증 정책(비밀번호·로그인 잠금·세션).
 * 정본: GET/PUT /api/admin/auth-policy → AuthPolicy (AuthPolicyController). 서버가 범위 클램프.
 * 로그인 잠금 수치는 LoginAttemptService(login.*)와 정합(관리 화면 계약).
 */
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { ErrorState, Skeleton } from '../../components/ui/States';
import { Button } from '../../components/ui/Button';
import { errMessage, useToast } from '../work/workShared';
import { authPolicyApi, type AuthPolicy, type AuthPolicySaveBody } from './systemBasicsApi';
import './admin-modules.css';

export function AuthPolicyPage() {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const q = useQuery({ queryKey: ['admin-auth-policy'], queryFn: authPolicyApi.get, retry: false });
  const [form, setForm] = useState<AuthPolicy | null>(null);

  useEffect(() => {
    if (q.data) setForm(q.data);
  }, [q.data]);

  const saveM = useMutation({
    mutationFn: (body: AuthPolicySaveBody) => authPolicyApi.save(body),
    onSuccess: () => {
      show(t('authPolicy.saved'));
      qc.invalidateQueries({ queryKey: ['admin-auth-policy'] });
    },
    onError: (e) => show(errMessage(e)),
  });

  function num(key: keyof AuthPolicy, v: string) {
    setForm((f) => (f ? { ...f, [key]: Number(v) } : f));
  }
  function yn(key: keyof AuthPolicy, checked: boolean) {
    setForm((f) => (f ? { ...f, [key]: checked ? 'Y' : 'N' } : f));
  }
  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form) return;
    const { updatedAt: _a, updatedBy: _b, ...body } = form;
    saveM.mutate(body);
  }

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('authPolicy.title')}</h1>
          <p className="kx-adm__subtitle">{t('authPolicy.subtitle')}</p>
        </div>
      </header>

      {q.isLoading && <Skeleton height={360} radius={12} />}
      {q.isError && !q.isLoading && <ErrorState message={t('authPolicy.loadError')} onRetry={() => q.refetch()} />}

      {!q.isLoading && !q.isError && form && (
        <form className="kx-card kx-adm-form" onSubmit={submit}>
          <h2 className="kx-adm-form__section">{t('authPolicy.pwSection')}</h2>
          <div className="kx-adm-modal__grid">
            <label className="kx-adm-field">
              <span className="kx-adm-field__label">{t('authPolicy.pwMinLength')}</span>
              <input className="kx-adm-field__input" type="number" min={4} max={64}
                     value={form.pwMinLength} onChange={(e) => num('pwMinLength', e.target.value)} />
            </label>
            <label className="kx-adm-field">
              <span className="kx-adm-field__label">{t('authPolicy.pwExpireDays')}</span>
              <input className="kx-adm-field__input" type="number" min={0} max={3650}
                     value={form.pwExpireDays} onChange={(e) => num('pwExpireDays', e.target.value)} />
            </label>
            <label className="kx-adm-check">
              <input type="checkbox" checked={form.pwRequireUpper === 'Y'}
                     onChange={(e) => yn('pwRequireUpper', e.target.checked)} />
              <span>{t('authPolicy.pwRequireUpper')}</span>
            </label>
            <label className="kx-adm-check">
              <input type="checkbox" checked={form.pwRequireNumber === 'Y'}
                     onChange={(e) => yn('pwRequireNumber', e.target.checked)} />
              <span>{t('authPolicy.pwRequireNumber')}</span>
            </label>
            <label className="kx-adm-check">
              <input type="checkbox" checked={form.pwRequireSpecial === 'Y'}
                     onChange={(e) => yn('pwRequireSpecial', e.target.checked)} />
              <span>{t('authPolicy.pwRequireSpecial')}</span>
            </label>
          </div>

          <h2 className="kx-adm-form__section">{t('authPolicy.lockSection')}</h2>
          <div className="kx-adm-modal__grid">
            <label className="kx-adm-field">
              <span className="kx-adm-field__label">{t('authPolicy.loginMaxFail')}</span>
              <input className="kx-adm-field__input" type="number" min={1} max={20}
                     value={form.loginMaxFail} onChange={(e) => num('loginMaxFail', e.target.value)} />
            </label>
            <label className="kx-adm-field">
              <span className="kx-adm-field__label">{t('authPolicy.lockMinutes')}</span>
              <input className="kx-adm-field__input" type="number" min={1} max={1440}
                     value={form.lockMinutes} onChange={(e) => num('lockMinutes', e.target.value)} />
            </label>
            <label className="kx-adm-field">
              <span className="kx-adm-field__label">{t('authPolicy.sessionTimeoutMin')}</span>
              <input className="kx-adm-field__input" type="number" min={5} max={1440}
                     value={form.sessionTimeoutMin} onChange={(e) => num('sessionTimeoutMin', e.target.value)} />
            </label>
          </div>

          <div className="kx-adm-modal__actions">
            <Button type="submit" disabled={saveM.isPending}>
              {saveM.isPending ? t('sysadmin.saving') : t('sysadmin.save')}
            </Button>
          </div>
        </form>
      )}
      {toast}
    </div>
  );
}
