/*
 * W12 시스템관리 — 회사(거래처) 관리.
 * 정본: GET/POST /api/admin/companies · DELETE /{id} (CompanyController). 목록 PageResponse, 연락처 마스킹.
 * 보안: 목록의 contactTel 은 마스킹되어 도착. 수정 시 마스킹된 값을 다시 전송하면 마스킹이 저장되므로
 *   전화 필드는 편집 시 공란 시작(미입력=미변경 아님 → 명시적으로 다시 입력) — 화면 안내.
 */
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { Button } from '../../components/ui/Button';
import { IconPlus, IconSearch } from '../../components/ui/icons';
import { errMessage, useToast } from '../work/workShared';
import { companyApi, PARTNER_TYPES, type Company, type CompanySaveBody } from './systemBasicsApi';
import { Pager } from './LoginHistoryPage';
import './admin-modules.css';

export function CompanyAdminPage() {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [keyword, setKeyword] = useState('');
  const [partnerType, setPartnerType] = useState('');
  const [applied, setApplied] = useState<{ keyword: string; partnerType: string }>({ keyword: '', partnerType: '' });
  const [page, setPage] = useState(0);
  const size = 20;
  const [editing, setEditing] = useState<Company | null | undefined>(undefined);

  const q = useQuery({
    queryKey: ['admin-companies', applied, page],
    queryFn: () => companyApi.list({ ...applied, page, size }),
    retry: false,
  });
  const rows = q.data?.items ?? [];
  const total = q.data?.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / size));

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

  function apply() { setPage(0); setApplied({ keyword, partnerType }); }

  return (
    <div className="kx-page kx-adm">
      <header className="kx-adm__head">
        <div>
          <h1 className="kx-adm__title">{t('company.title')}</h1>
          <p className="kx-adm__subtitle">{t('company.subtitle')}</p>
        </div>
        <Button leadingIcon={<IconPlus size={16} />} onClick={() => setEditing(null)}>{t('company.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('company.searchPh')} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.partnerType')}</span>
            <select className="kx-adm-field__select" value={partnerType} onChange={(e) => setPartnerType(e.target.value)}>
              <option value="">{t('company.allTypes')}</option>
              {PARTNER_TYPES.map((x) => <option key={x} value={x}>{t(`company.pt_${x}`)}</option>)}
            </select>
          </label>
          <div className="kx-adm-filter__actions">
            <Button leadingIcon={<IconSearch size={16} />} onClick={apply}>{t('sysadmin.search')}</Button>
          </div>
        </div>
      </section>

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

      {!q.isLoading && !q.isError && (
        <section className="kx-card kx-adm-table-card">
          {rows.length === 0 ? (
            <EmptyState title={t('company.emptyTitle')} description={t('company.emptyDesc')} />
          ) : (
            <>
              <div className="kx-table-scroll">
                <table className="kx-table kx-table--zebra">
                  <thead>
                    <tr>
                      <th>{t('company.colName')}</th>
                      <th>{t('company.colBizNo')}</th>
                      <th>{t('company.colType')}</th>
                      <th>{t('company.colContact')}</th>
                      <th>{t('company.colTel')}</th>
                      <th>{t('company.colUse')}</th>
                      <th aria-label={t('sysadmin.actions')} />
                    </tr>
                  </thead>
                  <tbody>
                    {rows.map((r) => (
                      <tr key={r.id}>
                        <td>{r.companyName}</td>
                        <td className="kx-adm-mono">{r.bizNo ?? '-'}</td>
                        <td>{r.partnerType ? t(`company.pt_${r.partnerType}`) : '-'}</td>
                        <td>{r.contactName ?? '-'}</td>
                        <td className="kx-adm-mono">{r.contactTel ?? '-'}</td>
                        <td>{r.useYn === 'N' ? t('sysadmin.noUse') : t('sysadmin.use')}</td>
                        <td 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('company.deleteConfirm', { name: r.companyName }))) delM.mutate(r.id); }}>
                            {t('sysadmin.delete')}
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pager page={page} totalPages={totalPages} total={total} onPrev={() => setPage((p) => Math.max(0, p - 1))}
                     onNext={() => setPage((p) => Math.min(totalPages - 1, p + 1))} />
            </>
          )}
        </section>
      )}

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

function CompanyModal({ company, saving, onClose, onSubmit }: {
  company: Company | null; saving: boolean; onClose: () => void; onSubmit: (b: CompanySaveBody) => void;
}) {
  const { t } = useTranslation();
  const isNew = company === null;
  const [companyName, setName] = useState(company?.companyName ?? '');
  const [bizNo, setBizNo] = useState(company?.bizNo ?? '');
  const [ceoName, setCeo] = useState(company?.ceoName ?? '');
  const [bizType, setBizType] = useState(company?.bizType ?? '');
  const [contactName, setContact] = useState(company?.contactName ?? '');
  const [contactTel, setTel] = useState(''); // 마스킹 방지: 편집 시 공란 시작
  const [address, setAddress] = useState(company?.address ?? '');
  const [partnerType, setPartner] = useState(company?.partnerType ?? '');
  const [useYn, setUseYn] = useState(company?.useYn ?? 'Y');
  const [error, setError] = useState<string | null>(null);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!companyName.trim()) { setError(t('company.errRequired')); return; }
    onSubmit({
      id: company?.id ?? null,
      companyName: companyName.trim(),
      bizNo: bizNo.trim() || null,
      ceoName: ceoName.trim() || null,
      bizType: bizType.trim() || null,
      contactName: contactName.trim() || null,
      contactTel: contactTel.trim() || null,
      address: address.trim() || null,
      partnerType: partnerType || 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('company.add') : t('company.edit')}</h2>
        <div className="kx-adm-modal__grid">
          <label className="kx-adm-field kx-adm-field--full">
            <span className="kx-adm-field__label">{t('company.colName')}</span>
            <input className="kx-adm-field__input" value={companyName} onChange={(e) => setName(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.colBizNo')}</span>
            <input className="kx-adm-field__input kx-adm-mono" value={bizNo} onChange={(e) => setBizNo(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.ceo')}</span>
            <input className="kx-adm-field__input" value={ceoName} onChange={(e) => setCeo(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.partnerType')}</span>
            <select className="kx-adm-field__select" value={partnerType} onChange={(e) => setPartner(e.target.value)}>
              <option value="">-</option>
              {PARTNER_TYPES.map((x) => <option key={x} value={x}>{t(`company.pt_${x}`)}</option>)}
            </select>
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.bizType')}</span>
            <input className="kx-adm-field__input" value={bizType} onChange={(e) => setBizType(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.contact')}</span>
            <input className="kx-adm-field__input" value={contactName} onChange={(e) => setContact(e.target.value)} />
          </label>
          <label className="kx-adm-field">
            <span className="kx-adm-field__label">{t('company.tel')}</span>
            <input className="kx-adm-field__input kx-adm-mono" value={contactTel} onChange={(e) => setTel(e.target.value)}
                   placeholder={isNew ? '' : t('company.telEditHint')} />
          </label>
          <label className="kx-adm-field kx-adm-field--full">
            <span className="kx-adm-field__label">{t('company.address')}</span>
            <input className="kx-adm-field__input" value={address} onChange={(e) => setAddress(e.target.value)} />
          </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>
        {!isNew && <p className="kx-adm-modal__desc">{t('company.telMaskNote')}</p>}
        {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>
  );
}
