"use client";

import { useEffect, useState, useCallback } from "react";
import { History, Users, ExternalLink, ChevronDown, ChevronRight } from "lucide-react";

interface HistoryRow {
  OBJID: string; TITLE: string; BODY: string | null;
  IMAGE_URL: string | null; URL: string | null;
  REGDATE: string; REGID: string;
  SENT_COUNT: number; FAILED_COUNT: number;
  RECIPIENT_COUNT: number;
  RECIPIENT_USER_IDS: string[];
  GROUP_NAMES: string[];
  RECIPIENT_NAMES: string[];
}

export default function NoticeHistoryPage() {
  const [list, setList] = useState<HistoryRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = await fetch("/api/m/admin/notice-history/list", { method: "POST" });
      setList((await r.json()).RESULTLIST ?? []);
    } finally { setLoading(false); }
  }, []);
  useEffect(() => { load(); }, [load]);

  const toggle = (id: string) => {
    setExpanded((p) => {
      const n = new Set(p);
      if (n.has(id)) n.delete(id); else n.add(id);
      return n;
    });
  };

  return (
    <div className="space-y-3">
      <div>
        <h1 className="text-xl sm:text-2xl font-bold inline-flex items-center gap-2">
          <History size={18} className="text-emerald-700" /> 푸시알림 발송이력
        </h1>
        <p className="text-xs text-slate-500 mt-0.5">보낸 공지의 발송 시각·대상·성공/실패 카운트를 확인. 행을 펼치면 수신자 명단과 그룹·본문을 볼 수 있어요.</p>
      </div>

      <div className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        <div className="px-3 py-2 bg-slate-50 border-b border-slate-200 text-xs font-semibold text-slate-600 flex items-center justify-between">
          <span>총 {list.length}건</span>
          <button onClick={load} disabled={loading}
            className="text-[11px] px-2 py-0.5 rounded border border-slate-300 bg-white hover:bg-slate-100 disabled:opacity-50">
            새로고침
          </button>
        </div>
        <div className="divide-y divide-slate-100 max-h-[calc(100vh-220px)] overflow-y-auto">
          {list.length === 0 ? (
            <div className="text-center py-10 text-slate-400 text-sm">{loading ? "불러오는 중…" : "발송 이력이 없습니다."}</div>
          ) : list.map((n) => {
            const open = expanded.has(n.OBJID);
            return (
              <div key={n.OBJID} className="px-3 py-2">
                <button onClick={() => toggle(n.OBJID)} className="w-full flex items-center gap-3 text-left">
                  <span className="text-slate-400 shrink-0">{open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}</span>
                  {n.IMAGE_URL && (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={n.IMAGE_URL} alt="" className="w-10 h-10 rounded object-cover shrink-0" />
                  )}
                  <div className="min-w-0 flex-1">
                    <div className="text-sm font-bold truncate">{n.TITLE}</div>
                    <div className="text-[11px] text-slate-500 truncate flex items-center gap-1.5">
                      <span>{n.REGDATE}</span>
                      <span className="text-slate-300">·</span>
                      <span>대상 <b className="text-slate-700">{n.RECIPIENT_COUNT < 0 ? "전체" : n.RECIPIENT_COUNT}</b>명</span>
                      <span className="text-slate-300">·</span>
                      <span className="text-emerald-700">성공 {n.SENT_COUNT}</span>
                      {n.FAILED_COUNT > 0 && <><span className="text-slate-300">/</span><span className="text-rose-600">실패 {n.FAILED_COUNT}</span></>}
                      {n.GROUP_NAMES && n.GROUP_NAMES.length > 0 && (
                        <>
                          <span className="text-slate-300">·</span>
                          <span className="text-violet-700 inline-flex items-center gap-0.5"><Users size={11} />{n.GROUP_NAMES.join(", ")}</span>
                        </>
                      )}
                    </div>
                  </div>
                  <a href={`/m/notices/${n.OBJID}`} target="_blank" rel="noreferrer" onClick={(e) => e.stopPropagation()}
                     className="shrink-0 text-slate-400 hover:text-emerald-700 inline-flex items-center gap-0.5 text-[11px]" title="공지 페이지 열기">
                    공지 <ExternalLink size={11} />
                  </a>
                </button>
                {open && (
                  <div className="mt-2 pl-7 space-y-2">
                    {n.BODY && (
                      <div className="bg-slate-50 rounded p-2 text-xs whitespace-pre-wrap leading-relaxed text-slate-700 border border-slate-100">
                        {n.BODY}
                      </div>
                    )}
                    <div>
                      <div className="text-[11px] font-bold text-slate-600 mb-1">수신자 {n.RECIPIENT_NAMES?.length ?? 0}명</div>
                      <div className="flex flex-wrap gap-1">
                        {n.RECIPIENT_COUNT < 0 ? (
                          <span className="text-[11px] px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 font-bold">전체 구독자</span>
                        ) : n.RECIPIENT_NAMES?.length === 0 ? (
                          <span className="text-[11px] text-slate-400">기록 없음 (구버전)</span>
                        ) : (
                          n.RECIPIENT_NAMES.map((nm, i) => (
                            <span key={i} className="text-[11px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-700">
                              {nm || n.RECIPIENT_USER_IDS?.[i]}
                            </span>
                          ))
                        )}
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
