"use client";

import React, { useState, useRef } from 'react';
import {
  FileText, CheckCircle, ChevronDown, ChevronUp,
  Eye, Truck, Calendar, ClipboardCheck, Box, FileCheck,
  Upload, Download, Loader2
} from 'lucide-react';
import { toast } from 'sonner';
import { Document, DocumentItem } from '../types';
import { downloadFileById } from '@/lib/utils/fileDownload';

interface DocumentListProps {
  documents: Document[];
  routeCode: string | null;
  onViewDocument: (doc: Document, item?: DocumentItem) => void;
  onQualityFileUpload?: (qualityDocumentId: string, file: File) => Promise<boolean>;
  isMock?: boolean;
}

const getIcon = (type: string) => {
  switch (type) {
    case 'import': return <CheckCircle className="text-green-600" />;
    case 'order': return <FileText className="text-blue-600" />;
    case 'log': return <Calendar className="text-orange-500" />;
    case 'report': return <ClipboardCheck className="text-blue-500" />;
    case 'confirmation': return <Box className="text-red-500" />;
    case 'shipping': return <Truck className="text-gray-600" />;
    case 'product': return <CheckCircle className="text-green-500" />;
    case 'quality': return <FileCheck className="text-purple-600" />;
    default: return <FileText className="text-blue-600" />;
  }
};

/** 파일 크기를 읽기 쉬운 형식으로 변환 */
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes}B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}

