import React from 'react';
import { 
  FileText, 
  Eye, 
  Download, 
  Trash2, 
  Calendar, 
  User, 
  Clock,
  CheckCircle,
  AlertCircle,
  PlayCircle
} from 'lucide-react';
import { cn } from '../utils/cn';

interface Document {
  id: string;
  name: string;
  originalName: string;
  status: 'uploaded' | 'processing' | 'completed' | 'error' | 'extracting_text';
  uploadedAt: string;
  processedAt?: string;
  uploadedBy: string;
  fileSize: number;
  pageCount?: number;
  summary?: string;
  error?: string;
  progress?: number;
  message?: string;
}

interface DocumentListProps {
  documents: Document[];
  onViewDocument?: (documentId: string) => void;
  onDownloadDocument?: (documentId: string) => void;
  onDeleteDocument?: (documentId: string) => void;
  onRetryProcessing?: (documentId: string) => void;
  onRefresh?: () => void;
}

const DocumentList: React.FC<DocumentListProps> = ({
  documents,
  onViewDocument,
  onDownloadDocument,
  onDeleteDocument,
  onRetryProcessing,
  onRefresh,
}) => {

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getStatusIcon = (status: Document['status']) => {
    switch (status) {
      case 'uploaded':
        return <CheckCircle className="h-4 w-4 text-success-500" />;
      case 'processing':
        return <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-accent-500" />;
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-success-500" />;
      case 'error':
        return <AlertCircle className="h-4 w-4 text-error-500" />;
      case 'extracting_text':
        return <Clock className="h-4 w-4 text-warning-500" />;
      default:
        return null;
    }
  };

  const getStatusText = (status: Document['status'], progress?: number, message?: string) => {
    switch (status) {
      case 'uploaded':
        return 'Uploaded ✓';
      case 'processing':
        if (progress !== undefined) {
          return `Processing... ${progress}%`;
        }
        return message || 'Processing...';
      case 'completed':
        return 'Completed ✓';
      case 'error':
        return 'Error';
      case 'extracting_text':
        return 'Extracting Text...';
      default:
        return '';
    }
  };

  const getStatusColor = (status: Document['status']) => {
    switch (status) {
      case 'uploaded':
        return 'text-success-600 bg-success-50';
      case 'processing':
        return 'text-accent-600 bg-accent-50';
      case 'completed':
        return 'text-success-600 bg-success-50';
      case 'error':
        return 'text-error-600 bg-error-50';
      case 'extracting_text':
        return 'text-warning-600 bg-warning-50';
      default:
        return 'text-gray-600 bg-gray-50';
    }
  };

  if (documents.length === 0) {
    return (
      <div className="text-center py-12">
        <FileText className="mx-auto h-12 w-12 text-gray-400 mb-4" />
        <h3 className="text-lg font-medium text-primary-800 mb-2">
          No documents uploaded yet
        </h3>
        <p className="text-gray-600">
          Upload your first CIM document to get started with processing.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium text-primary-800">
          Documents ({documents.length})
        </h3>
        {onRefresh && (
          <button
            onClick={onRefresh}
            className="inline-flex items-center px-3 py-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
          >
            <svg className="h-4 w-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Refresh
          </button>
        )}
      </div>

      <div className="bg-white shadow-soft border border-gray-100 overflow-hidden sm:rounded-md">
        <ul className="divide-y divide-gray-200">
          {documents.map((document) => (
            <li key={document.id}>
              <div className="px-4 py-4 sm:px-6">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-3 flex-1 min-w-0">
                    <FileText className="h-8 w-8 text-gray-400 flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2">
                        <p className="text-sm font-medium text-gray-900 truncate">
                          {document.name}
                        </p>
                        <span
                          className={cn(
                            'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium',
                            getStatusColor(document.status)
                          )}
                        >
                          {getStatusIcon(document.status)}
                          <span className="ml-1">{getStatusText(document.status, document.progress, document.message)}</span>
                        </span>
                      </div>
                      
                      <div className="mt-1 flex items-center space-x-4 text-sm text-gray-500">
                        <div className="flex items-center space-x-1">
                          <User className="h-4 w-4" />
                          <span>{document.uploadedBy}</span>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Calendar className="h-4 w-4" />
                          <span>{formatDate(document.uploadedAt)}</span>
                        </div>
                        <span>{formatFileSize(document.fileSize)}</span>
                        {document.pageCount && (
                          <span>{document.pageCount} pages</span>
                        )}
                      </div>

                      {/* Progress bar for processing documents */}
                      {document.status === 'processing' && document.progress !== undefined && (
                        <div className="mt-2">
                          <div className="flex items-center justify-between text-xs text-gray-500 mb-1">
                            <span>Processing progress</span>
                            <span>{document.progress}%</span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div
                              className="bg-accent-500 h-2 rounded-full transition-all duration-300"
                              style={{ width: `${document.progress}%` }}
                            />
                          </div>
                        </div>
                      )}

                      {/* Show a brief status message instead of the full summary */}
                      {document.status === 'completed' && (
                        <p className="mt-2 text-sm text-success-600">
                          ✓ Analysis completed - Click "View" to see detailed CIM review
                        </p>
                      )}

                      {document.error && (
                        <p className="mt-2 text-sm text-red-600">
                          Error: {document.error}
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="flex items-center space-x-2 ml-4">
                    {document.status === 'completed' && (
                      <>
                        <button
                          onClick={() => onViewDocument?.(document.id)}
                          className="inline-flex items-center px-3 py-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                        >
                          <Eye className="h-4 w-4 mr-1" />
                          View
                        </button>
                        <button
                          onClick={() => onDownloadDocument?.(document.id)}
                          className="inline-flex items-center px-3 py-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                        >
                          <Download className="h-4 w-4 mr-1" />
                          Download
                        </button>
                      </>
                    )}

                    {document.status === 'error' && onRetryProcessing && (
                      <button
                        onClick={() => onRetryProcessing(document.id)}
                        className="inline-flex items-center px-3 py-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                      >
                        <PlayCircle className="h-4 w-4 mr-1" />
                        Retry
                      </button>
                    )}

                    <button
                      onClick={() => onDeleteDocument?.(document.id)}
                      className="inline-flex items-center px-3 py-1.5 border border-red-300 shadow-sm text-xs font-medium rounded text-red-700 bg-white hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
                    >
                      <Trash2 className="h-4 w-4 mr-1" />
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default DocumentList; 