/*
 * SCR-39 업무일지 (worklog). 참조: UIWS worklog/*.
 * 좌: 필터 + 목록 테이블(날짜·제목·유형·진행·공수) / 우: 상세·작성 폼(공수·이슈).
 * 백엔드: /api/work/worklogs (PageResponse). 3상태(로딩/빈/에러) 필수.
 * ★ 갭: worklog 댓글 스레드 엔드포인트 부재 → 07_work_api_gaps.md 기록.
 */
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { worklogApi } from '../../api/endpoints';
import type { WorklogDto, WorklogSaveRequest } from '../../api/types';
import { Button } from '../../components/ui/Button';
import { EmptyState, ErrorState, Skeleton } from '../../components/ui/States';
import { IconPlus } from '../../components/ui/icons';
import { StatusPill, errMessage, fmtDate, useToast } from './workShared';
import './work.css';

const STATUS_OPTS = [
  { v: '', l: '전체' },
  { v: '진행중', l: '진행중' },
  { v: '완료', l: '완료' },
  { v: '보류', l: '보류' },
];
const TYPE_OPTS = ['현장점검', '시공관리', '설계검토', '행정', '회의', '기타'];

const EMPTY_FORM: WorklogSaveRequest = {
  workDate: new Date().toISOString().slice(0, 10),
  title: '',
  workType: '현장점검',
  progress: '',
  status: '진행중',
  content: '',
  hours: 0,
};

