/*
 * SCR-45 회의록 (meeting). 참조: UIWS meeting/MeetingDetailPage.
 * 좌: 회의 목록 / 우: 상세(본문·회의록 편집·액션아이템).
 * 백엔드: /api/work/meetings (get·create·minutes·actions·action status).
 * ★ 갭: 녹음 재생·STT 전사·AI 요약·Jasper PDF 엔드포인트 부재 → 해당 UI는 disabled+툴팁. 07_work_api_gaps.md 기록.
 */
import { useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { meetingApi } from '../../api/endpoints';
import type { MeetingSaveRequest } from '../../api/types';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconDownload, IconPlus } from '../../components/ui/icons';
import { StatusPill, errMessage, fmtDateTime, useToast } from './workShared';
import './work.css';

const NOT_SUPPORTED = '백엔드 미지원 — STT/PDF 파이프라인 연동 후 활성화';

export function MeetingPage() {
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [composing, setComposing] = useState(false);
  const [minutesDraft, setMinutesDraft] = useState('');
  const [actionText, setActionText] = useState('');

  const listQ = useQuery({
    queryKey: ['meetings'],
    queryFn: () => meetingApi.list({ page: 0, size: 50 }),
  });
  const detailQ = useQuery({
    queryKey: ['meeting', selectedId],
    queryFn: () => meetingApi.get(selectedId as string),
    enabled: !!selectedId,
  });

  useEffect(() => {
    if (detailQ.data) setMinutesDraft(detailQ.data.meeting.minutes ?? '');
  }, [detailQ.data]);

  const createM = useMutation({
    mutationFn: (b: MeetingSaveRequest) => meetingApi.create(b),
    onSuccess: (m) => {
      show('회의가 등록되었습니다.');
      setComposing(false);
      setSelectedId(m.id);
      qc.invalidateQueries({ queryKey: ['meetings'] });
    },
    onError: (e) => show(errMessage(e)),
  });
  const minutesM = useMutation({
    mutationFn: ({ id, minutes }: { id: string; minutes: string }) =>
      meetingApi.saveMinutes(id, minutes),
    onSuccess: () => {
      show('회의록이 저장되었습니다.');
      qc.invalidateQueries({ queryKey: ['meeting', selectedId] });
    },
    onError: (e) => show(errMessage(e)),
  });
  const actionM = useMutation({
    mutationFn: ({ id, item }: { id: string; item: string }) =>
      meetingApi.addAction(id, { actionItem: item }),
    onSuccess: () => {
      setActionText('');
      qc.invalidateQueries({ queryKey: ['meeting', selectedId] });
    },
    onError: (e) => show(errMessage(e)),
  });
  const actionStatusM = useMutation({
    mutationFn: ({ actionId, value }: { actionId: string; value: string }) =>
      meetingApi.actionStatus(actionId, value),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['meeting', selectedId] }),
    onError: (e) => show(errMessage(e)),
  });

  const rows = listQ.data?.items ?? [];

  return (
    <div className="kx-page">
      <header className="kx-work__head">
        <div>
          <h1 className="kx-work__title">회의록</h1>
          <p className="kx-work__subtitle">사전업무협의(D-30) 회의 기록 · 액션아이템 관리</p>
        </div>
        <Button leadingIcon={<IconPlus size={16} />} onClick={() => setComposing(true)}>
          회의 등록
        </Button>
      </header>

      <div className="kx-meet">
        {/* 목록 */}
        <section className="kx-card" aria-label="회의 목록" style={{ padding: 0 }}>
          <div className="kx-scroll-70">
            {listQ.isLoading &&
              Array.from({ length: 5 }).map((_, i) => (
                <div className="kx-meet__list-item" key={i}>
                  <Skeleton height={16} width="70%" />
                  <Skeleton height={13} width="40%" />
                </div>
              ))}
            {listQ.isError && (
              <ErrorState message={errMessage(listQ.error)} onRetry={() => listQ.refetch()} />
            )}
            {!listQ.isLoading && !listQ.isError && rows.length === 0 && (
              <EmptyState title="등록된 회의가 없습니다" />
            )}
            {rows.map((m) => (
              <div
                key={m.id}
                className={`kx-meet__list-item ${selectedId === m.id ? 'is-selected' : ''}`}
                onClick={() => {
                  setComposing(false);
                  setSelectedId(m.id);
                }}
              >
                <span className="kx-list-table__title">{m.title}</span>
                <span className="kx-detail__meta">
                  {fmtDateTime(m.meetingAt)}
                  {m.location && ` · ${m.location}`}
                </span>
              </div>
            ))}
          </div>
        </section>

        {/* 상세 */}
        <section className="kx-detail" aria-label="회의 상세" style={{ position: 'static' }}>
          {composing ? (
            <MeetingCompose
              saving={createM.isPending}
              onCancel={() => setComposing(false)}
              onSave={(b) => createM.mutate(b)}
            />
          ) : !selectedId ? (
            <EmptyState title="회의를 선택하세요" description="목록에서 회의를 선택하면 상세가 표시됩니다." />
          ) : detailQ.isLoading ? (
            <>
              <Skeleton height={24} width="60%" />
              <Skeleton height={120} />
            </>
          ) : detailQ.isError ? (
            <ErrorState message={errMessage(detailQ.error)} onRetry={() => detailQ.refetch()} />
          ) : detailQ.data ? (
            <>
              <div className="kx-detail__head">
                <h2 className="kx-detail__title">{detailQ.data.meeting.title}</h2>
                <span title={NOT_SUPPORTED} style={{ display: 'inline-flex' }}>
                  <Button variant="secondary" disabled leadingIcon={<IconDownload size={16} />}>
                    회의록 PDF
                  </Button>
                </span>
              </div>
              <div className="kx-detail__meta">
                <span>{detailQ.data.meeting.organizerName}</span>
                <span>· {fmtDateTime(detailQ.data.meeting.meetingAt)}</span>
                {detailQ.data.meeting.location && <span>· {detailQ.data.meeting.location}</span>}
              </div>

              {/* 녹음/STT (미지원) */}
              <div className="kx-meet__player" title={NOT_SUPPORTED}>
                ▶ 녹음 재생 · STT 전사 (준비 중)
              </div>

              {detailQ.data.meeting.content && (
                <div className="kx-field">
                  <span className="kx-label">회의 안건</span>
                  <div className="kx-detail__body">{detailQ.data.meeting.content}</div>
                </div>
              )}

              {/* 회의록 편집 */}
              <div className="kx-field">
                <span className="kx-label">회의록</span>
                <textarea
                  className="kx-textarea"
                  style={{ minHeight: 140 }}
                  value={minutesDraft}
                  onChange={(e) => setMinutesDraft(e.target.value)}
                  placeholder="회의 내용을 기록하세요."
                />
                <div style={{ marginTop: 8 }}>
                  <Button
                    disabled={minutesM.isPending}
                    onClick={() => minutesM.mutate({ id: detailQ.data!.meeting.id, minutes: minutesDraft })}
                  >
                    {minutesM.isPending ? '저장 중…' : '회의록 저장'}
                  </Button>
                </div>
              </div>

              {/* 액션아이템 */}
              <div className="kx-field">
                <span className="kx-label">액션아이템</span>
                <table className="kx-list-table">
                  <thead>
                    <tr>
                      <th style={{ width: 40 }}>#</th>
                      <th>내용</th>
                      <th style={{ width: 96 }}>상태</th>
                    </tr>
                  </thead>
                  <tbody>
                    {detailQ.data.actions.length === 0 && (
                      <tr>
                        <td colSpan={3} className="kx-list-table__muted">
                          등록된 액션아이템이 없습니다.
                        </td>
                      </tr>
                    )}
                    {detailQ.data.actions.map((a) => (
                      <tr key={a.id} style={{ cursor: 'default' }}>
                        <td className="kx-num">{a.seq}</td>
                        <td>{a.actionItem}</td>
                        <td>
                          <button
                            className="kx-pill kx-pill--neutral"
                            style={{ cursor: 'pointer', border: 'none' }}
                            onClick={() =>
                              actionStatusM.mutate({
                                actionId: a.id,
                                value: a.status === 'DONE' ? 'OPEN' : 'DONE',
                              })
                            }
                            title="상태 토글"
                          >
                            <StatusPill value={a.status} />
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                <div className="kx-thread__compose" style={{ marginTop: 8 }}>
                  <input
                    className="kx-input"
                    placeholder="새 액션아이템…"
                    value={actionText}
                    onChange={(e) => setActionText(e.target.value)}
                    onKeyDown={(e) =>
                      e.key === 'Enter' &&
                      actionText.trim() &&
                      actionM.mutate({ id: detailQ.data!.meeting.id, item: actionText })
                    }
                  />
                  <Button
                    disabled={!actionText.trim() || actionM.isPending}
                    onClick={() => actionM.mutate({ id: detailQ.data!.meeting.id, item: actionText })}
                  >
                    추가
                  </Button>
                </div>
              </div>
            </>
          ) : null}
        </section>
      </div>
      {toast}
    </div>
  );
}

function MeetingCompose({
  onCancel,
  onSave,
  saving,
}: {
  onCancel: () => void;
  onSave: (b: MeetingSaveRequest) => void;
  saving: boolean;
}) {
  const now = new Date();
  const [form, setForm] = useState<MeetingSaveRequest>({
    title: '',
    location: '',
    meetingAt: `${now.toISOString().slice(0, 16)}`,
    content: '',
  });
  return (
    <>
      <div className="kx-detail__head">
        <h2 className="kx-detail__title">회의 등록</h2>
      </div>
      <label className="kx-field">
        <span className="kx-label">제목 *</span>
        <input className="kx-input" value={form.title} onChange={(e) => setForm({ ...form, title: e.target.value })} />
      </label>
      <div className="kx-formgrid">
        <label className="kx-field">
          <span className="kx-label">일시 *</span>
          <input
            type="datetime-local"
            className="kx-input"
            value={form.meetingAt}
            onChange={(e) => setForm({ ...form, meetingAt: e.target.value })}
          />
        </label>
        <label className="kx-field">
          <span className="kx-label">장소</span>
          <input
            className="kx-input"
            value={form.location ?? ''}
            onChange={(e) => setForm({ ...form, location: e.target.value })}
          />
        </label>
      </div>
      <label className="kx-field">
        <span className="kx-label">안건</span>
        <textarea
          className="kx-textarea"
          value={form.content ?? ''}
          onChange={(e) => setForm({ ...form, content: e.target.value })}
        />
      </label>
      <div className="kx-detail__actions">
        <Button disabled={!form.title.trim() || saving} onClick={() => onSave(form)}>
          {saving ? '등록 중…' : '등록'}
        </Button>
        <Button variant="ghost" onClick={onCancel}>
          취소
        </Button>
      </div>
    </>
  );
}
