import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { Button } from '../../components/ui/Button';
import { ErrorState, Skeleton } from '../../components/ui/States';
import { IconArrowLeft } from '../../components/ui/icons';
import { approvalApi, type ApprovalDetail, type ApprovalSaveRequest } from './approvalApi';
import { ApprovalLineEditor, type ApprovalLineDraft } from './ApprovalLineEditor';
import './approval-form.css';

/*
 * §5B 전자결재(F028) 기안 작성 / 반려건 재상신 패널 — WISE/UIWS ApprovalFormPage 이식.
 * - mode='create'  : 신규 기안(제목·유형·본문·결재선) → 임시저장(DRAFT) 또는 상신(SUBMITTED).
 * - mode='resubmit': 반려(REJECTED) 문서 로드 → 수정(제목/본문/결재선) 후 재상신(version+1).
 *   반려 사유·이전 처리 이력을 상단에 표시(재상신 근거 확인).
 * ★ App.tsx 불변 규칙상 라우트 미추가 — 결재함 페이지의 인-페이지 패널로 동작.
 * ★ 재상신은 문서 로드 후 실제 폼(ComposeForm)을 마운트 → useState 초기값이 로드 데이터로 정확히 세팅.
 */
const DOC_TYPES = ['GENERAL', 'DESIGN', 'DOCUMENT', 'EXPENSE', 'ETC'];

const dt = (v: string | null) => (v ? v.replace('T', ' ').slice(0, 16) : '-');

export function ApprovalComposePanel({
  mode,
  approvalId,
  eventId,
  onDone,
  onCancel,
}: {
  mode: 'create' | 'resubmit';
  approvalId?: string;
  eventId?: string;
  onDone: (id: string, msg: string) => void;
  onCancel: () => void;
}) {
  const detailQ = useQuery({
    queryKey: ['approval', approvalId],
    queryFn: () => approvalApi.get(approvalId as string),
    enabled: mode === 'resubmit' && !!approvalId,
  });

  if (mode === 'resubmit' && approvalId) {
    if (detailQ.isLoading) {
      return (
        <div className="kx-apf">
          <div className="kx-apf__card">
            <Skeleton height={22} width="50%" />
            <Skeleton height={16} />
            <Skeleton height={120} />
          </div>
        </div>
      );
    }
    if (detailQ.isError || !detailQ.data) {
      return (
        <div className="kx-apf">
          <ErrorState onRetry={() => detailQ.refetch()} />
        </div>
      );
    }
    return (
      <ComposeForm
        mode="resubmit"
        source={detailQ.data}
        approvalId={approvalId}
        eventId={eventId}
        onDone={onDone}
        onCancel={onCancel}
      />
    );
  }

  return <ComposeForm mode="create" eventId={eventId} onDone={onDone} onCancel={onCancel} />;
}

