'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  FaFileAlt,
  FaDownload,
  FaEye,
  FaTrash,
  FaSearch,
  FaFilter,
  FaCalendar,
  FaUser,
  FaFileImage,
  FaFilePdf,
  FaFileWord,
  FaFile
} from 'react-icons/fa';

interface Document {
  id: string;
  name: string;
  type: string;
  size: number;
  uploadedBy: string;
  uploadDate: string;
  category: 'proposal' | 'report' | 'image' | 'contract' | 'other';
  url: string;
}

export default function DocumentManagement() {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [filteredDocuments, setFilteredDocuments] = useState<Document[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterCategory, setFilterCategory] = useState<string>('all');
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Simulate API call
    setTimeout(() => {
      const mockDocuments: Document[] = [
        {
          id: '1',
          name: 'E-Waste Collection Proposal.pdf',
          type: 'application/pdf',
          size: 2048576,
          uploadedBy: 'John Doe',
          uploadDate: '2024-01-15T10:30:00Z',
          category: 'proposal',
          url: '/documents/proposal.pdf'
        },
        {
          id: '2',
          name: 'Monthly Report January.docx',
          type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          size: 1024000,
          uploadedBy: 'Jane Smith',
          uploadDate: '2024-01-20T14:15:00Z',
          category: 'report',
          url: '/documents/report.docx'
        },
        {
          id: '3',
          name: 'Equipment Photo.jpg',
          type: 'image/jpeg',
          size: 512000,
          uploadedBy: 'Mike Johnson',
          uploadDate: '2024-01-18T09:45:00Z',
          category: 'image',
          url: '/documents/photo.jpg'
        },
        {
          id: '4',
          name: 'Service Contract.pdf',
          type: 'application/pdf',
          size: 3072000,
          uploadedBy: 'Sarah Wilson',
          uploadDate: '2024-01-22T16:20:00Z',
          category: 'contract',
          url: '/documents/contract.pdf'
        }
      ];
      setDocuments(mockDocuments);
      setFilteredDocuments(mockDocuments);
      setIsLoading(false);
    }, 1000);
  }, []);

  useEffect(() => {
    let filtered = documents.filter(doc =>
      doc.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      doc.uploadedBy.toLowerCase().includes(searchTerm.toLowerCase())
    );

    if (filterCategory !== 'all') {
      filtered = filtered.filter(doc => doc.category === filterCategory);
    }

    setFilteredDocuments(filtered);
  }, [searchTerm, filterCategory, documents]);

  const formatFileSize = (bytes: number): string => {
    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 getFileIcon = (type: string) => {
    if (type.startsWith('image/')) {
      return <FaFileImage className="text-blue-500" />;
    } else if (type === 'application/pdf') {
      return <FaFilePdf className="text-red-500" />;
    } else if (type.includes('word')) {
      return <FaFileWord className="text-blue-600" />;
    }
    return <FaFile className="text-gray-500" />;
  };

  const handleDownload = (doc: Document) => {
    // Simulate download
    const link = document.createElement('a');
    link.href = doc.url;
    link.download = doc.name;
    link.click();
  };

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this document?')) {
      setDocuments(prev => prev.filter(doc => doc.id !== id));
    }
  };

  const handleView = (doc: Document) => {
    window.open(doc.url, '_blank');
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-green-600"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold text-gray-900">Document Management</h1>
        <div className="text-sm text-gray-500">
          {filteredDocuments.length} of {documents.length} documents
        </div>
      </div>

      {/* Search and Filter */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="relative">
            <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            <input
              type="text"
              placeholder="Search documents by name or uploader..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
            />
          </div>
          
          <div className="relative">
            <FaFilter className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent appearance-none"
            >
              <option value="all">All Categories</option>
              <option value="proposal">Proposals</option>
              <option value="report">Reports</option>
              <option value="image">Images</option>
              <option value="contract">Contracts</option>
              <option value="other">Other</option>
            </select>
          </div>
        </div>
      </div>

      {/* Documents Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <AnimatePresence>
          {filteredDocuments.map((doc) => (
            <motion.div
              key={doc.id}
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow"
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center space-x-3">
                  <div className="text-2xl">
                    {getFileIcon(doc.type)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="text-sm font-medium text-gray-900 truncate" title={doc.name}>
                      {doc.name}
                    </h3>
                    <p className="text-xs text-gray-500">
                      {formatFileSize(doc.size)}
                    </p>
                  </div>
                </div>
                
                <span className={`px-2 py-1 text-xs font-semibold rounded-full ${
                  doc.category === 'proposal' ? 'bg-blue-100 text-blue-800' :
                  doc.category === 'report' ? 'bg-green-100 text-green-800' :
                  doc.category === 'image' ? 'bg-purple-100 text-purple-800' :
                  doc.category === 'contract' ? 'bg-yellow-100 text-yellow-800' :
                  'bg-gray-100 text-gray-800'
                }`}>
                  {doc.category}
                </span>
              </div>
              
              <div className="space-y-2 mb-4">
                <div className="flex items-center space-x-2 text-sm text-gray-600">
                  <FaUser className="text-gray-400" />
                  <span>{doc.uploadedBy}</span>
                </div>
                <div className="flex items-center space-x-2 text-sm text-gray-600">
                  <FaCalendar className="text-gray-400" />
                  <span>{new Date(doc.uploadDate).toLocaleDateString()}</span>
                </div>
              </div>
              
              <div className="flex space-x-2">
                <button
                  onClick={() => handleView(doc)}
                  className="flex-1 bg-blue-50 text-blue-600 hover:bg-blue-100 px-3 py-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center space-x-1"
                >
                  <FaEye />
                  <span>View</span>
                </button>
                <button
                  onClick={() => handleDownload(doc)}
                  className="flex-1 bg-green-50 text-green-600 hover:bg-green-100 px-3 py-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center space-x-1"
                >
                  <FaDownload />
                  <span>Download</span>
                </button>
                <button
                  onClick={() => handleDelete(doc.id)}
                  className="bg-red-50 text-red-600 hover:bg-red-100 px-3 py-2 rounded-lg text-sm font-medium transition-colors"
                >
                  <FaTrash />
                </button>
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>

      {filteredDocuments.length === 0 && (
        <div className="text-center py-12">
          <FaFileAlt className="mx-auto text-4xl text-gray-300 mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No documents found</h3>
          <p className="text-gray-500">
            {searchTerm || filterCategory !== 'all' 
              ? 'Try adjusting your search or filter criteria.' 
              : 'No documents have been uploaded yet.'}
          </p>
        </div>
      )}
    </div>
  );
}