/*
 * W12 시스템관리 — 프로그램(화면) 등록부.
 * 정본: GET/POST /api/admin/programs · DELETE /{id} (ProgramController). 라우트/화면 마스터(메뉴와 연결).
 */
import { useMemo, 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 { KxDataTable, type KxColumn } from '../../components/KxDataTable';
import { IconPlus, IconSearch } from '../../components/ui/icons';
import { errMessage, useToast } from '../work/workShared';
import { programApi, PROGRAM_TYPES, type Program, type ProgramSaveBody } from './systemBasicsApi';
import './admin-modules.css';

export function ProgramAdminPage() {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [keyword, setKeyword] = useState('');
  const [applied, setApplied] = useState('');
  const [editing, setEditing] = useState<Program | null | undefined>(undefined);

  const q = useQuery({
    queryKey: ['admin-programs', applied],
    queryFn: () => programApi.list(applied || undefined),
    retry: false,
  });
  const rows = q.data ?? [];

  const saveM = useMutation({
    mutationFn: (body: ProgramSaveBody) => programApi.save(body),
    onSuccess: () => { show(t('program.saved')); setEditing(undefined); qc.invalidateQueries({ queryKey: ['admin-programs'] }); },
    onError: (e) => show(errMessage(e)),
  });
  const delM = useMutation({
    mutationFn: (id: string) => programApi.remove(id),
    onSuccess: () => { show(t('program.deleted')); qc.invalidateQueries({ queryKey: ['admin-programs'] }); },
    onError: (e) => show(errMessage(e)),
  });

  const columns = useMemo<KxColumn<Program>[]>(
    () => [
      { key: 'name', header: t('program.colName'), value: (r) => r.programName },
      { key: 'type', header: t('program.colType'), value: (r) => r.programType,
        render: (r) => <span className="kx-adm-pill kx-adm-pill--neutral">{r.programType}</span> },
      { key: 'url', header: t('program.colUrl'), value: (r) => r.programUrl ?? '',
        render: (r) => <span className="kx-adm-mono">{r.programUrl ?? '-'}</span> },
      { key: 'category', header: t('program.colCategory'), value: (r) => r.category ?? '', render: (r) => r.category ?? '-' },
      { key: 'use', header: t('program.colUse'), value: (r) => (r.useYn === 'N' ? t('sysadmin.noUse') : t('sysadmin.use')),
        render: (r) => (r.useYn === 'N' ? t('sysadmin.noUse') : t('sysadmin.use')) },
      { key: 'manage', header: t('sysadmin.actions'), csv: false, sortable: false, searchable: false,
        thClassName: 'kx-adm-col-manage', tdClassName: 'kx-adm-col-manage',
        render: (r) => (
          <div className="kx-adm-tbl__actions">
            <Button variant="ghost" onClick={() => setEditing(r)}>{t('sysadmin.edit')}</Button>
            <Button variant="ghost" className="kx-adm-del" disabled={delM.isPending}
                    onClick={() => { if (window.confirm(t('program.deleteConfirm', { name: r.programName }))) delM.mutate(r.id); }}>
              {t('sysadmin.delete')}
            </Button>
          </div>
        ) },
    ],
    [t, delM],
  );

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('program.title')}</h1>
          <p className="kx-adm__subtitle">{t('program.subtitle')}</p>
        </div>
        <Button leadingIcon={<IconPlus size={16} />} onClick={() => setEditing(null)}>{t('program.add')}</Button>
      </header>

      <section className="kx-card kx-adm-filter">
        <div className="kx-adm-filter__grid">
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('sysadmin.keyword')}</span>
            <input className="kx-adm-field__input" value={keyword} onChange={(e) => setKeyword(e.target.value)}
                   placeholder={t('program.searchPh')} />
          </label>
          <div className="kx-adm-filter__actions">
            <Button leadingIcon={<IconSearch size={16} />} onClick={() => setApplied(keyword)}>{t('sysadmin.search')}</Button>
          </div>
        </div>
      </section>

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

      {!q.isLoading && !q.isError && (
        <section className="kx-card kx-adm-table-card">
          <KxDataTable
            columns={columns}
            rows={rows}
            rowKey={(r) => r.id}
            searchable={false}
            csvFileName="programs"
            ariaLabel={t('program.title')}
            emptyTitle={t('program.emptyTitle')}
            emptyDescription={t('program.emptyDesc')}
          />
        </section>
      )}

      {editing !== undefined && (
        <ProgramModal program={editing} saving={saveM.isPending}
                      onClose={() => setEditing(undefined)} onSubmit={(b) => saveM.mutate(b)} />
      )}
      {toast}
    </div>
  );
}

function ProgramModal({ program, saving, onClose, onSubmit }: {
  program: Program | null; saving: boolean; onClose: () => void; onSubmit: (b: ProgramSaveBody) => void;
}) {
  const { t } = useTranslation();
  const isNew = program === null;
  const [programName, setName] = useState(program?.programName ?? '');
  const [programType, setType] = useState(program?.programType ?? 'SCREEN');
  const [programUrl, setUrl] = useState(program?.programUrl ?? '');
  const [category, setCategory] = useState(program?.category ?? '');
  const [useYn, setUseYn] = useState(program?.useYn ?? 'Y');
  const [error, setError] = useState<string | null>(null);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!programName.trim()) { setError(t('program.errRequired')); return; }
    onSubmit({
      id: program?.id ?? null,
      programName: programName.trim(),
      programType,
      programUrl: programUrl.trim() || null,
      category: category.trim() || null,
      useYn,
    });
  }

  return (
    <div className="kx-adm-modal" role="dialog" aria-modal="true">
      <div className="kx-adm-modal__backdrop" onClick={onClose} />
      <form className="kx-adm-modal__panel" onSubmit={submit}>
        <h2 className="kx-adm-modal__title">{isNew ? t('program.add') : t('program.edit')}</h2>
        <div className="kx-adm-modal__grid">
          <label className="kx-adm-field kx-adm-field--full">
            <span className="kx-adm-field__label">{t('program.colName')}</span>
            <input className="kx-adm-field__input" value={programName} onChange={(e) => setName(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('program.colType')}</span>
            <select className="kx-adm-field__select" value={programType} onChange={(e) => setType(e.target.value)}>
              {PROGRAM_TYPES.map((x) => <option key={x} value={x}>{x}</option>)}
            </select>
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('program.colCategory')}</span>
            <input className="kx-adm-field__input" value={category} onChange={(e) => setCategory(e.target.value)} />
          </label>
          <label className="kx-adm-field kx-adm-field--full">
            <span className="kx-adm-field__label">{t('program.colUrl')}</span>
            <input className="kx-adm-field__input kx-adm-mono" value={programUrl} onChange={(e) => setUrl(e.target.value)}
                   placeholder="/admin/users" />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('sysadmin.useYn')}</span>
            <select className="kx-adm-field__select" value={useYn} onChange={(e) => setUseYn(e.target.value)}>
              <option value="Y">{t('sysadmin.use')}</option>
              <option value="N">{t('sysadmin.noUse')}</option>
            </select>
          </label>
        </div>
        {error && <p className="kx-adm-modal__error" role="alert">{error}</p>}
        <div className="kx-adm-modal__actions">
          <Button variant="ghost" type="button" onClick={onClose}>{t('sysadmin.cancel')}</Button>
          <Button type="submit" disabled={saving}>{saving ? t('sysadmin.saving') : t('sysadmin.save')}</Button>
        </div>
      </form>
    </div>
  );
}