function ComposeForm({
  mode,
  source,
  approvalId,
  eventId,
  onDone,
  onCancel,
}: {
  mode: 'create' | 'resubmit';
  source?: ApprovalDetail;
  approvalId?: string;
  eventId?: string;
  onDone: (id: string, msg: string) => void;
  onCancel: () => void;
}) {
  const { t } = useTranslation();

  const [docType, setDocType] = useState(source?.docType ?? 'GENERAL');
  const [title, setTitle] = useState(source?.title ?? '');
  const [content, setContent] = useState(source?.content ?? '');
  const [lines, setLines] = useState<ApprovalLineDraft[]>(
    source?.lines?.length
      ? source.lines.map((l) => ({ approverId: l.approverId, approverName: l.approverName ?? '' }))
      : [{ approverId: '', approverName: '' }],
  );
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  // 반려 사유(가장 최근 REJECT 이력) — 재상신 근거 표시.
  const rejectReason = useMemo(() => {
    if (!source) return null;
    const rej = [...source.history].reverse().find((h) => h.action === 'REJECT');
    return rej?.comment ?? null;
  }, [source]);

  const buildPayload = (): ApprovalSaveRequest => {
    const filled = lines.filter((l) => l.approverId.trim());
    return {
      eventId: eventId || undefined,
      docType,
      title: title.trim(),
      content: content.trim() || undefined,
      lines: filled.map((l, i) => ({
        stepNo: i + 1,
        approverId: l.approverId.trim(),
        approverName: l.approverName.trim() || undefined,
      })),
    };
  };

  const validate = (requireLine: boolean): string | null => {
    if (!title.trim()) return t('approval.err.titleRequired');
    if (requireLine && lines.filter((l) => l.approverId.trim()).length === 0) {
      return t('approval.err.lineRequired');
    }
    return null;
  };

  const run = async (requireLine: boolean, fn: () => Promise<string>, msg: string) => {
    const v = validate(requireLine);
    if (v) return setError(v);
    setError(null);
    setBusy(true);
    try {
      const id = await fn();
      onDone(id, msg);
    } catch (e) {
      setError((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  // 임시저장(DRAFT).
  const saveDraft = () =>
    run(false, async () => (await approvalApi.create(buildPayload())).id, t('approval.createdDraft'));

  // 상신(create → submit).
  const submitDoc = () =>
    run(true, async () => {
      const created = await approvalApi.create(buildPayload());
      await approvalApi.submit(created.id);
      return created.id;
    }, t('approval.submittedDone'));

  // 재상신(REJECTED→SUBMITTED, version+1).
  const doResubmit = () =>
    run(true, async () => {
      await approvalApi.resubmit(approvalId as string, buildPayload());
      return approvalId as string;
    }, t('approval.resubmittedDone'));

  return (
    <div className="kx-apf">
      <header className="kx-apf__head">
        <button className="kx-apf__back" onClick={onCancel} type="button">
          <IconArrowLeft size={16} /> {t('approval.backToList')}
        </button>
        <h1>{mode === 'resubmit' ? t('approval.resubmitTitle') : t('approval.composeTitle')}</h1>
        {mode === 'resubmit' && source ? (
          <span className="kx-apf__ver">
            {t('approval.version')}: v{source.version} → v{source.version + 1}
          </span>
        ) : null}
      </header>

      {error && (
        <div className="kx-apf__error" role="alert">
          {error}
        </div>
      )}

      {/* 반려 사유·이전 이력 — 재상신 근거 */}
      {mode === 'resubmit' && source ? (
        <div className="kx-apf__reject">
          <div className="kx-apf__reject-head">
            <strong>{t('approval.rejectedReason')}</strong>
          </div>
          <p className="kx-apf__reject-body">{rejectReason ?? '-'}</p>
          {source.history.length > 0 ? (
            <ul className="kx-apf__prev">
              {source.history.map((h) => (
                <li key={h.id}>
                  <span className="kx-apf__prev-act">{t(`approval.action.${h.action}`)}</span>
                  <span className="kx-apf__prev-meta">
                    {(h.actorName ?? h.actorId)} · {dt(h.actedAt)}
                  </span>
                  {h.comment ? <span className="kx-apf__prev-cmt">— {h.comment}</span> : null}
                </li>
              ))}
            </ul>
          ) : null}
        </div>
      ) : null}

      <form className="kx-apf__card" onSubmit={(e) => e.preventDefault()}>
        <div className="kx-apf__row">
          <label className="kx-apf__field kx-apf__field--type">
            <span className="kx-apf__label">{t('approval.docType')}</span>
            <select
              className="kx-apf__select"
              value={docType}
              disabled={busy}
              onChange={(e) => setDocType(e.target.value)}
            >
              {DOC_TYPES.map((code) => (
                <option key={code} value={code}>
                  {t(`approval.docTypes.${code}`)}
                </option>
              ))}
            </select>
          </label>
          <label className="kx-apf__field kx-apf__field--title">
            <span className="kx-apf__label">
              {t('approval.titleLabel')} <em className="kx-apf__req">*</em>
            </span>
            <input
              className="kx-apf__input"
              value={title}
              disabled={busy}
              placeholder={t('approval.titlePlaceholder')}
              onChange={(e) => setTitle(e.target.value)}
            />
          </label>
        </div>

        <label className="kx-apf__field">
          <span className="kx-apf__label">{t('approval.contentLabel')}</span>
          <textarea
            className="kx-apf__textarea"
            rows={7}
            value={content}
            disabled={busy}
            placeholder={t('approval.contentPlaceholder')}
            onChange={(e) => setContent(e.target.value)}
          />
        </label>

        <div className="kx-apf__field">
          <span className="kx-apf__label">
            {t('approval.line')} <em className="kx-apf__req">*</em>
          </span>
          <ApprovalLineEditor lines={lines} onChange={setLines} disabled={busy} />
        </div>

        <div className="kx-apf__actions">
          <Button variant="ghost" type="button" disabled={busy} onClick={onCancel}>
            {t('approval.cancel')}
          </Button>
          {mode === 'create' ? (
            <>
              <Button variant="secondary" type="button" disabled={busy} onClick={saveDraft}>
                {t('approval.draftSave')}
              </Button>
              <Button type="button" disabled={busy} onClick={submitDoc}>
                {busy ? t('approval.saving') : t('approval.submitDoc')}
              </Button>
            </>
          ) : (
            <Button type="button" disabled={busy} onClick={doResubmit}>
              {busy ? t('approval.saving') : t('approval.resubmitBtn')}
            </Button>
          )}
        </div>
      </form>
    </div>
  );
}
