'use client';

import React, { useState, useRef, useCallback } from 'react';
import { FileText, CheckCircle2, Upload, X, Loader2, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import type { Day1CheckItem, TemplateDocument } from '../types';

const ACCEPTED_EXTENSIONS = '.pdf,.xlsx,.xls,.doc,.docx,.hwp';
const ACCEPTED_MIME = [
  'application/pdf',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/vnd.ms-excel',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/haansofthwp',
];
const MAX_FILE_SIZE_MB = 20;

interface Day1DocumentSectionProps {
  checkItem: Day1CheckItem | null;
  onConfirmComplete: () => void;
  isCompleted: boolean;
  isMock?: boolean;
  onFileUpload?: (subItemId: string, file: File) => Promise<boolean>;
  uploadedFiles?: TemplateDocument[];
  onFileDelete?: (fileId: number) => void;
  onFileSelect?: (file: TemplateDocument) => void;
  selectedFileId?: number | null;
}

export function Day1DocumentSection({
  checkItem,
  onConfirmComplete,
  isCompleted,
  isMock,
  onFileUpload,
  uploadedFiles = [],
  onFileDelete,
  onFileSelect,
  selectedFileId,
}: Day1DocumentSectionProps) {
  if (!checkItem) {
    return (
      <div className="bg-white rounded-lg border border-gray-200 h-full flex items-center justify-center">
        <div className="text-center text-gray-400 py-12">
          <FileText className="h-12 w-12 mx-auto mb-3 opacity-50" />
          <p className="text-sm">점검표 항목을 선택하세요</p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg border border-gray-200 overflow-hidden h-full flex flex-col">
      {/* 헤더 */}
      <div className="bg-gray-100 px-2 sm:px-4 py-2 sm:py-3 border-b border-gray-200">
        <div className="flex items-center gap-2">
          <h3 className="font-semibold text-gray-900 text-sm sm:text-base">기준 문서화</h3>
          {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>

      {/* 콘텐츠 */}
      <div className="flex-1 overflow-y-auto p-3 sm:p-4 space-y-3 sm:space-y-4">
        {/* 항목 정보 */}
        <div className="bg-blue-50 rounded-lg p-3 sm:p-4">
          <h4 className="font-medium text-blue-900 mb-1 sm:mb-2 text-sm sm:text-base">{checkItem.title}</h4>
          <p className="text-xs sm:text-sm text-blue-700">{checkItem.description}</p>
        </div>

        {/* 관련 기준 문서 */}
        <div>
          <h5 className="text-xs sm:text-sm font-medium text-gray-700 mb-1.5 sm:mb-2">관련 기준 문서</h5>
          <div className="space-y-1">
            {uploadedFiles.map((file) => (
              <UploadedFileRow
                key={file.id}
                file={file}
                isSelected={selectedFileId === file.id}
                onSelect={onFileSelect ? () => onFileSelect(file) : undefined}
                onDelete={onFileDelete ? () => onFileDelete(file.id) : undefined}
              />
            ))}
          </div>
          <DocumentUploadArea
            onUpload={onFileUpload ? (file) => onFileUpload(checkItem.subItemId, file) : undefined}
          />
        </div>

        {/* 확인 버튼 */}
        <div className="pt-3 sm:pt-4 border-t border-gray-200">
          <Button
            onClick={onConfirmComplete}
            disabled={isCompleted}
            className={cn(
              'w-full',
              isCompleted
                ? 'bg-green-500 hover:bg-green-500 cursor-default'
                : 'bg-blue-600 hover:bg-blue-700'
            )}
          >
            {isCompleted ? (
              <>
                <CheckCircle2 className="h-4 w-4 mr-2" />
                확인 완료
              </>
            ) : (
              <>
                {checkItem.buttonLabel}
              </>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ===== 파일 업로드 영역 =====

interface DocumentUploadAreaProps {
  onUpload?: (file: File) => Promise<boolean>;
}

function DocumentUploadArea({ onUpload }: DocumentUploadAreaProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [pendingFile, setPendingFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const validateFile = useCallback((file: File): string | null => {
    const sizeMB = file.size / (1024 * 1024);
    if (sizeMB > MAX_FILE_SIZE_MB) {
      return `파일 크기는 ${MAX_FILE_SIZE_MB}MB 이하여야 합니다.`;
    }
    // 확장자 체크
    const ext = file.name.split('.').pop()?.toLowerCase();
    const allowed = ['pdf', 'xlsx', 'xls', 'doc', 'docx', 'hwp'];
    if (!ext || !allowed.includes(ext)) {
      return 'PDF, Excel, Word, HWP 파일만 업로드 가능합니다.';
    }
    return null;
  }, []);

  const handleFile = useCallback((file: File) => {
    const error = validateFile(file);
    if (error) {
      toast.error(error);
      return;
    }
    setPendingFile(file);
  }, [validateFile]);

  const handleConfirmUpload = useCallback(async () => {
    if (!pendingFile || !onUpload) return;
    setUploading(true);
    try {
      const success = await onUpload(pendingFile);
      if (success) {
        toast.success(`${pendingFile.name} 업로드 완료`);
        setPendingFile(null);
      }
    } finally {
      setUploading(false);
    }
  }, [pendingFile, onUpload]);

  const handleCancelUpload = useCallback(() => {
    setPendingFile(null);
    if (fileInputRef.current) fileInputRef.current.value = '';
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) handleFile(file);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    const file = e.dataTransfer.files?.[0];
    if (file) handleFile(file);
  };

  // 선택된 파일 미리보기
  if (pendingFile) {
    const ext = pendingFile.name.split('.').pop()?.toLowerCase();
    const sizeMB = (pendingFile.size / (1024 * 1024)).toFixed(1);
    return (
      <div className="mt-2 p-2.5 bg-blue-50 rounded-lg border border-blue-200">
        <div className="flex items-center gap-2">
          <div className={cn(
            'flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center',
            ext === 'pdf' ? 'bg-red-100 text-red-600' : 'bg-green-100 text-green-600'
          )}>
            <FileText className="h-4 w-4" />
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-xs font-medium text-gray-800 truncate">{pendingFile.name}</p>
            <p className="text-[10px] text-gray-500">{sizeMB} MB</p>
          </div>
          <button
            type="button"
            onClick={handleCancelUpload}
            className="p-1 text-gray-400 hover:text-gray-600"
          >
            <X className="h-3.5 w-3.5" />
          </button>
        </div>
        <div className="flex gap-2 mt-2">
          <button
            type="button"
            onClick={handleCancelUpload}
            className="flex-1 py-1.5 text-xs text-gray-600 bg-white border border-gray-200 rounded-md hover:bg-gray-50"
          >
            취소
          </button>
          <button
            type="button"
            onClick={handleConfirmUpload}
            disabled={uploading}
            className="flex-1 py-1.5 text-xs text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50 flex items-center justify-center gap-1"
          >
            {uploading ? (
              <>
                <Loader2 className="h-3 w-3 animate-spin" />
                업로드 중...
              </>
            ) : (
              '업로드'
            )}
          </button>
        </div>
      </div>
    );
  }

  return (
    <>
      <input
        ref={fileInputRef}
        type="file"
        accept={ACCEPTED_EXTENSIONS}
        onChange={handleInputChange}
        className="hidden"
      />
      <div
        onDragEnter={(e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(true); }}
        onDragLeave={(e) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); }}
        onDragOver={(e) => { e.preventDefault(); e.stopPropagation(); }}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
        className={cn(
          'mt-2 flex items-center justify-center gap-1.5 py-2.5 rounded-lg border-2 border-dashed cursor-pointer transition-colors',
          isDragging
            ? 'border-blue-400 bg-blue-50'
            : 'border-gray-200 hover:border-blue-300 hover:bg-gray-50'
        )}
      >
        <Upload className="h-3.5 w-3.5 text-gray-400" />
        <span className="text-xs text-gray-500">
          파일 업로드 (PDF, Excel, Word, HWP)
        </span>
      </div>
    </>
  );
}

// ===== 업로드된 파일 행 =====

interface UploadedFileRowProps {
  file: TemplateDocument;
  isSelected?: boolean;
  onSelect?: () => void;
  onDelete?: () => void;
}

function UploadedFileRow({ file, isSelected, onSelect, onDelete }: UploadedFileRowProps) {
  const ext = file.displayName.split('.').pop()?.toLowerCase();
  const sizeMB = (file.fileSize / (1024 * 1024)).toFixed(1);

  return (
    <div
      className={cn(
        'flex items-center gap-2 p-2 rounded-lg border cursor-pointer transition-colors',
        isSelected
          ? 'bg-blue-50 border-blue-300'
          : 'bg-gray-50 border-gray-200 hover:bg-gray-100'
      )}
      onClick={onSelect}
    >
      <div className={cn(
        'flex-shrink-0 w-7 h-7 rounded flex items-center justify-center',
        ext === 'pdf' ? 'bg-red-100 text-red-600' : 'bg-green-100 text-green-600'
      )}>
        <FileText className="h-3.5 w-3.5" />
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-xs font-medium text-gray-800 truncate">{file.displayName}</p>
        <p className="text-[10px] text-gray-400">{sizeMB} MB</p>
      </div>
      {onDelete && (
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); onDelete(); }}
          className="p-1 text-gray-400 hover:text-red-500 transition-colors"
          title="삭제"
        >
          <Trash2 className="h-3.5 w-3.5" />
        </button>
      )}
    </div>
  );
}