"use client";

import React, { useState } from 'react';
import {
  FileText, CheckCircle, ChevronDown, ChevronUp,
  Eye, Truck, Calendar, ClipboardCheck, Box, FileCheck
} from 'lucide-react';
import { Document, DocumentItem } from '../types';

interface DocumentListProps {
  documents: Document[];
  routeCode: string | null;
  onViewDocument: (doc: Document, item?: DocumentItem) => void;
}

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" />;
  }
};

export const DocumentList = ({ documents, routeCode, onViewDocument }: DocumentListProps) => {
  const [expandedId, setExpandedId] = useState<string | null>(null);

  // 문서 카테고리 클릭 핸들러
  const handleDocClick = (doc: Document) => {
    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);
  };

  return (
    <div className="bg-white rounded-lg p-4 shadow-sm h-full flex flex-col overflow-hidden">
      <h2 className="font-bold text-gray-800 text-sm mb-4">
        관련 서류{' '}
        {routeCode && (
          <span className="text-gray-400 font-normal ml-1">({routeCode})</span>
        )}
      </h2>

      <div className="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 hasItems = doc.items && doc.items.length > 0;
            const hasMultipleItems = doc.items && doc.items.length > 1;

            return (
              <div key={doc.id} className="border border-gray-200 rounded-lg overflow-hidden">
                <div
                  onClick={() => handleDocClick(doc)}
                  className={`p-4 flex justify-between items-center transition-colors ${
                    hasItems ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default opacity-60'
                  } ${isExpanded ? 'bg-green-50' : 'bg-white'}`}
                >
                  <div className="flex items-center gap-3">
                    <div className={`p-2 rounded-lg ${isExpanded ? 'bg-white' : 'bg-gray-100'}`}>
                      {getIcon(doc.type)}
                    </div>
                    <div>
                      <h3 className="font-bold text-gray-800 text-sm">{doc.title}</h3>
                      <p className="text-xs text-gray-500">
                        {doc.count > 0 ? `${doc.count}건의 서류` : '서류 없음'}
                      </p>
                    </div>
                  </div>
                  {hasMultipleItems && (
                    isExpanded ? (
                      <ChevronUp size={16} className="text-gray-400" />
                    ) : (
                      <ChevronDown size={16} className="text-gray-400" />
                    )
                  )}
                </div>

                {isExpanded && hasMultipleItems && (
                  <div className="bg-white px-4 pb-4 space-y-2">
                    <div className="h-px bg-gray-100 w-full 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-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>
  );
};