import { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { Link, useNavigate } from 'react-router-dom';
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";

interface Document {
  id: number;
  title: string;
  content: string;
  status: string;
  workflowType: string;
  adminSignature: string | null;
  allowDownload: number;
  createdAt: string;
}

export default function Dashboard() {
  const [documents, setDocuments] = useState<Document[]>([]);
  const [plans, setPlans] = useState<any[]>([]);
  const [selectedPlanId, setSelectedPlanId] = useState<number | null>(null);
  const [previewDoc, setPreviewDoc] = useState<Document | null>(null);
  const [toastMessage, setToastMessage] = useState<{msg: string, type: 'success' | 'error'} | null>(null);
  const [inviteModal, setInviteModal] = useState<{isOpen: boolean, doc: Document | null, isManual: boolean}>({ isOpen: false, doc: null, isManual: false });
  const [emailsInput, setEmailsInput] = useState('');
  const [expiryInput, setExpiryInput] = useState('48');
  const [generatedLinks, setGeneratedLinks] = useState('');
  const [activeTab, setActiveTab] = useState<'pending' | 'completed'>('pending');
  
  const { user, token, logout } = useAuth();
  const navigate = useNavigate();

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToastMessage({ msg, type });
    setTimeout(() => setToastMessage(null), 5000);
  };

  useEffect(() => {
    fetch('/api/plans')
      .then(res => res.json())
      .then(data => {
        setPlans(data);
        if (data.length > 0) setSelectedPlanId(data[0].id);
      })
      .catch(err => console.error(err));
  }, []);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get('payment') === 'success') {
      alert("Payment successful! Your membership is now active.");
      // In a real app we might want to refresh user context here
    }

    const fetchDocs = async () => {
      try {
        const res = await axios.get('/api/documents', { headers: { Authorization: `Bearer ${token}` } });
        setDocuments(res.data);
      } catch (err: any) {
        console.error("Failed to fetch documents", err);
        if (err.response && (err.response.status === 401 || err.response.status === 403)) {
          alert("Your session has expired. Please log in again.");
          logout();
          navigate('/');
        }
      }
    };
    if (token) fetchDocs();
  }, [token]);

  const handleUpgrade = async () => {
    if (!selectedPlanId) return alert("Please select a plan first.");
    try {
      const res = await axios.post('/api/checkout', { planId: selectedPlanId }, { headers: { Authorization: `Bearer ${token}` } });
      window.location.href = res.data.url;
    } catch (err) {
      alert("Failed to initiate checkout");
    }
  };

  const handleAdminSign = async (doc: Document) => {
    const signatureName = prompt('Enter your legal name to sign as Admin:');
    if (!signatureName) return;
    try {
      // In a real app, we'd inject the admin signature into the HTML content here.
      // For this implementation, we append it at the end of the content.
      const finalContent = doc.content + `<div style="margin-top: 40px; border-top: 1px solid #ccc; padding-top: 20px;">
        <p><strong>Admin Signature:</strong> <span style="font-family: 'Dancing Script', cursive; font-size: 24px;">${signatureName}</span></p>
      </div>`;
      
      await axios.post(`/api/documents/${doc.id}/admin-sign`, { signatureName, finalContent }, { headers: { Authorization: `Bearer ${token}` } });
      alert("Document signed successfully!");
      // Refresh docs
      const res = await axios.get('/api/documents', { headers: { Authorization: `Bearer ${token}` } });
      setDocuments(res.data);
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to sign document');
    }
  };

  const handleDeleteDocument = async (docId: number) => {
    if (!confirm('Are you sure you want to delete this document?')) return;
    try {
      await axios.delete(`/api/documents/${docId}`, { headers: { Authorization: `Bearer ${token}` } });
      setDocuments(documents.filter(d => d.id !== docId));
    } catch (err: any) {
      alert(err.response?.data?.error || 'Failed to delete document');
    }
  };

  const isRestricted = user?.role === 'admin' && user?.membershipStatus !== 'active';

  const recentDocuments = documents.filter(d => d.status !== 'signed');
  const completedDocuments = documents.filter(d => d.status === 'signed');

  return (
    <div className="font-body-md text-body-md overflow-x-hidden min-h-screen bg-[#f8fafc] text-[#0f172a] -mt-5 -mx-3 px-3 py-10" style={{ fontFamily: 'Inter, sans-serif' }}>
      <div className="px-4 py-8 max-w-[1440px] mx-auto">
        
        {/* Header Section */}
        <div className="mb-10">
          <h1 className="font-display-lg text-[32px] md:text-[48px] font-bold leading-tight text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>
            Welcome back, {user?.firstName || 'Admin'}.
          </h1>
          <p className="font-body-lg text-[16px] md:text-[18px] text-[#475569] mt-2">Here's your signing activity for the last 30 days.</p>
        </div>

        {/* Bento Grid Metric Cards */}
        <div className="grid grid-cols-1 md:grid-cols-12 gap-[24px] mb-12">
          
          {/* Create Document Card */}
          <div className="md:col-span-4 glass-card p-8 rounded-xl flex flex-col justify-between items-start h-64 transition-all duration-300">
            <div className="w-12 h-12 bg-[#c0c1ff]/10 rounded-lg flex items-center justify-center mb-4">
              <span className="material-symbols-outlined text-[#c0c1ff]">add_circle</span>
            </div>
            <div className="w-full">
              <h2 className="text-[24px] font-semibold text-[#0f172a] mb-4" style={{ fontFamily: 'Outfit, sans-serif' }}>Create Document</h2>
              <div className="flex flex-col xl:flex-row gap-2 w-full">
                {isRestricted ? (
                  <div className="w-full flex flex-col gap-3">
                    <select 
                      value={selectedPlanId || ''} 
                      onChange={(e) => setSelectedPlanId(Number(e.target.value))}
                      className="w-full bg-white text-[#0f172a] p-2 rounded-lg border border-slate-300 focus:outline-none focus:border-[#8083ff] text-[14px]"
                    >
                      {plans.map(p => (
                        <option key={p.id} value={p.id}>{p.name} - ${p.price}/year</option>
                      ))}
                    </select>
                    <button onClick={handleUpgrade} className="w-full bg-[#8083ff] text-[#0d0096] px-4 py-3 rounded-lg font-bold text-[14px] flex items-center justify-center gap-2 primary-glow hover:scale-105 transition-transform active:scale-95 border-none mt-2">
                      <span className="material-symbols-outlined text-[18px]">credit_card</span>
                      Pay with Credit Card
                    </button>
                    <div className="w-full relative z-0">
                      <PayPalScriptProvider options={{ clientId: "AU9CVR7X2i6oyFQj7RM85FhLTx-0k2010AOZ0bQIAgRmjelrSydEq9xXkAo46jyBN21IlkVPauqpF2e9" }}>
                        <PayPalButtons 
                          style={{ layout: "horizontal", height: 44 }}
                          createOrder={async () => {
                            if (!selectedPlanId) throw new Error("Select plan");
                            const res = await axios.post('/api/paypal/create-order', { planId: selectedPlanId }, { headers: { Authorization: `Bearer ${token}` } });
                            return res.data.id;
                          }}
                          onApprove={async (data) => {
                            try {
                              await axios.post('/api/paypal/capture-order', { orderID: data.orderID, planId: selectedPlanId }, { headers: { Authorization: `Bearer ${token}` } });
                              alert("Payment successful! Your membership is now active.");
                              window.location.reload();
                            } catch (err) {
                              alert("Failed to capture PayPal payment.");
                            }
                          }}
                        />
                      </PayPalScriptProvider>
                    </div>
                  </div>
                ) : (
                  <>
                    <Link to="/editor" className="flex-1 bg-[#8083ff] text-[#0d0096] px-4 py-3 rounded-lg font-semibold text-[14px] flex items-center justify-center gap-2 primary-glow hover:scale-105 transition-transform active:scale-95 no-underline">
                      <span className="material-symbols-outlined text-[18px]">post_add</span>
                      New
                    </Link>
                    <label className="flex-1 bg-[#f1f5f9] border border-slate-300 text-[#0f172a] px-4 py-3 rounded-lg font-semibold text-[14px] flex items-center justify-center gap-2 hover:bg-[#e2e8f0] transition-colors cursor-pointer text-center">
                      <span className="material-symbols-outlined text-[18px]">upload_file</span>
                      Upload
                      <input type="file" className="hidden" accept=".pdf,.docx" onChange={async (e) => {
                        const file = e.target.files?.[0];
                        if (!file) return;
                        const formData = new FormData();
                        formData.append('file', file);
                        try {
                          const res = await axios.post('/api/documents/upload', formData, { headers: { Authorization: `Bearer ${token}` } });
                          navigate('/editor', { state: { initialHtml: res.data.html, initialTitle: res.data.title } });
                        } catch (err) {
                          alert("Upload failed. Make sure the backend server is restarted with the new dependencies.");
                        }
                      }} />
                    </label>
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Total Documents Card */}
          <div className="md:col-span-4 glass-card p-8 rounded-xl flex flex-col h-64 transition-all duration-300 relative overflow-hidden">
            <div className="absolute -right-4 -top-4 w-32 h-32 bg-[#c0c1ff]/5 rounded-full blur-3xl"></div>
            <div className="flex justify-between items-start mb-auto">
              <span className="text-[#475569] font-semibold text-[14px]">Total Documents</span>
              <div className="flex items-center gap-1 text-[#4edea3] font-semibold text-[12px] bg-[#4edea3]/10 px-2 py-1 rounded-full">
                <span className="material-symbols-outlined text-[16px]">trending_up</span>
                12%
              </div>
            </div>
            <div>
              <span className="font-bold text-[48px] text-[#0f172a] block" style={{ fontFamily: 'Outfit, sans-serif' }}>{documents.length}</span>
              <span className="text-[#475569] text-[16px]">Across all workspaces</span>
            </div>
          </div>

          {/* User Management Card (For Superadmin) */}
          {(user?.role === 'superadmin') ? (
            <div className="md:col-span-4 glass-card p-8 rounded-xl flex flex-col h-64 transition-all duration-300 relative overflow-hidden">
              <div className="absolute -right-4 -bottom-4 w-32 h-32 bg-[#ffb4ab]/5 rounded-full blur-3xl"></div>
              <div className="flex justify-between items-start mb-auto">
                <span className="text-[#475569] font-semibold text-[14px]">Platform Management</span>
                <span className="material-symbols-outlined text-[#ffb4ab]">admin_panel_settings</span>
              </div>
              <div className="mt-auto flex flex-wrap gap-2">
                <Link to="/manage-users" className="flex-1 min-w-[80px] text-center bg-[#ffb4ab]/10 text-[#ffb4ab] border border-[#ffb4ab]/20 px-2 py-2 rounded-lg font-semibold text-[12px] flex items-center justify-center gap-1 hover:bg-[#ffb4ab]/20 transition-all no-underline">
                  <span className="material-symbols-outlined text-[14px]">group</span> Users
                </Link>
                <Link to="/manage-plans" className="flex-1 min-w-[80px] text-center bg-[#8083ff]/10 text-[#8083ff] border border-[#8083ff]/20 px-2 py-2 rounded-lg font-semibold text-[12px] flex items-center justify-center gap-1 hover:bg-[#8083ff]/20 transition-all no-underline">
                  <span className="material-symbols-outlined text-[14px]">sell</span> Plans
                </Link>
                <Link to="/manage-memberships" className="flex-1 min-w-[80px] text-center bg-[#ffb4ab]/10 text-[#ffb4ab] border border-[#ffb4ab]/20 px-2 py-2 rounded-lg font-semibold text-[12px] flex items-center justify-center gap-1 hover:bg-[#ffb4ab]/20 transition-all no-underline">
                  <span className="material-symbols-outlined text-[14px]">card_membership</span> Pay
                </Link>
                <Link to="/analytics" className="flex-1 min-w-[80px] text-center bg-[#c0c1ff]/10 text-[#c0c1ff] border border-[#c0c1ff]/20 px-2 py-2 rounded-lg font-semibold text-[12px] flex items-center justify-center gap-1 hover:bg-[#c0c1ff]/20 transition-all no-underline">
                  <span className="material-symbols-outlined text-[14px]">monitoring</span> Analytics
                </Link>
                <Link to="/logs" className="flex-1 min-w-[80px] text-center bg-[#4edea3]/10 text-[#4edea3] border border-[#4edea3]/20 px-2 py-2 rounded-lg font-semibold text-[12px] flex items-center justify-center gap-1 hover:bg-[#4edea3]/20 transition-all no-underline">
                  <span className="material-symbols-outlined text-[14px]">history</span> Logs
                </Link>
              </div>
            </div>
          ) : (
            <div className="md:col-span-4 glass-card p-8 rounded-xl flex flex-col h-64 transition-all duration-300 relative overflow-hidden">
              <div className="absolute -right-4 -bottom-4 w-32 h-32 bg-[#4edea3]/5 rounded-full blur-3xl"></div>
              <div className="flex justify-between items-start mb-auto">
                <span className="text-[#475569] font-semibold text-[14px]">Pending Signatures</span>
                <span className="material-symbols-outlined text-[#4edea3]">pending_actions</span>
              </div>
              <div>
                <span className="font-bold text-[48px] text-[#4edea3] block" style={{ fontFamily: 'Outfit, sans-serif' }}>0</span>
                <span className="text-[#475569] text-[16px]">Awaiting recipient action</span>
              </div>
            </div>
          )}

        </div>

        {/* Tabs */}
        <div className="flex items-center gap-4 mb-6 border-b border-black/10 pb-4">
          <button 
            onClick={() => setActiveTab('pending')}
            className={`px-4 py-2 font-bold text-[16px] transition-all border-none bg-transparent ${activeTab === 'pending' ? 'text-[#0f172a] border-b-2 border-[#8083ff]' : 'text-[#475569] hover:text-[#0f172a]'}`}
          >
            Pending Documents
          </button>
          <button 
            onClick={() => setActiveTab('completed')}
            className={`px-4 py-2 font-bold text-[16px] transition-all border-none bg-transparent ${activeTab === 'completed' ? 'text-[#0f172a] border-b-2 border-[#8083ff]' : 'text-[#475569] hover:text-[#0f172a]'}`}
          >
            Completed Signatures
          </button>
        </div>

        {activeTab === 'pending' && (
        <div className="glass-card rounded-xl overflow-hidden mb-12">
          <div className="px-8 py-6 border-b border-black/10 flex justify-between items-center">
            <h3 className="text-[24px] font-semibold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Recent Documents</h3>
            <div className="relative group">
              <input className="bg-[#f1f5f9]/50 border border-slate-300 rounded-lg pl-10 pr-4 py-2 focus:border-[#c0c1ff] focus:ring-1 focus:ring-[#c0c1ff] transition-all text-[16px] text-[#0f172a] outline-none" placeholder="Search documents..." type="text" />
              <span className="material-symbols-outlined absolute left-3 top-2.5 text-[#475569]">search</span>
            </div>
          </div>
          
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-white/30 text-[#475569] text-[14px] font-semibold uppercase tracking-wider">
                  <th className="px-8 py-4">ID</th>
                  <th className="px-8 py-4">Title</th>
                  <th className="px-8 py-4">Status</th>
                  <th className="px-8 py-4">Date Created</th>
                  <th className="px-8 py-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {recentDocuments.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-8 py-8 text-center text-[#475569]">No pending documents found.</td>
                  </tr>
                ) : (
                  recentDocuments.map(doc => (
                    <tr key={doc.id} className="hover:bg-black/5 transition-colors group">
                      <td className="px-8 py-5 text-[#475569] text-[16px]">#{doc.id}</td>
                      <td className="px-8 py-5 font-medium text-[#0f172a] text-[16px]">{doc.title}</td>
                      <td className="px-8 py-5">
                        <span className={`px-3 py-1 rounded-full text-[12px] font-semibold border ${
                          doc.status === 'signed' 
                            ? 'bg-[#4edea3]/15 text-[#4edea3] border-[#4edea3]/20' 
                            : 'bg-[#ffb4ab]/15 text-[#ffb4ab] border-[#ffb4ab]/20'
                        }`}>
                          {doc.status}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-[#475569] text-[16px]">{new Date(doc.createdAt).toLocaleDateString()}</td>
                      <td className="px-8 py-5 text-right flex items-center justify-end gap-3">
                        {(!doc.adminSignature && ((doc.workflowType === 'pre-sign') || (doc.workflowType === 'post-sign' && doc.status === 'signed'))) ? (
                          <button 
                            className="bg-[#8083ff] hover:bg-[#c0c1ff] text-[#0d0096] px-4 py-2 rounded-lg font-bold text-[14px] transition-all border-none"
                            onClick={() => handleAdminSign(doc)}
                          >
                            Sign as Admin
                          </button>
                        ) : null}

                        <button 
                          className="bg-black/5 hover:bg-black/10 text-[#4edea3] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Edit Document"
                          onClick={() => {
                            navigate('/editor', { state: { initialHtml: doc.content, initialTitle: doc.title, documentId: doc.id } });
                          }}
                        >
                          <span className="material-symbols-outlined text-[20px]">edit</span>
                        </button>

                        <button 
                          className="bg-black/5 hover:bg-black/10 text-[#0f172a] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Preview Document"
                          onClick={() => setPreviewDoc(doc)}
                        >
                          <span className="material-symbols-outlined text-[20px]">visibility</span>
                        </button>

                        <button 
                          className="bg-black/5 hover:bg-black/10 text-[#0f172a] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Copy Manual Link"
                          onClick={() => {
                            if (isRestricted) return showToast('Upgrade to standard membership to send documents!', 'error');
                            if (doc.workflowType === 'pre-sign' && !doc.adminSignature) return showToast('You must sign this document before sending it!', 'error');
                            setInviteModal({ isOpen: true, doc, isManual: true });
                            setEmailsInput('');
                            setGeneratedLinks('');
                          }}
                        >
                          <span className="material-symbols-outlined text-[20px]">content_copy</span>
                        </button>

                        {doc.status !== 'signed' ? (
                          <button 
                            className={`px-4 py-2 rounded-lg font-semibold text-[14px] transition-all border ${isRestricted ? 'bg-[#e2e8f0]/40 text-[#475569]/50 border-black/5 cursor-not-allowed' : 'bg-[#e2e8f0]/40 hover:bg-[#e2e8f0]/60 text-[#0f172a] active:scale-95 border-black/5'}`}
                            onClick={() => {
                              if (isRestricted) return showToast('Upgrade to standard membership to send documents!', 'error');
                              if (doc.workflowType === 'pre-sign' && !doc.adminSignature) return showToast('You must sign this document before sending it!', 'error');
                              setInviteModal({ isOpen: true, doc, isManual: false });
                              setEmailsInput('');
                              setGeneratedLinks('');
                            }}
                          >
                            Invite Signer
                          </button>
                        ) : (
                          <span className="text-[#4edea3] font-semibold flex items-center gap-1">
                            <span className="material-symbols-outlined text-[18px]">verified</span> Completed
                          </span>
                        )}
                        <div className="relative group/dropdown">
                          <button className="bg-black/50 text-[#475569] w-9 h-9 rounded-lg hover:text-[#0f172a] transition-colors border border-black/5 flex items-center justify-center p-0">
                            <span className="material-symbols-outlined text-[18px]">download</span>
                          </button>
                          <div className="absolute right-0 top-full mt-2 w-40 bg-[#f1f5f9] border border-black/10 rounded-lg shadow-xl opacity-0 group-hover/dropdown:opacity-100 pointer-events-none group-hover/dropdown:pointer-events-auto transition-opacity z-50 overflow-hidden flex flex-col">
                            <a href={`/api/documents/${doc.id}/export/pdf`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/pdf?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">picture_as_pdf</span> PDF Document
                            </a>
                            <a href={`/api/documents/${doc.id}/export/docx`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors border-t border-black/5" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/docx?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">description</span> Word Document
                            </a>
                            <a href={`/api/documents/${doc.id}/export/txt`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors border-t border-black/5" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/txt?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">article</span> Text File
                            </a>
                          </div>
                        </div>

                        <button 
                          className="bg-black/5 hover:bg-[#ffb4ab]/20 text-[#ffb4ab] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Delete Document"
                          onClick={() => handleDeleteDocument(doc.id)}
                        >
                          <span className="material-symbols-outlined text-[20px]">delete</span>
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
          
          <div className="px-8 py-4 border-t border-black/10 flex justify-between items-center bg-black/10">
            <span className="text-[#475569] text-[12px] font-semibold">Showing {recentDocuments.length} pending documents</span>
          </div>
        </div>
        )}

        {activeTab === 'completed' && (
        <div className="glass-card rounded-xl overflow-hidden mb-12">
          <div className="px-8 py-6 border-b border-black/10 flex justify-between items-center">
            <h3 className="text-[24px] font-semibold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Completed Signatures</h3>
          </div>
          
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-white/30 text-[#475569] text-[14px] font-semibold uppercase tracking-wider">
                  <th className="px-8 py-4">ID</th>
                  <th className="px-8 py-4">Title</th>
                  <th className="px-8 py-4">Status</th>
                  <th className="px-8 py-4">Date Completed</th>
                  <th className="px-8 py-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {completedDocuments.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-8 py-8 text-center text-[#475569]">No completed signatures yet.</td>
                  </tr>
                ) : (
                  completedDocuments.map(doc => (
                    <tr key={doc.id} className="hover:bg-black/5 transition-colors group">
                      <td className="px-8 py-5 text-[#475569] text-[16px]">#{doc.id}</td>
                      <td className="px-8 py-5 font-medium text-[#0f172a] text-[16px]">{doc.title}</td>
                      <td className="px-8 py-5">
                        <span className="px-3 py-1 rounded-full text-[12px] font-semibold border bg-[#4edea3]/15 text-[#4edea3] border-[#4edea3]/20 flex items-center w-max gap-1">
                          <span className="material-symbols-outlined text-[14px]">check_circle</span>
                          Completed
                        </span>
                      </td>
                      <td className="px-8 py-5 text-[#475569] text-[16px]">{new Date(doc.createdAt).toLocaleDateString()}</td>
                      <td className="px-8 py-5 text-right flex items-center justify-end gap-3">
                        <button 
                          className="bg-black/5 hover:bg-black/10 text-[#0f172a] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Preview Document"
                          onClick={() => setPreviewDoc(doc)}
                        >
                          <span className="material-symbols-outlined text-[20px]">visibility</span>
                        </button>
                        
                        {doc.allowDownload === 0 && (
                          <button 
                            className="bg-black/5 hover:bg-black/10 text-[#8083ff] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                            title="Email PDF to Signer"
                            onClick={async () => {
                              const email = prompt('Signer was not allowed to download PDF. Enter email address to manually send PDF attachment:');
                              if (!email) return;
                              try {
                                const res = await axios.post(`/api/documents/${doc.id}/send-pdf`, { email }, { headers: { Authorization: `Bearer ${token}` } });
                                alert(res.data.message);
                              } catch (err) {
                                alert('Failed to send email');
                              }
                            }}
                          >
                            <span className="material-symbols-outlined text-[20px]">mail</span>
                          </button>
                        )}
                        
                        <div className="relative group/dropdown">
                          <button className="bg-black/50 text-[#475569] w-9 h-9 rounded-lg hover:text-[#0f172a] transition-colors border border-black/5 flex items-center justify-center p-0">
                            <span className="material-symbols-outlined text-[18px]">download</span>
                          </button>
                          <div className="absolute right-0 top-full mt-2 w-40 bg-[#f1f5f9] border border-black/10 rounded-lg shadow-xl opacity-0 group-hover/dropdown:opacity-100 pointer-events-none group-hover/dropdown:pointer-events-auto transition-opacity z-50 overflow-hidden flex flex-col">
                            <a href={`/api/documents/${doc.id}/export/pdf`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/pdf?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">picture_as_pdf</span> PDF Document
                            </a>
                            <a href={`/api/documents/${doc.id}/export/docx`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors border-t border-black/5" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/docx?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">description</span> Word Document
                            </a>
                            <a href={`/api/documents/${doc.id}/export/txt`} className="px-4 py-3 text-[#475569] hover:bg-[#8083ff]/10 hover:text-[#c0c1ff] text-[13px] font-semibold flex items-center gap-2 no-underline text-left transition-colors border-t border-black/5" onClick={(e) => { e.preventDefault(); window.open(`/api/documents/${doc.id}/export/txt?token=${token}`, '_blank'); }}>
                              <span className="material-symbols-outlined text-[16px]">article</span> Text File
                            </a>
                          </div>
                        </div>

                        <button 
                          className="bg-black/5 hover:bg-[#ffb4ab]/20 text-[#ffb4ab] p-2 rounded-lg transition-all border-none flex items-center justify-center"
                          title="Delete Document"
                          onClick={() => handleDeleteDocument(doc.id)}
                        >
                          <span className="material-symbols-outlined text-[20px]">delete</span>
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
          
          <div className="px-8 py-4 border-t border-black/10 flex justify-between items-center bg-black/10">
            <span className="text-[#475569] text-[12px] font-semibold">Showing {completedDocuments.length} completed documents</span>
          </div>
        </div>
        )}

      </div>

      {/* Preview Modal */}
      {previewDoc && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-8">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden">
            <div className="flex justify-between items-center p-6 border-b border-gray-100">
              <h2 className="text-2xl font-bold text-gray-800">{previewDoc.title}</h2>
              <button onClick={() => setPreviewDoc(null)} className="text-gray-400 hover:text-gray-600 border-none bg-transparent cursor-pointer">
                <span className="material-symbols-outlined text-[28px]">close</span>
              </button>
            </div>
            <div className="p-8 overflow-y-auto bg-gray-50 flex-1">
              <div className="bg-white p-12 shadow-sm rounded-lg border border-gray-100 min-h-full" dangerouslySetInnerHTML={{ __html: previewDoc.content }} />
            </div>
          </div>
        </div>
      )}
      {/* Invite Modal */}
      {inviteModal.isOpen && inviteModal.doc && (
        <div className="fixed inset-0 bg-slate-900/40 backdrop-blur-sm z-50 flex items-center justify-center p-8">
          <div className="bg-white border border-black/10 rounded-xl shadow-2xl w-full max-w-lg flex flex-col overflow-hidden relative">
            <div className="absolute -right-4 -top-4 w-32 h-32 bg-[#8083ff]/10 rounded-full blur-3xl pointer-events-none"></div>
            
            <div className="flex justify-between items-center p-6 border-b border-black/10 relative z-10">
              <h2 className="text-[20px] font-bold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>
                {inviteModal.isManual ? 'Generate Manual Links' : 'Invite Signers'}
              </h2>
              <button onClick={() => setInviteModal({ isOpen: false, doc: null, isManual: false })} className="text-[#475569] hover:text-[#0f172a] border-none bg-transparent cursor-pointer">
                <span className="material-symbols-outlined text-[24px]">close</span>
              </button>
            </div>
            
            <div className="p-6 relative z-10">
              <div className="mb-4">
                <label className="block text-[#475569] text-[14px] font-semibold mb-2">Recipient Email(s)</label>
                <textarea 
                  className="w-full bg-[#f1f5f9] border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:border-[#8083ff] focus:ring-1 focus:ring-[#8083ff] outline-none text-[14px] custom-scrollbar min-h-[100px]"
                  placeholder="Enter email addresses, separated by commas"
                  value={emailsInput}
                  onChange={(e) => setEmailsInput(e.target.value)}
                />
                <p className="text-[12px] text-[#475569]/70 mt-1">Separate multiple emails with a comma (e.g., test@a.com, test@b.com)</p>
              </div>

              {!inviteModal.isManual && (
                <div className="mb-6">
                  <label className="block text-[#475569] text-[14px] font-semibold mb-2">Link Expiration (Hours)</label>
                  <input 
                    type="number"
                    className="w-full bg-[#f1f5f9] border border-slate-300 rounded-lg p-3 text-[#0f172a] focus:border-[#8083ff] focus:ring-1 focus:ring-[#8083ff] outline-none text-[14px]"
                    placeholder="48"
                    value={expiryInput}
                    onChange={(e) => setExpiryInput(e.target.value)}
                  />
                </div>
              )}

              {generatedLinks && (
                <div className="mt-4 mb-4 p-4 bg-[#4edea3]/10 border border-[#4edea3]/20 rounded-lg">
                  <p className="text-[14px] font-semibold text-[#4edea3] mb-2">Links Generated Successfully:</p>
                  <textarea 
                    readOnly
                    value={generatedLinks}
                    className="w-full bg-black/20 border border-black/5 rounded p-2 text-[12px] text-[#0f172a] h-24 custom-scrollbar outline-none"
                    onClick={(e) => {
                      (e.target as HTMLTextAreaElement).select();
                      navigator.clipboard.writeText(generatedLinks);
                      showToast('Copied to clipboard!', 'success');
                    }}
                  />
                  <p className="text-[12px] text-[#475569] mt-2">Click inside the box to copy.</p>
                </div>
              )}

              <div className="flex justify-end gap-3 mt-6">
                <button 
                  onClick={() => setInviteModal({ isOpen: false, doc: null, isManual: false })}
                  className="px-4 py-2 rounded-lg bg-transparent border border-black/10 text-[#475569] hover:bg-black/5 font-semibold text-[14px] transition-all"
                >
                  Close
                </button>
                <button 
                  className="px-4 py-2 rounded-lg bg-[#8083ff] hover:bg-[#c0c1ff] text-[#0d0096] font-bold text-[14px] transition-all border-none flex items-center gap-2 primary-glow"
                  onClick={async () => {
                    if (!emailsInput.trim()) return showToast('Please enter at least one email address', 'error');
                    try {
                      const res = await axios.post('/api/invite', { 
                        documentId: inviteModal.doc!.id, 
                        email: emailsInput, 
                        expirationHours: inviteModal.isManual ? 48 : Number(expiryInput), 
                        sendEmail: !inviteModal.isManual 
                      }, { headers: { Authorization: `Bearer ${token}` } });
                      
                      const linksText = res.data.links ? res.data.links.join('\n') : res.data.link;
                      
                      if (inviteModal.isManual) {
                        setGeneratedLinks(linksText);
                        await navigator.clipboard.writeText(linksText);
                        showToast('Links generated and copied to clipboard!', 'success');
                      } else {
                        showToast(res.data.message || 'Invitations sent successfully!', 'success');
                        setInviteModal({ isOpen: false, doc: null, isManual: false });
                      }
                    } catch (err) {
                      showToast('Failed to process request. Please try again.', 'error');
                    }
                  }}
                >
                  <span className="material-symbols-outlined text-[18px]">
                    {inviteModal.isManual ? 'link' : 'send'}
                  </span>
                  {inviteModal.isManual ? 'Generate Links' : 'Send Invites'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Toast Notifications */}
      {toastMessage && (
        <div className={`fixed bottom-8 right-8 px-6 py-4 rounded-xl shadow-2xl flex items-center gap-3 z-[60] border animate-slide-up ${
          toastMessage.type === 'error' ? 'bg-[#3b171a] border-[#ffb4ab]/30 text-[#ffb4ab]' : 'bg-[#122e23] border-[#4edea3]/30 text-[#4edea3]'
        }`}>
          <span className="material-symbols-outlined text-[20px]">
            {toastMessage.type === 'error' ? 'error' : 'check_circle'}
          </span>
          <span className="font-semibold text-[14px]">{toastMessage.msg}</span>
        </div>
      )}

    </div>
  );
}