export const DocumentList = ({ documents, routeCode, onViewDocument, onQualityFileUpload, isMock }: DocumentListProps) => {
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [uploadingDocId, setUploadingDocId] = useState<string | null>(null);
  const [downloadingDocId, setDownloadingDocId] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const uploadTargetDocId = useRef<string | null>(null); // doc.id (상태 추적용)
  const uploadApiDocId = useRef<string | null>(null); // 실제 DB ID (API 호출용)

  // 품질관리서 파일 다운로드
  const handleQualityDownload = async (doc: Document) => {
    if (!doc.fileId) return;
    setDownloadingDocId(doc.id);
    try {
      await downloadFileById(doc.fileId, doc.fileName);
    } catch {
      toast.error('파일 다운로드에 실패했습니다.');
    } finally {
      setDownloadingDocId(null);
    }
  };

  // 업로드 버튼 클릭 → hidden input 트리거
  const handleUploadClick = (e: React.MouseEvent, docId: string, apiDocId?: string) => {
    e.stopPropagation();
    uploadTargetDocId.current = docId; // 상태 추적용
    uploadApiDocId.current = apiDocId || docId; // API 호출용 (품질관리서는 items[0].id)
    fileInputRef.current?.click();
  };

  // 파일 선택 후 업로드 실행
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    const trackingId = uploadTargetDocId.current;
    const apiId = uploadApiDocId.current;
    if (!file || !trackingId || !apiId || !onQualityFileUpload) return;

    setUploadingDocId(trackingId);
    try {
      const success = await onQualityFileUpload(apiId, file);
      if (success) {
        toast.success('파일이 업로드되었습니다.');
      }
    } finally {
      setUploadingDocId(null);
      uploadTargetDocId.current = null;
      uploadApiDocId.current = null;
      // input 초기화 (같은 파일 재선택 가능하도록)
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  // 문서 카테고리 클릭 핸들러
  const handleDocClick = (doc: Document) => {
    // 품질관리서: 파일이 있으면 다운로드, 없으면 무시
    if (doc.type === 'quality') {
      if (doc.fileId) {
        handleQualityDownload(doc);
      }
      return;
    }

    const hasItems = doc.items && doc.items.length > 0;
    if (!hasItems) return;

    // 아이템이 1개면 바로 문서 열기
    if (doc.items!.length === 1) {
      onViewDocument(doc, doc.items![0]);
      return;
    }

    // 여러 개면 펼치기/접기
    setExpandedId(expandedId === doc.id ? null : doc.id);
  };

  // 개별 아이템 클릭 핸들러
  const handleItemClick = (doc: Document, item: DocumentItem) => {
    onViewDocument(doc, item);
  };

  // 품질관리서 서브텍스트 렌더링
  const renderQualitySubText = (doc: Document) => {
    if (doc.fileId && doc.fileName) {
      return (
        <span className="flex items-center gap-1">
          <Download size={10} className="text-purple-500" />
          <span className="text-purple-600 truncate max-w-[150px]" title={doc.fileName}>
            {doc.fileName}
          </span>
          {doc.fileSize && (
            <span className="text-gray-400 ml-1">({formatFileSize(doc.fileSize)})</span>
          )}
        </span>
      );
    }
    return <span className="text-gray-400">파일 없음</span>;
  };

  return (
    <div className="bg-white rounded-lg p-3 sm:p-4 shadow-sm h-full flex flex-col overflow-hidden">
      {/* hidden file input for quality document upload */}
      <input
        ref={fileInputRef}
        type="file"
        className="hidden"
        onChange={handleFileChange}
      />

      <div className="flex items-center gap-2 mb-3 sm:mb-4">
        <h2 className="font-bold text-gray-800 text-xs sm:text-sm">
          관련 서류{' '}
          {routeCode && (
            <span className="text-gray-400 font-normal ml-1">({routeCode})</span>
          )}
        </h2>
        {isMock && (
          <span className="bg-amber-100 text-amber-700 text-[9px] sm:text-[10px] font-semibold px-1.5 py-0.5 rounded border border-amber-200">
            Mock
          </span>
        )}
      </div>

      <div className="space-y-2 sm:space-y-3 overflow-y-auto flex-1">
        {!routeCode ? (
          <div className="flex items-center justify-center h-32 text-gray-400 text-sm">
            수주로트를 선택해주세요.
          </div>
        ) : (
          documents.map((doc) => {
            const isExpanded = expandedId === doc.id;
            const isQuality = doc.type === 'quality';
            const hasItems = doc.items && doc.items.length > 0;
            const hasMultipleItems = doc.items && doc.items.length > 1;
            const isUploading = uploadingDocId === doc.id;
            const isDownloading = downloadingDocId === doc.id;

            // 품질관리서: 파일 유무로 클릭 가능 여부 결정
            // 나머지: 아이템 유무로 결정
            const isClickable = isQuality ? !!doc.fileId : hasItems;

            return (
              <div key={doc.id} className="border border-gray-200 rounded-lg overflow-hidden">
                <div
                  onClick={() => handleDocClick(doc)}
                  className={`p-3 sm:p-4 flex justify-between items-center transition-colors ${
                    isClickable ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default opacity-60'
                  } ${isExpanded ? 'bg-green-50' : 'bg-white'}`}
                >
                  <div className="flex items-center gap-3 min-w-0 flex-1">
                    <div className={`p-2 rounded-lg flex-shrink-0 ${isExpanded ? 'bg-white' : 'bg-gray-100'}`}>
                      {(isUploading || isDownloading) ? (
                        <Loader2 className="text-purple-600 animate-spin" size={20} />
                      ) : (
                        getIcon(doc.type)
                      )}
                    </div>
                    <div className="min-w-0 flex-1">
                      <h3 className="font-bold text-gray-800 text-sm">{doc.title}</h3>
                      <p className="text-xs text-gray-500">
                        {isQuality
                          ? renderQualitySubText(doc)
                          : doc.count > 0 ? `${doc.count}건의 서류` : '서류 없음'
                        }
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-1 flex-shrink-0">
                    {/* 품질관리서 업로드 버튼 */}
                    {isQuality && onQualityFileUpload && doc.items?.[0]?.id && (
                      <button
                        type="button"
                        onClick={(e) => handleUploadClick(e, doc.id, doc.items![0].id)}
                        disabled={isUploading}
                        className="p-1.5 rounded-md hover:bg-purple-50 text-purple-500 hover:text-purple-700 transition-colors disabled:opacity-50"
                        title={doc.fileId ? '파일 교체' : '파일 업로드'}
                      >
                        <Upload size={16} />
                      </button>
                    )}
                    {/* 기존: 여러 아이템일 때 펼치기/접기 아이콘 */}
                    {!isQuality && hasMultipleItems && (
                      isExpanded ? (
                        <ChevronUp size={16} className="text-gray-400" />
                      ) : (
                        <ChevronDown size={16} className="text-gray-400" />
                      )
                    )}
                  </div>
                </div>

                {isExpanded && hasMultipleItems && (
                  <div className="bg-white px-3 sm:px-4 pb-3 sm:pb-4 space-y-1.5 sm:space-y-2">
                    <div className="h-px bg-gray-100 w-full mb-2 sm:mb-3" />
                    {doc.items!.map((item) => (
                      <div
                        key={item.id}
                        onClick={() => handleItemClick(doc, item)}
                        className="flex items-center justify-between border border-gray-100 p-2 sm:p-3 rounded cursor-pointer hover:bg-green-50 hover:border-green-200 transition-colors group"
                      >
                        <div>
                          <div className="text-xs font-bold text-gray-700">{item.title}</div>
                          <div className="text-[10px] text-gray-400 mt-1">
                            {item.date}
                            {item.code && (
                              <>
                                <span className="mx-1">|</span>
                                {item.code}
                              </>
                            )}
                          </div>
                        </div>
                        <Eye size={16} className="text-green-600 opacity-0 group-hover:opacity-100 transition-opacity" />
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};
