import React, { useState, useRef } from 'react';
import { 
  FileText, 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal, 
  Folder, 
  File, 
  Download, 
  Share2, 
  Trash2, 
  Upload, 
  HardDrive,
  Clock,
  Star,
  ChevronRight,
  FileCode,
  FileImage,
  FileArchive,
  X,
  AlertCircle,
  FolderInput
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useApp, Document, Folder as FolderType } from '@/context/AppContext';
import { useAuth } from '@/context/AuthContext';
import { motion, AnimatePresence } from 'framer-motion';

export function Documents() {
  const { documents, addDocument, updateDocument, deleteDocument, folders, addFolder, deleteFolder } = useApp();
  const { profile } = useAuth();
  const [searchQuery, setSearchQuery] = useState('');
  const [activeTab, setActiveTab] = useState<'all' | 'recent' | 'starred'>('all');
  const [selectedFolder, setSelectedFolder] = useState<string | null>(null);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [isNewFolderModalOpen, setIsNewFolderModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isMoveModalOpen, setIsMoveModalOpen] = useState(false);
  const [docToMove, setDocToMove] = useState<Document | null>(null);
  const [docToDelete, setDocToDelete] = useState<Document | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [newDoc, setNewDoc] = useState<Partial<Document>>({
    name: '',
    type: 'PDF',
    size: '0 KB',
  });

  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleCreateFolder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newFolderName.trim()) {
      toast.error('Please enter a folder name');
      return;
    }

    if (isSubmitting) return;

    setIsSubmitting(true);
    try {
      const colors = ['text-blue-500', 'text-purple-500', 'text-green-500', 'text-red-500', 'text-orange-500', 'text-indigo-500'];
      const randomColor = colors[Math.floor(Math.random() * colors.length)];

      const id = `FLD-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
      const newFolder: FolderType = {
        id,
        name: newFolderName.trim(),
        color: randomColor
      };

      await addFolder(newFolder);
      toast.success(`Folder "${newFolderName}" created`);
      setIsNewFolderModalOpen(false);
      setNewFolderName('');
    } catch (error) {
      console.error('Create folder error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const filteredDocuments = documents.filter(doc => {
    const matchesSearch = doc.name.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesFolder = selectedFolder ? doc.folder === selectedFolder : true;
    
    if (!matchesFolder) return false;
    
    if (activeTab === 'starred') return matchesSearch && doc.isStarred;
    if (activeTab === 'recent') {
      // For demo, assume recent is anything from today
      const today = new Date().toISOString().split('T')[0];
      return matchesSearch && doc.lastModified.startsWith(today);
    }
    return matchesSearch;
  });

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      
      // Determine type from extension
      const ext = file.name.split('.').pop()?.toUpperCase();
      let type: Document['type'] = 'PDF';
      if (['JPG', 'JPEG', 'PNG', 'GIF'].includes(ext || '')) type = 'IMG';
      else if (['DOC', 'DOCX'].includes(ext || '')) type = 'DOCX';
      else if (['XLS', 'XLSX'].includes(ext || '')) type = 'XLSX';
      else if (['PPT', 'PPTX'].includes(ext || '')) type = 'PPTX';
      else if (['ZIP', 'RAR', '7Z'].includes(ext || '')) type = 'ZIP';
      else if (['JS', 'TS', 'PY', 'HTML', 'CSS', 'TSX'].includes(ext || '')) type = 'CODE';

      setNewDoc({
        ...newDoc,
        name: file.name.split('.')[0],
        type,
        size: `${(file.size / 1024).toFixed(1)} KB`
      });
    }
  };

  const handleUpload = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newDoc.name) {
      toast.error('Please enter a document name');
      return;
    }

    if (isSubmitting) return;

    setIsSubmitting(true);
    try {
      const id = `DOC-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
      const document: Document = {
        id,
        name: newDoc.name,
        type: newDoc.type as any,
        size: newDoc.size || '0 KB',
        lastModified: new Date().toISOString(),
        owner: profile?.name || 'Unknown User',
        isStarred: false,
        folder: selectedFolder || undefined
      };

      await addDocument(document);
      toast.success('Document uploaded successfully');
      setIsUploadModalOpen(false);
      setNewDoc({ name: '', type: 'PDF' });
      setSelectedFile(null);
    } catch (error) {
      console.error('Upload document error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = (doc: Document) => {
    setDocToDelete(doc);
    setIsDeleteModalOpen(true);
  };

  const confirmDelete = async () => {
    if (docToDelete && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await deleteDocument(docToDelete.id);
        toast.success('Document deleted');
        setIsDeleteModalOpen(false);
        setDocToDelete(null);
      } catch (error) {
        console.error('Delete document error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleMove = (doc: Document) => {
    setDocToMove(doc);
    setIsMoveModalOpen(true);
  };

  const confirmMove = async (folderName: string | null) => {
    if (docToMove && !isSubmitting) {
      setIsSubmitting(true);
      try {
        await updateDocument(docToMove.id, { folder: folderName || undefined });
        toast.success(`Moved to ${folderName || 'Root'}`);
        setIsMoveModalOpen(false);
        setDocToMove(null);
      } catch (error) {
        console.error('Move document error:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleDownload = (doc: Document) => {
    // In a real app, this would fetch the file from a server/storage
    // For this demo, we'll generate a metadata file to simulate the download
    const content = `
Document Details
---------------
ID: ${doc.id}
Name: ${doc.name}
Type: ${doc.type}
Size: ${doc.size}
Owner: ${doc.owner}
Last Modified: ${new Date(doc.lastModified).toLocaleString()}
Folder: ${doc.folder || 'Root'}

This is a simulated download of the document metadata.
    `.trim();

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = window.document.createElement('a');
    a.href = url;
    a.download = `${doc.name.replace(/\s+/g, '_')}_info.txt`;
    window.document.body.appendChild(a);
    a.click();
    window.document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast.success(`Downloading ${doc.name}...`);
  };

  const handleExportAll = () => {
    const headers = ['ID', 'Name', 'Type', 'Size', 'Last Modified', 'Owner', 'Folder'];
    const rows = documents.map(doc => [
      doc.id,
      doc.name,
      doc.type,
      doc.size,
      doc.lastModified,
      doc.owner,
      doc.folder || 'Root'
    ]);
    
    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell}"`).join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = window.document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `documents_export_${new Date().toISOString().split('T')[0]}.csv`);
    window.document.body.appendChild(link);
    link.click();
    window.document.body.removeChild(link);
    URL.revokeObjectURL(url);
    toast.success('Documents list exported as CSV');
  };

  const toggleStar = async (doc: Document) => {
    try {
      await updateDocument(doc.id, { isStarred: !doc.isStarred });
      toast.success(doc.isStarred ? 'Removed from starred' : 'Added to starred');
    } catch (error) {
       console.error('Toggle star error:', error);
    }
  };

  const getFileIcon = (type: Document['type']) => {
    switch (type) {
      case 'PDF': return <FileText className="text-red-500" size={20} />;
      case 'DOCX': return <FileText className="text-blue-500" size={20} />;
      case 'XLSX': return <FileText className="text-green-500" size={20} />;
      case 'IMG': return <FileImage className="text-purple-500" size={20} />;
      case 'ZIP': return <FileArchive className="text-orange-500" size={20} />;
      case 'CODE': return <FileCode className="text-gray-500" size={20} />;
      default: return <File className="text-muted-foreground" size={20} />;
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Document Management</h1>
          <p className="text-muted-foreground">Securely store, organize, and share company documents.</p>
        </div>
        <div className="flex items-center gap-2">
          <button 
            onClick={handleExportAll}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Download size={18} />
            Export List
          </button>
          <button 
            onClick={() => setIsNewFolderModalOpen(true)}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-medium hover:bg-accent transition-colors"
          >
            <Plus size={18} />
            New Folder
          </button>
          <button 
            onClick={() => setIsUploadModalOpen(true)}
            className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
          >
            <Upload size={18} />
            Upload File
          </button>
        </div>
      </div>

      {/* Storage Stats */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <DocumentStatCard 
          title="Total Storage" 
          value="1.2 TB" 
          icon={HardDrive} 
          description="65% of 2 TB used"
          progress={65}
        />
        <DocumentStatCard 
          title="Total Files" 
          value={documents.length.toString()} 
          icon={File} 
          description="Across all departments"
        />
        <DocumentStatCard 
          title="Starred" 
          value={documents.filter(d => d.isStarred).length.toString()} 
          icon={Star} 
          description="Quick access items"
          color="text-yellow-500"
        />
        <DocumentStatCard 
          title="Recent Uploads" 
          value={documents.filter(d => d.lastModified.startsWith(new Date().toISOString().split('T')[0])).length.toString()} 
          icon={Clock} 
          description="In the last 24 hours"
          color="text-blue-500"
        />
      </div>

      {/* Folders Grid */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {folders.map((folder) => {
          const folderFileCount = documents.filter(d => d.folder === folder.name).length;
          const isActive = selectedFolder === folder.name;
          
          return (
            <div 
              key={folder.id} 
              className={cn(
                "group relative flex items-center gap-4 p-4 rounded-xl border transition-all cursor-pointer",
                isActive 
                  ? "border-primary bg-primary/5 shadow-sm" 
                  : "border-border bg-card hover:border-primary/50 hover:shadow-md"
              )}
              onClick={() => setSelectedFolder(isActive ? null : folder.name)}
            >
              <div className={cn("h-12 w-12 rounded-lg bg-accent flex items-center justify-center", folder.color)}>
                <Folder size={24} />
              </div>
              <div className="flex-1">
                <h3 className={cn(
                  "font-semibold text-sm transition-colors",
                  isActive ? "text-primary" : "group-hover:text-primary"
                )}>{folder.name}</h3>
                <p className="text-xs text-muted-foreground">{folderFileCount} Files</p>
              </div>
              <div className="flex flex-col items-center gap-2">
                <ChevronRight size={16} className={cn(
                  "transition-colors",
                  isActive ? "text-primary rotate-90" : "text-muted-foreground group-hover:text-primary"
                )} />
                {isActive && (
                  <button 
                    disabled={isSubmitting}
                    onClick={async (e) => {
                      e.stopPropagation();
                      if (confirm(`Delete folder "${folder.name}"? Files will be moved to root.`)) {
                        setIsSubmitting(true);
                        try {
                          await deleteFolder(folder.id);
                          setSelectedFolder(null);
                        } catch (error) {
                          console.error('Delete folder error:', error);
                        } finally {
                          setIsSubmitting(false);
                        }
                      }
                    }}
                    className="p-1 hover:bg-red-500/10 text-red-500 rounded-md transition-colors disabled:opacity-50"
                  >
                    <Trash2 size={14} />
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Search & Tabs */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center justify-between">
        <div className="flex items-center gap-2">
          {['all', 'recent', 'starred'].map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab as any)}
              className={cn(
                "px-4 py-1.5 rounded-full text-sm font-medium transition-all capitalize",
                activeTab === tab 
                  ? "bg-primary text-primary-foreground shadow-sm" 
                  : "bg-card border border-border text-muted-foreground hover:bg-accent"
              )}
            >
              {tab}
            </button>
          ))}
        </div>
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" size={18} />
          <input
            type="text"
            placeholder="Search documents..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="h-10 w-full rounded-lg border border-border bg-background pl-10 pr-4 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
          />
        </div>
      </div>

      {/* Documents List */}
      <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                <th className="px-4 py-3 font-medium">Name</th>
                <th className="px-4 py-3 font-medium">Type</th>
                <th className="px-4 py-3 font-medium">Size</th>
                <th className="px-4 py-3 font-medium">Last Modified</th>
                <th className="px-4 py-3 font-medium">Owner</th>
                <th className="px-4 py-3 font-medium"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {filteredDocuments.length > 0 ? filteredDocuments.map((doc) => (
                <tr key={doc.id} className="hover:bg-accent/30 transition-colors group">
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-3">
                      {getFileIcon(doc.type)}
                      <div>
                        <p className="font-medium group-hover:text-primary transition-colors">{doc.name}</p>
                        <p className="text-xs text-muted-foreground">{doc.id}</p>
                      </div>
                      {doc.isStarred && <Star size={14} className="text-yellow-500 fill-yellow-500" />}
                    </div>
                  </td>
                  <td className="px-4 py-4">
                    <span className="inline-flex items-center rounded-full bg-accent px-2 py-0.5 text-xs font-medium text-muted-foreground">
                      {doc.type}
                    </span>
                  </td>
                  <td className="px-4 py-4 text-muted-foreground">{doc.size}</td>
                  <td className="px-4 py-4 text-muted-foreground">
                    {new Date(doc.lastModified).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-4">
                    <div className="flex items-center gap-2">
                      <div className="h-6 w-6 rounded-full bg-primary/10 flex items-center justify-center text-primary text-[10px] font-bold">
                        {doc.owner.split(' ').map(n => n[0]).join('')}
                      </div>
                      <span className="text-xs">{doc.owner}</span>
                    </div>
                  </td>
                  <td className="px-4 py-4 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button 
                        onClick={() => toggleStar(doc)}
                        className={cn(
                          "p-1 hover:bg-accent rounded-md transition-colors",
                          doc.isStarred ? "text-yellow-500" : "text-muted-foreground"
                        )}
                        title={doc.isStarred ? "Unstar" : "Star"}
                      >
                        <Star size={16} fill={doc.isStarred ? "currentColor" : "none"} />
                      </button>
                      <button 
                        onClick={() => handleDownload(doc)}
                        className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                        title="Download"
                      >
                        <Download size={16} />
                      </button>
                      <button 
                        onClick={() => handleMove(doc)}
                        className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                        title="Move to Folder"
                      >
                        <FolderInput size={16} />
                      </button>
                      <button 
                        onClick={() => handleDelete(doc)}
                        className="p-1 hover:bg-accent rounded-md text-muted-foreground hover:text-destructive transition-colors"
                        title="Delete"
                      >
                        <Trash2 size={16} />
                      </button>
                      <button 
                        onClick={() => toast.info(`Options for ${doc.name}`)}
                        className="p-1 hover:bg-accent rounded-md text-muted-foreground transition-colors"
                      >
                        <MoreHorizontal size={18} />
                      </button>
                    </div>
                  </td>
                </tr>
              )) : (
                <tr>
                  <td colSpan={6} className="px-4 py-12 text-center text-muted-foreground">
                    <div className="flex flex-col items-center gap-2">
                      <FileText size={48} className="opacity-20" />
                      <p>No documents found</p>
                      <button 
                        onClick={() => setIsUploadModalOpen(true)}
                        className="text-sm text-primary hover:underline"
                      >
                        Upload your first document
                      </button>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Upload Modal */}
      <AnimatePresence>
        {isUploadModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsUploadModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">Upload Document</h2>
                <button 
                  onClick={() => setIsUploadModalOpen(false)}
                  className="rounded-full p-1 hover:bg-accent transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              <form onSubmit={handleUpload} className="space-y-4">
                <div 
                  onClick={() => fileInputRef.current?.click()}
                  className="group relative flex flex-col items-center justify-center gap-3 p-8 rounded-xl border-2 border-dashed border-border hover:border-primary hover:bg-primary/5 transition-all cursor-pointer"
                >
                  <input 
                    type="file" 
                    ref={fileInputRef}
                    onChange={handleFileChange}
                    className="hidden"
                  />
                  <div className="p-3 rounded-full bg-primary/10 text-primary group-hover:scale-110 transition-transform">
                    <Upload size={24} />
                  </div>
                  <div className="text-center">
                    <p className="text-sm font-medium">{selectedFile ? selectedFile.name : 'Click to select or drag and drop'}</p>
                    <p className="text-xs text-muted-foreground mt-1">Maximum file size 50MB</p>
                  </div>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium">Document Name</label>
                  <input 
                    type="text" 
                    placeholder="e.g. Project Proposal"
                    value={newDoc.name}
                    onChange={(e) => setNewDoc({ ...newDoc, name: e.target.value })}
                    className="w-full h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    required
                  />
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium">File Type</label>
                  <select 
                    value={newDoc.type}
                    onChange={(e) => setNewDoc({ ...newDoc, type: e.target.value as any })}
                    className="w-full h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                  >
                    <option value="PDF">PDF Document</option>
                    <option value="DOCX">Word Document</option>
                    <option value="XLSX">Excel Spreadsheet</option>
                    <option value="PPTX">PowerPoint Presentation</option>
                    <option value="ZIP">Archive (ZIP)</option>
                    <option value="IMG">Image File</option>
                    <option value="CODE">Source Code</option>
                  </select>
                </div>

                <div className="pt-4 flex gap-3">
                  <button 
                    type="button"
                    onClick={() => setIsUploadModalOpen(false)}
                    className="flex-1 h-10 rounded-lg border border-border text-sm font-medium hover:bg-accent transition-colors"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    disabled={isSubmitting}
                    className="flex-1 h-10 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                  >
                    {isSubmitting ? (
                      <>
                        <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                        Uploading...
                      </>
                    ) : (
                      'Upload File'
                    )}
                  </button>
                </div>
              </form>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* New Folder Modal */}
      <AnimatePresence>
        {isNewFolderModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsNewFolderModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">Create New Folder</h2>
                <button 
                  onClick={() => setIsNewFolderModalOpen(false)}
                  className="rounded-full p-1 hover:bg-accent transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              <form onSubmit={handleCreateFolder} className="space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Folder Name</label>
                  <input 
                    type="text" 
                    placeholder="e.g. Marketing Assets"
                    value={newFolderName}
                    onChange={(e) => setNewFolderName(e.target.value)}
                    className="w-full h-10 rounded-lg border border-border bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20"
                    autoFocus
                    required
                  />
                </div>

                <div className="pt-4 flex gap-3">
                  <button 
                    type="button"
                    onClick={() => setIsNewFolderModalOpen(false)}
                    className="flex-1 h-10 rounded-lg border border-border text-sm font-medium hover:bg-accent transition-colors"
                  >
                    Cancel
                  </button>
                  <button 
                    type="submit"
                    disabled={isSubmitting}
                    className="flex-1 h-10 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                  >
                    {isSubmitting ? (
                      <>
                        <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                        Creating...
                      </>
                    ) : (
                      'Create Folder'
                    )}
                  </button>
                </div>
              </form>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* Delete Modal */}
      <AnimatePresence>
        {isDeleteModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsDeleteModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center gap-3 text-destructive mb-4">
                <AlertCircle size={24} />
                <h2 className="text-xl font-bold">Delete Document</h2>
              </div>
              
              <p className="text-sm text-muted-foreground mb-6">
                Are you sure you want to delete <span className="font-semibold text-foreground">"{docToDelete?.name}"</span>? This action cannot be undone.
              </p>

              <div className="flex gap-3">
                <button 
                  onClick={() => setIsDeleteModalOpen(false)}
                  className="flex-1 h-10 rounded-lg border border-border text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
                <button 
                  onClick={confirmDelete}
                  disabled={isSubmitting}
                  className="flex-1 h-10 rounded-lg bg-destructive text-destructive-foreground text-sm font-medium hover:bg-destructive/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-destructive-foreground border-t-transparent" />
                      Deleting...
                    </>
                  ) : (
                    'Delete'
                  )}
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
      
      {/* Move to Folder Modal */}
      <AnimatePresence>
        {isMoveModalOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsMoveModalOpen(false)}
              className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 20 }}
              className="fixed left-1/2 top-1/2 z-[51] w-[95vw] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-border bg-card p-6 shadow-2xl"
            >
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xl font-bold">Move to Folder</h2>
                <button 
                  onClick={() => setIsMoveModalOpen(false)}
                  className="rounded-full p-1 hover:bg-accent transition-colors"
                >
                  <X size={20} />
                </button>
              </div>

              <div className="space-y-2 max-h-[400px] overflow-y-auto pr-2">
                <button
                  onClick={() => confirmMove(null)}
                  className="w-full flex items-center gap-3 p-3 rounded-xl border border-border hover:border-primary hover:bg-primary/5 transition-all text-left"
                >
                  <div className="h-10 w-10 rounded-lg bg-accent flex items-center justify-center text-muted-foreground">
                    <HardDrive size={20} />
                  </div>
                  <div>
                    <p className="font-medium text-sm">Root Directory</p>
                    <p className="text-xs text-muted-foreground">Main storage area</p>
                  </div>
                </button>

                {folders.map((folder) => (
                  <button
                    key={folder.id}
                    onClick={() => confirmMove(folder.name)}
                    className="w-full flex items-center gap-3 p-3 rounded-xl border border-border hover:border-primary hover:bg-primary/5 transition-all text-left"
                  >
                    <div className={cn("h-10 w-10 rounded-lg bg-accent flex items-center justify-center", folder.color)}>
                      <Folder size={20} />
                    </div>
                    <div>
                      <p className="font-medium text-sm">{folder.name}</p>
                      <p className="text-xs text-muted-foreground">Move item here</p>
                    </div>
                  </button>
                ))}
              </div>

              <div className="mt-6 pt-6 border-t border-border">
                <button 
                  onClick={() => setIsMoveModalOpen(false)}
                  className="w-full h-10 rounded-lg border border-border text-sm font-medium hover:bg-accent transition-colors"
                >
                  Cancel
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

function DocumentStatCard({ title, value, icon: Icon, description, progress, color = "text-muted-foreground" }: { title: string, value: string, icon: any, description: string, progress?: number, color?: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4 shadow-sm">
      <div className="flex items-center justify-between mb-2">
        <div className={cn("p-2 rounded-lg bg-accent", color)}>
          <Icon size={18} />
        </div>
      </div>
      <div>
        <p className="text-sm text-muted-foreground">{title}</p>
        <p className="text-2xl font-bold">{value}</p>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
        {progress !== undefined && (
          <div className="mt-3 h-1.5 w-full rounded-full bg-accent overflow-hidden">
            <div 
              className="h-full bg-primary transition-all" 
              style={{ width: `${progress}%` }} 
            />
          </div>
        )}
      </div>
    </div>
  );
}
