import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Search, File, FileText, FileSpreadsheet, X, Trash2, Download } from "lucide-react";
import { MOCK_DOCUMENTS, MOCK_TASKS, MOCK_USERS, type MockDocument } from "@/data/mockData";

function formatBytes(bytes: number): string {
  if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1)} MB`;
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  return `${bytes} B`;
}

function getFileIcon(mimeType: string) {
  if (mimeType === "application/pdf") return <FileText className="w-5 h-5 text-rose-500" />;
  if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return <FileSpreadsheet className="w-5 h-5 text-emerald-600" />;
  return <File className="w-5 h-5 text-blue-500" />;
}

function getFileTypeName(mimeType: string): string {
  if (mimeType === "application/pdf") return "PDF";
  if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return "Excel";
  if (mimeType.includes("word")) return "Word";
  if (mimeType === "application/octet-stream") return "Figma";
  return "File";
}

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const d = Math.floor(diff / 86400000);
  if (d > 0) return `${d}d ago`;
  return "Today";
}

export default function DocumentsPage() {
  const [documents, setDocuments] = useState(MOCK_DOCUMENTS);
  const [search, setSearch] = useState("");
  const [showUpload, setShowUpload] = useState(false);
  const [newDoc, setNewDoc] = useState({ name: "", url: "#", mimeType: "application/pdf", taskId: "" });

  const filtered = documents.filter(d =>
    d.name.toLowerCase().includes(search.toLowerCase()) ||
    d.uploadedByName.toLowerCase().includes(search.toLowerCase())
  );

  const handleUpload = () => {
    if (!newDoc.name.trim()) return;
    const user = MOCK_USERS[0];
    const task = newDoc.taskId ? MOCK_TASKS.find(t => t.id === parseInt(newDoc.taskId)) : null;
    const doc: MockDocument = {
      id: documents.length + 100,
      tenantId: 1,
      name: newDoc.name,
      mimeType: newDoc.mimeType,
      sizeBytes: Math.floor(Math.random() * 2000000) + 100000,
      taskId: task?.id ?? null,
      taskTitle: task?.title ?? null,
      uploadedByUserId: user.id,
      uploadedByName: user.name,
      url: newDoc.url,
      createdAt: new Date().toISOString(),
    };
    setDocuments(prev => [doc, ...prev]);
    setNewDoc({ name: "", url: "#", mimeType: "application/pdf", taskId: "" });
    setShowUpload(false);
  };

  const handleDelete = (docId: number) => {
    setDocuments(prev => prev.filter(d => d.id !== docId));
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Documents</h1>
          <p className="text-sm text-muted-foreground mt-1">{documents.length} files uploaded</p>
        </div>
        <button
          onClick={() => setShowUpload(true)}
          className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 transition"
          data-testid="button-upload-document"
        >
          <Plus className="w-4 h-4" /> Upload Document
        </button>
      </div>

      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search documents..."
          className="w-full pl-9 pr-4 py-2 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
        />
      </div>

      <div className="bg-card border border-card-border rounded-xl shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/30">
              <th className="text-left px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Name</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden sm:table-cell">Type</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden md:table-cell">Size</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden lg:table-cell">Task</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden md:table-cell">Uploaded by</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden lg:table-cell">Date</th>
              <th className="px-5 py-3" />
            </tr>
          </thead>
          <tbody>
            {filtered.map((doc, i) => (
              <motion.tr
                key={doc.id}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: i * 0.05 }}
                className="border-b border-border/50 hover:bg-muted/20 transition-colors"
                data-testid={`row-doc-${doc.id}`}
              >
                <td className="px-5 py-3.5">
                  <div className="flex items-center gap-3">
                    {getFileIcon(doc.mimeType)}
                    <span className="font-medium text-foreground truncate max-w-48">{doc.name}</span>
                  </div>
                </td>
                <td className="px-4 py-3.5 hidden sm:table-cell">
                  <span className="text-xs bg-muted px-2 py-0.5 rounded font-medium text-muted-foreground">{getFileTypeName(doc.mimeType)}</span>
                </td>
                <td className="px-4 py-3.5 hidden md:table-cell text-sm text-muted-foreground">{formatBytes(doc.sizeBytes)}</td>
                <td className="px-4 py-3.5 hidden lg:table-cell">
                  {doc.taskTitle ? (
                    <span className="text-xs text-blue-600 bg-blue-50 px-2 py-0.5 rounded border border-blue-100">{doc.taskTitle.slice(0, 30)}{doc.taskTitle.length > 30 ? "..." : ""}</span>
                  ) : <span className="text-muted-foreground text-xs">—</span>}
                </td>
                <td className="px-4 py-3.5 hidden md:table-cell text-sm text-muted-foreground">{doc.uploadedByName}</td>
                <td className="px-4 py-3.5 hidden lg:table-cell text-xs text-muted-foreground">{timeAgo(doc.createdAt)}</td>
                <td className="px-5 py-3.5">
                  <div className="flex items-center gap-1 justify-end">
                    <button className="p-1.5 text-muted-foreground hover:text-blue-600 hover:bg-blue-50 rounded-lg transition">
                      <Download className="w-3.5 h-3.5" />
                    </button>
                    <button onClick={() => handleDelete(doc.id)} className="p-1.5 text-muted-foreground hover:text-rose-500 hover:bg-rose-50 rounded-lg transition">
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </td>
              </motion.tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={7} className="px-5 py-12 text-center text-muted-foreground text-sm">No documents found</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <AnimatePresence>
        {showUpload && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
            onClick={() => setShowUpload(false)}
          >
            <motion.div initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }}
              onClick={e => e.stopPropagation()}
              className="bg-card rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
            >
              <div className="px-6 py-5 border-b border-border flex items-center justify-between">
                <h2 className="text-base font-semibold">Upload Document</h2>
                <button onClick={() => setShowUpload(false)} className="p-1.5 hover:bg-muted rounded text-muted-foreground"><X className="w-4 h-4" /></button>
              </div>
              <div className="p-6 space-y-4">
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Document Name *</label>
                  <input value={newDoc.name} onChange={e => setNewDoc(p => ({ ...p, name: e.target.value }))}
                    placeholder="Report Q2 2025.pdf"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">File Type</label>
                  <select value={newDoc.mimeType} onChange={e => setNewDoc(p => ({ ...p, mimeType: e.target.value }))}
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  >
                    <option value="application/pdf">PDF</option>
                    <option value="application/vnd.ms-excel">Excel</option>
                    <option value="application/vnd.openxmlformats-officedocument.wordprocessingml.document">Word</option>
                    <option value="application/octet-stream">Other</option>
                  </select>
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Link to Task (optional)</label>
                  <select value={newDoc.taskId} onChange={e => setNewDoc(p => ({ ...p, taskId: e.target.value }))}
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  >
                    <option value="">No task</option>
                    {MOCK_TASKS.map(t => <option key={t.id} value={t.id}>{t.title}</option>)}
                  </select>
                </div>
                <div className="flex gap-3 pt-2">
                  <button onClick={() => setShowUpload(false)} className="flex-1 py-2.5 bg-muted text-muted-foreground text-sm font-medium rounded-lg">Cancel</button>
                  <button onClick={handleUpload} className="flex-1 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg">Upload</button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
