/*
 * W12 시스템관리 — 메일/알림 설정(sys_setting mail./notify. 프리픽스).
 * 정본: GET/PUT /api/admin/mail-config · /api/admin/notify-config (MailConfigController/NotifyConfigController).
 * 보안: secretYn='Y' 값은 마스킹(********)되어 도착 — 마스킹 그대로 저장하면 미변경 처리(원문 보존).
 */
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 {
  CONFIG_MASK, mailConfigApi, notifyConfigApi,
  type InfraConfigRow, type InfraConfigUpdateBody,
} from './systemBasicsApi';
import './admin-modules.css';

type Variant = 'mail' | 'notify';

function InfraConfig({ variant }: { variant: Variant }) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const apiObj = variant === 'mail' ? mailConfigApi : notifyConfigApi;
  const titleKey = variant === 'mail' ? 'mailConfig' : 'notifyConfig';

  const q = useQuery({ queryKey: ['admin-infra', variant], queryFn: apiObj.list, retry: false });
  const [values, setValues] = useState<Record<string, string>>({});

  useEffect(() => {
    if (q.data) {
      const v: Record<string, string> = {};
      for (const r of q.data) v[r.settingKey] = r.settingValue ?? '';
      setValues(v);
    }
  }, [q.data]);

  const saveM = useMutation({
    mutationFn: (body: InfraConfigUpdateBody) => apiObj.save(body),
    onSuccess: () => { show(t(`${titleKey}.saved`)); qc.invalidateQueries({ queryKey: ['admin-infra', variant] }); },
    onError: (e) => show(errMessage(e)),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    const rows = q.data ?? [];
    const items = rows.map((r) => ({ settingKey: r.settingKey, settingValue: values[r.settingKey] ?? '' }));
    saveM.mutate({ items });
  }

  const rows = q.data ?? [];

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

      {q.isLoading && <Skeleton height={320} radius={12} />}
      {q.isError && !q.isLoading && <ErrorState message={t(`${titleKey}.loadError`)} onRetry={() => q.refetch()} />}

      {!q.isLoading && !q.isError && (
        <form className="kx-card kx-adm-form" onSubmit={submit}>
          <div className="kx-adm-config-list">
            {rows.map((r) => (
              <ConfigField key={r.settingKey} row={r} value={values[r.settingKey] ?? ''}
                           onChange={(v) => setValues((s) => ({ ...s, [r.settingKey]: v }))} />
            ))}
          </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>
  );
}

function ConfigField({ row, value, onChange }: {
  row: InfraConfigRow; value: string; onChange: (v: string) => void;
}) {
  const isBool = (row.valueType ?? '').toUpperCase() === 'BOOL';
  const isSecret = row.secretYn === 'Y';
  return (
    <label className="kx-adm-config-field">
      <span className="kx-adm-config-field__key">
        <span className="kx-adm-mono">{row.settingKey}</span>
        {row.description && <span className="kx-adm-config-field__desc">{row.description}</span>}
      </span>
      {isBool ? (
        <select className="kx-adm-field__select" value={value} onChange={(e) => onChange(e.target.value)}>
          <option value="true">ON</option>
          <option value="false">OFF</option>
        </select>
      ) : (
        <input className={`kx-adm-field__input ${isSecret ? '' : 'kx-adm-mono'}`}
               type={isSecret && value !== CONFIG_MASK ? 'password' : 'text'}
               value={value} onChange={(e) => onChange(e.target.value)} />
      )}
    </label>
  );
}

export function MailConfigPage() {
  return <InfraConfig variant="mail" />;
}
export function NotifyConfigPage() {
  return <InfraConfig variant="notify" />;
}
