"use client";

import { useState, useEffect, useCallback, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { FileUpload } from "@/components/ui/file-upload";
import Swal from "sweetalert2";

interface FileRow {
  OBJID: string;
  REAL_FILE_NAME: string;
  DOC_TYPE: string;
  DOC_TYPE_NAME: string;
  FILE_SIZE: string;
  REGDATE: string;
  WRITER_NAME: string;
}

// 첨부파일 조회/업로드 팝업 (projectConcept/FileRegistPopup.do 대응)
function FilesPopup() {
  const searchParams = useSearchParams();
  const objId = searchParams.get("targetObjId") || searchParams.get("objId") || "";
  const docType = searchParams.get("docType") || "";
  const docTypeName = searchParams.get("docTypeName") || "첨부파일";

  const [files, setFiles] = useState<FileRow[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchFiles = useCallback(async () => {
    if (!objId) return;
    setLoading(true);
    try {
      const res = await fetch("/api/common/files", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ objId, docType }),
      });
      const data = await res.json();
      if (data.success) {
        const all = (data.files || []) as FileRow[];
        // docType 필터 (서버측이 모두 반환할 수 있으므로 클라 재필터)
        setFiles(docType ? all.filter((f) => f.DOC_TYPE === docType) : all);
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, [objId, docType]);

  useEffect(() => { fetchFiles(); }, [fetchFiles]);

  // opener에 파일 변경 알림 (fn_onFileChange(targetObjId) 또는 fn_search 우선순위)
  const notifyOpener = useCallback(() => {
    if (!window.opener) return;
    try {
      const op = window.opener as Window & {
        fn_onFileChange?: (id: string) => void;
        fn_search?: () => void;
      };
      if (typeof op.fn_onFileChange === "function") op.fn_onFileChange(objId);
      else if (typeof op.fn_search === "function") op.fn_search();
    } catch { /* cross-origin */ }
  }, [objId]);

  const handleDownload = (fileObjId: string, fileName: string) => {
    window.open(`/api/common/files/download?objId=${fileObjId}&fileName=${encodeURIComponent(fileName)}`, "_blank");
  };

  const handleDelete = async (fileObjId: string) => {
    const r = await Swal.fire({
      title: "삭제 확인",
      text: "첨부파일을 삭제하시겠습니까?",
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: "삭제",
      cancelButtonText: "취소",
    });
    if (!r.isConfirmed) return;
    try {
      const res = await fetch("/api/common/files/delete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ objId: fileObjId }),
      });
      const data = await res.json();
      if (data.success) {
        await Swal.fire({ icon: "success", title: "삭제되었습니다.", timer: 1200, showConfirmButton: false });
        fetchFiles();
        notifyOpener();
      } else {
        Swal.fire("오류", data.message || "삭제 실패", "error");
      }
    } catch {
      Swal.fire("오류", "서버 오류가 발생했습니다.", "error");
    }
  };

  const formatSize = (size: string) => {
    const bytes = parseInt(size || "0", 10);
    if (bytes === 0) return "-";
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const handleUploadComplete = () => {
    fetchFiles();
    notifyOpener();
  };

  return (
    <div className="p-5 bg-white min-h-screen">
      <h2 className="text-base font-bold text-gray-800 mb-4 border-b pb-2">{docTypeName}</h2>

      {objId && docType && (
        <div className="flex items-center justify-between mb-3 p-3 bg-gray-50 rounded border border-gray-200">
          <span className="text-xs text-gray-500">대상 ID: {objId} / 유형: {docType}</span>
          <FileUpload
            targetObjId={objId}
            docType={docType}
            docTypeName={docTypeName}
            onUploadComplete={handleUploadComplete}
          />
        </div>
      )}

      {loading ? (
        <div className="text-center text-gray-400 py-8">로딩 중...</div>
      ) : files.length === 0 ? (
        <div className="text-center text-gray-400 py-8">첨부파일이 없습니다.</div>
      ) : (
        <table className="w-full text-sm border-collapse">
          <thead>
            <tr className="border-b bg-gray-50">
              <th className="text-left p-2 font-medium text-gray-600">파일명</th>
              <th className="text-center p-2 font-medium text-gray-600 w-20">크기</th>
              <th className="text-center p-2 font-medium text-gray-600 w-24">등록일</th>
              <th className="text-center p-2 font-medium text-gray-600 w-20">작성자</th>
              <th className="text-center p-2 font-medium text-gray-600 w-16">삭제</th>
            </tr>
          </thead>
          <tbody>
            {files.map((f) => (
              <tr key={f.OBJID} className="border-b hover:bg-gray-50">
                <td className="p-2 text-blue-600 cursor-pointer hover:underline"
                  onClick={() => handleDownload(f.OBJID, f.REAL_FILE_NAME)}>
                  {f.REAL_FILE_NAME}
                </td>
                <td className="p-2 text-center">{formatSize(f.FILE_SIZE)}</td>
                <td className="p-2 text-center">{f.REGDATE || "-"}</td>
                <td className="p-2 text-center">{f.WRITER_NAME || "-"}</td>
                <td className="p-2 text-center">
                  <Button size="sm" variant="secondary" className="text-xs h-7 text-red-500 hover:text-red-700"
                    onClick={() => handleDelete(f.OBJID)}>삭제</Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}

      <div className="flex justify-end gap-2 mt-6 pt-4 border-t">
        <Button variant="secondary" onClick={() => window.close()}>닫기</Button>
      </div>
    </div>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<div className="p-8 text-center text-gray-400">로딩 중...</div>}>
      <FilesPopup />
    </Suspense>
  );
}
