'use client';

import { useRef, useState } from 'react';
import {
  AttachFileInfo,
  deleteFile,
  downloadFile,
  downloadZip,
  formatFileSize,
  uploadFiles,
} from '@/lib/api/attach';

interface Props {
  atchNo?: string;
  division?: string;
  initialFiles?: AttachFileInfo[];
  onChange?: (atchNo: string, files: AttachFileInfo[]) => void;
  maxFiles?: number;
  readOnly?: boolean;
}

export default function FileUpload({
  atchNo: initialAtchNo,
  division,
  initialFiles = [],
  onChange,
  maxFiles = 10,
  readOnly = false,
}: Props) {
  const [files, setFiles] = useState<AttachFileInfo[]>(initialFiles);
  const [atchNo, setAtchNo] = useState<string | undefined>(initialAtchNo);
  const [uploading, setUploading] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleUpload = async (selected: FileList | null) => {
    if (!selected || selected.length === 0) return;
    if (files.length + selected.length > maxFiles) {
      alert(`최대 ${maxFiles}개까지 업로드할 수 있습니다.`);
      return;
    }

    setUploading(true);
    try {
      const uploaded = await uploadFiles(Array.from(selected), atchNo, division);
      const newAtchNo = uploaded[0]?.atchNo ?? atchNo;
      const newFiles = [...files, ...uploaded];
      setAtchNo(newAtchNo);
      setFiles(newFiles);
      onChange?.(newAtchNo!, newFiles);
    } catch (e: any) {
      alert(e?.response?.data?.message ?? '업로드 중 오류가 발생했습니다.');
    } finally {
      setUploading(false);
      if (inputRef.current) inputRef.current.value = '';
    }
  };

  const handleDelete = async (atchfileNo: string) => {
    if (!confirm('파일을 삭제하시겠습니까?')) return;
    try {
      await deleteFile(atchfileNo);
      const newFiles = files.filter((f) => f.atchfileNo !== atchfileNo);
      setFiles(newFiles);
      onChange?.(atchNo!, newFiles);
    } catch (e: any) {
      alert(e?.response?.data?.message ?? '삭제 중 오류가 발생했습니다.');
    }
  };

  return (
    <div className="space-y-2">
      {/* 드롭존 */}
      {!readOnly && (
        <div
          className={`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors
            ${dragOver ? 'border-blue-400 bg-blue-50' : 'border-gray-300 hover:border-blue-400'}`}
          onClick={() => inputRef.current?.click()}
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => {
            e.preventDefault();
            setDragOver(false);
            handleUpload(e.dataTransfer.files);
          }}
        >
          <input
            ref={inputRef}
            type="file"
            multiple
            className="hidden"
            onChange={(e) => handleUpload(e.target.files)}
          />
          {uploading ? (
            <p className="text-sm text-gray-500">업로드 중...</p>
          ) : (
            <p className="text-sm text-gray-500">
              클릭하거나 파일을 드래그하세요 (최대 {maxFiles}개, 30MB 이하)
            </p>
          )}
        </div>
      )}

      {/* 파일 목록 헤더 */}
      {files.length > 1 && atchNo && (
        <div className="flex justify-end">
          <button
            onClick={() => downloadZip(atchNo)}
            className="text-xs text-blue-600 hover:underline"
          >
            전체 다운로드 (ZIP)
          </button>
        </div>
      )}

      {/* 파일 목록 */}
      {files.length > 0 && (
        <ul className="space-y-1">
          {files.map((f) => (
            <li
              key={f.atchfileNo}
              className="flex items-center justify-between px-3 py-2 bg-gray-50 rounded border text-sm"
            >
              <div className="flex items-center gap-2 overflow-hidden">
                <FileIcon contentType={f.atchTypeNm} />
                <button
                  onClick={() => downloadFile(f.atchfileNo, f.atchFileNm)}
                  className="truncate text-blue-600 hover:underline text-left"
                >
                  {f.atchFileNm}
                </button>
                <span className="text-gray-400 text-xs shrink-0">
                  ({formatFileSize(f.atchFileMg)})
                </span>
              </div>
              {!readOnly && (
                <button
                  onClick={() => handleDelete(f.atchfileNo)}
                  className="ml-2 text-red-400 hover:text-red-600 shrink-0"
                  title="삭제"
                >
                  ✕
                </button>
              )}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function FileIcon({ contentType }: { contentType: string }) {
  const isImage = contentType?.startsWith('image');
  const isPdf = contentType === 'application/pdf';
  return (
    <span className="text-gray-400 shrink-0">
      {isImage ? '🖼' : isPdf ? '📄' : '📎'}
    </span>
  );
}