export function WorklogPage() {
  const qc = useQueryClient();
  const { show, node: toast } = useToast();
  const [fromDate, setFromDate] = useState('');
  const [toDate, setToDate] = useState('');
  const [status, setStatus] = useState('');
  const [page, setPage] = useState(0);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [form, setForm] = useState<WorklogSaveRequest>(EMPTY_FORM);

  const listQ = useQuery({
    queryKey: ['worklogs', { fromDate, toDate, status, page }],
    queryFn: () =>
      worklogApi.list({
        fromDate: fromDate || undefined,
        toDate: toDate || undefined,
        status: status || undefined,
        page,
        size: 20,
      }),
  });

  const invalidate = () => qc.invalidateQueries({ queryKey: ['worklogs'] });

  const saveM = useMutation({
    mutationFn: (body: WorklogSaveRequest) =>
      selectedId ? worklogApi.update(selectedId, body) : worklogApi.create(body),
    onSuccess: (saved: WorklogDto) => {
      show(selectedId ? '수정되었습니다.' : '등록되었습니다.');
      setSelectedId(saved.id);
      invalidate();
    },
    onError: (e) => show(errMessage(e)),
  });

  const delM = useMutation({
    mutationFn: (id: string) => worklogApi.remove(id),
    onSuccess: () => {
      show('삭제되었습니다.');
      resetForm();
      invalidate();
    },
    onError: (e) => show(errMessage(e)),
  });

  function resetForm() {
    setSelectedId(null);
    setForm(EMPTY_FORM);
  }

  function selectRow(row: WorklogDto) {
    setSelectedId(row.id);
    setForm({
      eventId: row.eventId ?? undefined,
      workDate: row.workDate,
      title: row.title,
      workType: row.workType ?? '',
      progress: row.progress ?? '',
      status: row.status ?? '',
      content: row.content ?? '',
      hours: row.hours,
    });
  }

  const rows = listQ.data?.items ?? [];
  const total = listQ.data?.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / 20));
  const canSave = form.title.trim().length > 0 && !!form.workDate;

  const editingTitle = useMemo(() => (selectedId ? '업무일지 수정' : '새 업무일지'), [selectedId]);

  return (
    <div className="kx-page">
      <header className="kx-work__head">
        <div>
          <h1 className="kx-work__title">업무일지</h1>
          <p className="kx-work__subtitle">현장·시공·설계 일지 기록 · 공수/이슈 관리</p>
        </div>
        <Button leadingIcon={<IconPlus size={16} />} onClick={resetForm}>
          새 일지
        </Button>
      </header>

      <div className="kx-split">
        {/* 목록 */}
        <section className="kx-card" aria-label="업무일지 목록">
          <div className="kx-filterbar">
            <label className="kx-field">
              <span className="kx-label">시작일</span>
              <input
                type="date"
                className="kx-input"
                value={fromDate}
                onChange={(e) => {
                  setFromDate(e.target.value);
                  setPage(0);
                }}
              />
            </label>
            <label className="kx-field">
              <span className="kx-label">종료일</span>
              <input
                type="date"
                className="kx-input"
                value={toDate}
                onChange={(e) => {
                  setToDate(e.target.value);
                  setPage(0);
                }}
              />
            </label>
            <label className="kx-field">
              <span className="kx-label">진행상태</span>
              <select
                className="kx-select"
                value={status}
                onChange={(e) => {
                  setStatus(e.target.value);
                  setPage(0);
                }}
              >
                {STATUS_OPTS.map((o) => (
                  <option key={o.v} value={o.v}>
                    {o.l}
                  </option>
                ))}
              </select>
            </label>
          </div>

          <div className="kx-table-scroll kx-scroll-70">
            <table className="kx-list-table">
              <thead>
                <tr>
                  <th style={{ width: 72 }}>날짜</th>
                  <th>제목</th>
                  <th style={{ width: 92 }}>유형</th>
                  <th style={{ width: 92 }}>진행상태</th>
                  <th style={{ width: 64 }} className="kx-num">
                    공수
                  </th>
                </tr>
              </thead>
              <tbody>
                {listQ.isLoading &&
                  Array.from({ length: 6 }).map((_, i) => (
                    <tr key={i}>
                      <td colSpan={5}>
                        <Skeleton height={20} />
                      </td>
                    </tr>
                  ))}
                {!listQ.isLoading &&
                  rows.map((r) => (
                    <tr
                      key={r.id}
                      className={selectedId === r.id ? 'is-selected' : ''}
                      onClick={() => selectRow(r)}
                    >
                      <td className="kx-num">{fmtDate(r.workDate)}</td>
                      <td>
                        <div className="kx-list-table__title">{r.title}</div>
                        <div className="kx-list-table__muted">{r.writerName}</div>
                      </td>
                      <td className="kx-list-table__muted">{r.workType ?? '-'}</td>
                      <td>
                        <StatusPill value={r.status} />
                      </td>
                      <td className="kx-num">{r.hours ?? 0}h</td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>

          {!listQ.isLoading && listQ.isError && (
            <ErrorState message={errMessage(listQ.error)} onRetry={() => listQ.refetch()} />
          )}
          {!listQ.isLoading && !listQ.isError && rows.length === 0 && (
            <EmptyState
              title="작성된 업무일지가 없습니다"
              description="우측에서 새 일지를 작성하세요."
            />
          )}

          {totalPages > 1 && (
            <div className="kx-pager">
              <button disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))}>
                이전
              </button>
              <span className="tnum">
                {page + 1} / {totalPages}
              </span>
              <button
                disabled={page + 1 >= totalPages}
                onClick={() => setPage((p) => p + 1)}
              >
                다음
              </button>
            </div>
          )}
        </section>

        {/* 상세·작성 */}
        <aside className="kx-detail" aria-label="업무일지 작성">
          <div className="kx-detail__head">
            <h2 className="kx-detail__title">{editingTitle}</h2>
            {selectedId && (
              <Button
                variant="danger"
                onClick={() => {
                  if (window.confirm('이 일지를 삭제할까요?')) delM.mutate(selectedId);
                }}
              >
                삭제
              </Button>
            )}
          </div>

          <div className="kx-formgrid">
            <label className="kx-field">
              <span className="kx-label">작업일 *</span>
              <input
                type="date"
                className="kx-input"
                value={form.workDate}
                onChange={(e) => setForm({ ...form, workDate: e.target.value })}
              />
            </label>
            <label className="kx-field">
              <span className="kx-label">공수(시간)</span>
              <input
                type="number"
                min={0}
                step={0.5}
                className="kx-input"
                value={form.hours ?? 0}
                onChange={(e) => setForm({ ...form, hours: Number(e.target.value) })}
              />
            </label>
            <label className="kx-field kx-field--full">
              <span className="kx-label">제목 *</span>
              <input
                className="kx-input"
                value={form.title}
                maxLength={200}
                placeholder="업무 제목"
                onChange={(e) => setForm({ ...form, title: e.target.value })}
              />
            </label>
            <label className="kx-field">
              <span className="kx-label">유형</span>
              <select
                className="kx-select"
                value={form.workType ?? ''}
                onChange={(e) => setForm({ ...form, workType: e.target.value })}
              >
                {TYPE_OPTS.map((t) => (
                  <option key={t} value={t}>
                    {t}
                  </option>
                ))}
              </select>
            </label>
            <label className="kx-field">
              <span className="kx-label">진행상태</span>
              <select
                className="kx-select"
                value={form.status ?? ''}
                onChange={(e) => setForm({ ...form, status: e.target.value })}
              >
                {STATUS_OPTS.filter((o) => o.v).map((o) => (
                  <option key={o.v} value={o.v}>
                    {o.l}
                  </option>
                ))}
              </select>
            </label>
            <label className="kx-field kx-field--full">
              <span className="kx-label">이슈·내용</span>
              <textarea
                className="kx-textarea"
                value={form.content ?? ''}
                placeholder="진행 내용, 이슈, 특이사항을 기록하세요."
                onChange={(e) => setForm({ ...form, content: e.target.value })}
              />
            </label>
          </div>

          <div className="kx-detail__actions">
            <Button disabled={!canSave || saveM.isPending} onClick={() => saveM.mutate(form)}>
              {saveM.isPending ? '저장 중…' : selectedId ? '수정 저장' : '등록'}
            </Button>
            {selectedId && (
              <Button variant="ghost" onClick={resetForm}>
                취소
              </Button>
            )}
          </div>
        </aside>
      </div>
      {toast}
    </div>
  );
}
