'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  FileText,
  Plus,
  Calendar,
  Users,
  Upload,
  LogOut,
  Eye,
  Edit,
  Trash2,
  X,
  AlertCircle,
  CheckCircle,
  Mail
} from 'lucide-react';

interface DocketEntry {
  id: number;
  date: string;
  title: string;
  summary: string;
  notes: string | null;
  documents: any[];
  createdAt: string;
  updatedAt: string;
}

export default function AdminDashboard() {
  const [docketEntries, setDocketEntries] = useState<DocketEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingEntry, setEditingEntry] = useState<DocketEntry | null>(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [deletingEntry, setDeletingEntry] = useState<DocketEntry | null>(null);
  const [sendingNotification, setSendingNotification] = useState<number | null>(null);
  const router = useRouter();

  // Form states for add/edit modals
  const [formData, setFormData] = useState({
    date: '',
    title: '',
    summary: '',
    notes: ''
  });
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  useEffect(() => {
    // Check if user is authenticated
    const token = localStorage.getItem('adminToken');
    if (!token) {
      router.push('/admin');
      return;
    }

    fetchDocketEntries();
  }, [router]);

  const fetchDocketEntries = async () => {
    try {
      const response = await fetch('/api/docket-entries');
      if (!response.ok) {
        throw new Error('Failed to fetch docket entries');
      }
      const data = await response.json();
      setDocketEntries(data.entries || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('adminToken');
    router.push('/admin');
  };

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

  // Handler functions
  const handleAddEntry = () => {
    setFormData({ date: '', title: '', summary: '', notes: '' });
    setSelectedFile(null);
    setMessage(null);
    setShowAddModal(true);
  };

  const handleEditEntry = (entry: DocketEntry) => {
    setEditingEntry(entry);
    setFormData({
      date: entry.date ? entry.date.split('T')[0] || '' : '', // Convert to YYYY-MM-DD format
      title: entry.title || '',
      summary: entry.summary || '',
      notes: entry.notes || ''
    });
    setMessage(null);
    setShowEditModal(true);
  };

  const handleDeleteEntry = (entry: DocketEntry) => {
    setDeletingEntry(entry);
    setShowDeleteModal(true);
  };

  const handleSubmitEntry = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.date || !formData.title || !formData.summary) {
      setMessage({ type: 'error', text: 'Please fill in all required fields' });
      return;
    }

    setSubmitting(true);
    setMessage(null);

    try {
      const token = localStorage.getItem('adminToken');
      
      // First, create or update the docket entry
      const url = showEditModal && editingEntry 
        ? `/api/docket-entries/${editingEntry.id}`
        : '/api/docket-entries';
      
      const method = showEditModal ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`,
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (!response.ok) {
        setMessage({ type: 'error', text: data.message || 'Operation failed' });
        return;
      }

      // If we have a file, upload it (works for both add and edit)
      if (selectedFile && data.entry) {
        const uploadFormData = new FormData();
        uploadFormData.append('file', selectedFile);
        uploadFormData.append('docketEntryId', data.entry.id.toString());
        uploadFormData.append('title', selectedFile.name.replace('.pdf', ''));
        uploadFormData.append('summary', '');
        uploadFormData.append('notes', '');

        const uploadResponse = await fetch('/api/documents/upload', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
          },
          body: uploadFormData,
        });

        if (!uploadResponse.ok) {
          // Entry was created/updated but file upload failed
          setMessage({ 
            type: 'error', 
            text: showEditModal 
              ? 'Entry updated but document upload failed. You can upload the document later.'
              : 'Entry created but document upload failed. You can upload the document later.'
          });
          await fetchDocketEntries();
          setTimeout(() => {
            setShowAddModal(false);
            setShowEditModal(false);
            setEditingEntry(null);
            setSelectedFile(null);
          }, 3000);
          return;
        }
      }

      setMessage({ 
        type: 'success', 
        text: showEditModal 
          ? 'Entry updated successfully!' 
          : selectedFile 
            ? 'Entry created and document uploaded successfully!' 
            : 'Entry created successfully!'
      });
      
      await fetchDocketEntries(); // Refresh the list
      setTimeout(() => {
        setShowAddModal(false);
        setShowEditModal(false);
        setEditingEntry(null);
        setSelectedFile(null);
      }, 1500);

    } catch (error) {
      setMessage({ type: 'error', text: 'Network error. Please try again.' });
    } finally {
      setSubmitting(false);
    }
  };

  const handleConfirmDelete = async () => {
    if (!deletingEntry) return;

    setSubmitting(true);

    try {
      const token = localStorage.getItem('adminToken');
      const response = await fetch(`/api/docket-entries/${deletingEntry.id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      if (response.ok) {
        await fetchDocketEntries(); // Refresh the list
        setShowDeleteModal(false);
        setDeletingEntry(null);
      } else {
        const data = await response.json();
        alert(data.message || 'Delete failed');
      }
    } catch (error) {
      alert('Network error. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleSendNotification = async (entry: DocketEntry) => {
    if (sendingNotification === entry.id) return; // Prevent double-clicking

    setSendingNotification(entry.id);

    try {
      const token = localStorage.getItem('adminToken');
      const response = await fetch(`/api/notifications/send/${entry.id}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
      });

      const data = await response.json();

      if (response.ok) {
        alert(`✅ Email notification sent successfully to all subscribers!\n\n"${entry.title}"`);
      } else {
        alert(`❌ Failed to send email notification: ${data.message || 'Unknown error'}`);
      }
    } catch (error) {
      alert('❌ Network error. Please try again.');
    } finally {
      setSendingNotification(null);
    }
  };


  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', backgroundColor: '#6E6362' }}>
      {/* Header */}
      <header style={{
        backgroundColor: 'rgba(57, 64, 83, 0.95)',
        boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
        borderBottom: '1px solid #4E4A59'
      }}>
        <div style={{ maxWidth: '80rem', margin: '0 auto', padding: '0 1rem' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '1.5rem 0' }}>
            <div>
              <h1 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: 'white' }}>Admin Dashboard</h1>
              <p style={{ fontSize: '0.875rem', color: '#7CAE7A' }}>Manage court docket entries and documents</p>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
              <button
                onClick={() => window.open('/', '_blank')}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  padding: '0.5rem 1rem',
                  color: '#7CAE7A',
                  backgroundColor: 'transparent',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                <Eye style={{ width: '1rem', height: '1rem' }} />
                View Public Site
              </button>
              <button
                onClick={handleLogout}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  padding: '0.5rem 1rem',
                  backgroundColor: '#dc2626',
                  color: 'white',
                  borderRadius: '0.375rem',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                <LogOut style={{ width: '1rem', height: '1rem' }} />
                Logout
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main style={{ maxWidth: '80rem', margin: '0 auto', padding: '0 1rem 2rem 1rem' }}>
        {/* Stats Cards */}
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', 
          gap: '1.5rem', 
          marginBottom: '2rem',
          marginTop: '2rem'
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <FileText style={{ height: '2rem', width: '2rem', color: '#394053' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Total Entries</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>{docketEntries.length}</p>
              </div>
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <Upload style={{ height: '2rem', width: '2rem', color: '#7CAE7A' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Total Documents</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>
                  {docketEntries.reduce((total, entry) => total + entry.documents.length, 0)}
                </p>
              </div>
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ flexShrink: 0 }}>
                <Calendar style={{ height: '2rem', width: '2rem', color: '#839073' }} />
              </div>
              <div style={{ marginLeft: '1rem' }}>
                <p style={{ fontSize: '0.875rem', fontWeight: '500', color: '#6b7280' }}>Last Updated</p>
                <p style={{ fontSize: '1.5rem', fontWeight: '600', color: '#111827' }}>
                  {docketEntries.length > 0 && docketEntries[0] ? formatDate(docketEntries[0].date) : 'N/A'}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
          <h2 style={{ fontSize: '1.125rem', fontWeight: '600', color: 'white' }}>Docket Entries</h2>
          <div style={{ display: 'flex', gap: '0.5rem' }}>
            <button 
              onClick={handleAddEntry}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '0.5rem',
                padding: '0.5rem 1rem',
                backgroundColor: '#394053',
                color: 'white',
                borderRadius: '0.375rem',
                border: 'none',
                cursor: 'pointer'
              }}>
              <Plus style={{ width: '1rem', height: '1rem' }} />
              Add New Entry
            </button>
          </div>
        </div>

        {/* Docket Entries Cards */}
        <div>
          {error ? (
            <div style={{
              backgroundColor: 'white',
              borderRadius: '0.5rem',
              boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
              padding: '1.5rem',
              textAlign: 'center'
            }}>
              <p style={{ color: '#dc2626', marginBottom: '1rem' }}>{error}</p>
              <button
                onClick={fetchDocketEntries}
                style={{
                  padding: '0.5rem 1rem',
                  backgroundColor: '#394053',
                  color: 'white',
                  borderRadius: '0.375rem',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                Try Again
              </button>
            </div>
          ) : docketEntries.length === 0 ? (
            <div style={{
              backgroundColor: 'white',
              borderRadius: '0.5rem',
              boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
              padding: '3rem 1.5rem',
              textAlign: 'center'
            }}>
              <FileText style={{ width: '3rem', height: '3rem', margin: '0 auto 1rem auto', color: '#d1d5db' }} />
              <p style={{ color: '#6b7280', marginBottom: '1rem' }}>No docket entries found.</p>
              <button style={{
                padding: '0.5rem 1rem',
                backgroundColor: '#394053',
                color: 'white',
                borderRadius: '0.375rem',
                border: 'none',
                cursor: 'pointer'
              }}>
                Create First Entry
              </button>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
              {docketEntries.map((entry, index) => (
                <div 
                  key={entry.id}
                  style={{
                    backgroundColor: 'white',
                    borderRadius: '0.5rem',
                    boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
                    border: '2px solid #e5e7eb',
                    overflow: 'hidden'
                  }}
                >
                  <div style={{ padding: '1.5rem' }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '1rem' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                        <div style={{
                          width: '2.5rem',
                          height: '2.5rem',
                          borderRadius: '50%',
                          backgroundColor: '#394053',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          color: 'white',
                          fontWeight: 'bold',
                          fontSize: '1rem',
                          flexShrink: 0
                        }}>
                          {index + 1}
                        </div>
                        <div>
                          <div style={{ fontSize: '0.875rem', color: '#6b7280', marginBottom: '0.25rem' }}>
                            {formatDate(entry.date)}
                          </div>
                          <h3 style={{ fontSize: '1.125rem', fontWeight: '600', color: '#111827', marginBottom: '0.25rem' }}>
                            {entry.title}
                          </h3>
                          <span style={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            padding: '0.25rem 0.75rem',
                            borderRadius: '9999px',
                            fontSize: '0.75rem',
                            fontWeight: '500',
                            backgroundColor: '#839073',
                            color: 'white'
                          }}>
                            {entry.documents.length} documents
                          </span>
                        </div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                        <button
                          onClick={() => handleSendNotification(entry)}
                          disabled={sendingNotification === entry.id}
                          style={{
                            padding: '0.5rem',
                            backgroundColor: sendingNotification === entry.id ? '#9ca3af' : '#16a34a',
                            color: 'white',
                            borderRadius: '0.375rem',
                            border: 'none',
                            cursor: sendingNotification === entry.id ? 'not-allowed' : 'pointer',
                            display: 'flex',
                            alignItems: 'center'
                          }}
                          title="Send email notification to all subscribers"
                        >
                          <Mail style={{ width: '1rem', height: '1rem' }} />
                        </button>
                        <button 
                          onClick={() => handleEditEntry(entry)}
                          style={{
                            padding: '0.5rem',
                            backgroundColor: '#394053',
                            color: 'white',
                            borderRadius: '0.375rem',
                            border: 'none',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center'
                          }}>
                          <Edit style={{ width: '1rem', height: '1rem' }} />
                        </button>
                        <button 
                          onClick={() => handleDeleteEntry(entry)}
                          style={{
                            padding: '0.5rem',
                            backgroundColor: '#dc2626',
                            color: 'white',
                            borderRadius: '0.375rem',
                            border: 'none',
                            cursor: 'pointer',
                            display: 'flex',
                            alignItems: 'center'
                          }}>
                          <Trash2 style={{ width: '1rem', height: '1rem' }} />
                        </button>
                      </div>
                    </div>
                    <div style={{ paddingLeft: '3.5rem' }}>
                      <p style={{ color: '#6b7280', lineHeight: '1.5' }}>
                        {entry.summary}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Quick Actions */}
        <div style={{ 
          marginTop: '2rem', 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', 
          gap: '1.5rem' 
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            border: '2px solid #e5e7eb',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '1rem' }}>
              <Plus style={{ width: '1.5rem', height: '1.5rem', color: '#394053', marginRight: '0.75rem' }} />
              <h3 style={{ fontSize: '1.125rem', fontWeight: '500', color: '#111827' }}>Add Entry</h3>
            </div>
            <p style={{ fontSize: '0.875rem', color: '#6b7280', marginBottom: '1rem' }}>
              Create a new docket entry with documents
            </p>
            <button 
              onClick={handleAddEntry}
              style={{
                width: '100%',
                padding: '0.5rem 1rem',
                backgroundColor: '#394053',
                color: 'white',
                borderRadius: '0.375rem',
                border: 'none',
                cursor: 'pointer',
                fontSize: '0.875rem',
                fontWeight: '500'
              }}>
              Create Entry
            </button>
          </div>


          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
            border: '2px solid #e5e7eb',
            padding: '1.5rem'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: '1rem' }}>
              <Users style={{ width: '1.5rem', height: '1.5rem', color: '#839073', marginRight: '0.75rem' }} />
              <h3 style={{ fontSize: '1.125rem', fontWeight: '500', color: '#111827' }}>Subscribers</h3>
            </div>
            <p style={{ fontSize: '0.875rem', color: '#6b7280', marginBottom: '1rem' }}>
              Manage email subscriptions
            </p>
            <button
              onClick={() => router.push('/admin/subscribers')}
              style={{
                width: '100%',
                padding: '0.5rem 1rem',
                backgroundColor: '#839073',
                color: 'white',
                borderRadius: '0.375rem',
                border: 'none',
                cursor: 'pointer',
                fontSize: '0.875rem',
                fontWeight: '500'
              }}
            >
              View Subscribers
            </button>
          </div>
        </div>
      </main>

      {/* Add/Edit Entry Modal */}
      {(showAddModal || showEditModal) && (
        <div style={{
          position: 'fixed',
          inset: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 50
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
            width: '100%',
            maxWidth: '36rem',
            margin: '0 1rem',
            maxHeight: '90vh',
            overflow: 'auto'
          }}>
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              padding: '1.5rem',
              borderBottom: '1px solid #e5e7eb'
            }}>
              <h3 style={{ fontSize: '1.125rem', fontWeight: '600', color: '#111827' }}>
                {showEditModal ? 'Edit Docket Entry' : 'Add New Docket Entry'}
              </h3>
              <button
                onClick={() => {
                  setShowAddModal(false);
                  setShowEditModal(false);
                  setEditingEntry(null);
                  setMessage(null);
                }}
                style={{
                  color: '#6b7280',
                  backgroundColor: 'transparent',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                <X style={{ width: '1.5rem', height: '1.5rem' }} />
              </button>
            </div>

            <form onSubmit={handleSubmitEntry} style={{ padding: '2rem' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
                <div>
                  <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                    Filing Date *
                  </label>
                  <input
                    type="date"
                    value={formData.date}
                    onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                    style={{
                      width: '100%',
                      padding: '0.5rem 0.75rem',
                      border: '1px solid #d1d5db',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      outline: 'none'
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = '#7CAE7A';
                      e.target.style.boxShadow = '0 0 0 2px rgba(124, 174, 122, 0.2)';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = '#d1d5db';
                      e.target.style.boxShadow = 'none';
                    }}
                    required
                  />
                  <p style={{ fontSize: '0.75rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    Date when the document was filed with the court
                  </p>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                    Court Filing Title *
                  </label>
                  <textarea
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    rows={3}
                    style={{
                      width: '100%',
                      padding: '0.5rem 0.75rem',
                      border: '1px solid #d1d5db',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      outline: 'none',
                      resize: 'vertical'
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = '#7CAE7A';
                      e.target.style.boxShadow = '0 0 0 2px rgba(124, 174, 122, 0.2)';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = '#d1d5db';
                      e.target.style.boxShadow = 'none';
                    }}
                    placeholder="e.g., Motion for Preliminary Injunction (Filed By Kragh, Elizabeth on behalf of Kragh, Elizabeth)"
                    required
                  />
                  <p style={{ fontSize: '0.75rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    Copy and paste the exact text from the Montana court docket "TEXT" field
                  </p>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                    Brief Summary *
                  </label>
                  <textarea
                    value={formData.summary}
                    onChange={(e) => setFormData({ ...formData, summary: e.target.value })}
                    rows={4}
                    style={{
                      width: '100%',
                      padding: '0.5rem 0.75rem',
                      border: '1px solid #d1d5db',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      outline: 'none',
                      resize: 'vertical'
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = '#7CAE7A';
                      e.target.style.boxShadow = '0 0 0 2px rgba(124, 174, 122, 0.2)';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = '#d1d5db';
                      e.target.style.boxShadow = 'none';
                    }}
                    placeholder="Provide a clear description of the filed briefs and their significance to the case"
                    required
                  />
                  <p style={{ fontSize: '0.75rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    Manual description of the filed briefs for public understanding
                  </p>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                    Additional Notes & Resources
                  </label>
                  <textarea
                    value={formData.notes}
                    onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                    rows={4}
                    style={{
                      width: '100%',
                      padding: '0.5rem 0.75rem',
                      border: '1px solid #d1d5db',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      outline: 'none',
                      resize: 'vertical'
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = '#7CAE7A';
                      e.target.style.boxShadow = '0 0 0 2px rgba(124, 174, 122, 0.2)';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = '#d1d5db';
                      e.target.style.boxShadow = 'none';
                    }}
                    placeholder="Additional information, context, or links to ASL interpretation videos"
                  />
                  <p style={{ fontSize: '0.75rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    Optional field for additional context, links to ASL vlogs, or other accessibility resources
                  </p>
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                    {showEditModal && editingEntry && editingEntry.documents.length > 0 
                      ? 'Replace Document (Optional)' 
                      : 'Attach Document (Optional)'}
                  </label>
                  <input
                    type="file"
                    accept=".pdf"
                    onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
                    style={{
                      width: '100%',
                      padding: '0.5rem 0.75rem',
                      border: '1px solid #d1d5db',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      outline: 'none',
                      backgroundColor: 'white'
                    }}
                    onFocus={(e) => {
                      e.target.style.borderColor = '#7CAE7A';
                      e.target.style.boxShadow = '0 0 0 2px rgba(124, 174, 122, 0.2)';
                    }}
                    onBlur={(e) => {
                      e.target.style.borderColor = '#d1d5db';
                      e.target.style.boxShadow = 'none';
                    }}
                  />
                  <p style={{ fontSize: '0.75rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    {showEditModal && editingEntry && editingEntry.documents.length > 0 
                      ? 'Optional: Upload a new PDF to replace the existing document(s).' 
                      : 'Optional: Upload a PDF document to attach to this docket entry.'}
                  </p>
                  {selectedFile && (
                    <div style={{
                      marginTop: '0.5rem',
                      padding: '0.5rem',
                      backgroundColor: '#f0f9f0',
                      border: '1px solid #7CAE7A',
                      borderRadius: '0.375rem',
                      fontSize: '0.875rem',
                      color: '#166534'
                    }}>
                      Selected: {selectedFile.name}
                    </div>
                  )}
                  {showEditModal && editingEntry && editingEntry.documents.length > 0 && (
                    <div style={{
                      marginTop: '0.5rem',
                      padding: '0.5rem',
                      backgroundColor: '#fef3c7',
                      border: '1px solid #f59e0b',
                      borderRadius: '0.375rem',
                      fontSize: '0.75rem',
                      color: '#92400e'
                    }}>
                      Current entry has {editingEntry.documents.length} document(s). Uploading a new file will add it to the existing documents.
                    </div>
                  )}
                </div>

                {message && (
                  <div style={{
                    borderRadius: '0.375rem',
                    padding: '1rem',
                    backgroundColor: message.type === 'success' ? '#f0f9f0' : '#fef2f2',
                    border: `1px solid ${message.type === 'success' ? '#7CAE7A' : '#dc2626'}`
                  }}>
                    <div style={{ display: 'flex' }}>
                      <div style={{ flexShrink: 0 }}>
                        {message.type === 'success' ? (
                          <CheckCircle style={{ height: '1.25rem', width: '1.25rem', color: '#7CAE7A' }} />
                        ) : (
                          <AlertCircle style={{ height: '1.25rem', width: '1.25rem', color: '#dc2626' }} />
                        )}
                      </div>
                      <div style={{ marginLeft: '0.75rem' }}>
                        <p style={{
                          fontSize: '0.875rem',
                          fontWeight: '500',
                          color: message.type === 'success' ? '#166534' : '#991b1b'
                        }}>
                          {message.text}
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '1rem' }}>
                  <button
                    type="button"
                    onClick={() => {
                      setShowAddModal(false);
                      setShowEditModal(false);
                      setEditingEntry(null);
                      setMessage(null);
                    }}
                    style={{
                      padding: '0.5rem 1rem',
                      border: '1px solid #4E4A59',
                      borderRadius: '0.375rem',
                      color: '#374151',
                      backgroundColor: 'white',
                      cursor: 'pointer',
                      fontSize: '0.875rem'
                    }}
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={submitting}
                    style={{
                      padding: '0.5rem 1.5rem',
                      backgroundColor: submitting ? '#9ca3af' : '#7CAE7A',
                      color: 'white',
                      borderRadius: '0.375rem',
                      border: 'none',
                      cursor: submitting ? 'not-allowed' : 'pointer',
                      fontSize: '0.875rem',
                      fontWeight: '500'
                    }}
                  >
                    {submitting ? 'Saving...' : (showEditModal ? 'Update Entry' : 'Create Entry')}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteModal && deletingEntry && (
        <div style={{
          position: 'fixed',
          inset: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 50
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '0.5rem',
            boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
            width: '100%',
            maxWidth: '28rem',
            margin: '0 1rem'
          }}>
            <div style={{ padding: '1.5rem' }}>
              <div style={{ display: 'flex', alignItems: 'center', marginBottom: '1rem' }}>
                <div style={{
                  width: '3rem',
                  height: '3rem',
                  borderRadius: '50%',
                  backgroundColor: '#fef2f2',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  marginRight: '1rem'
                }}>
                  <AlertCircle style={{ width: '1.5rem', height: '1.5rem', color: '#dc2626' }} />
                </div>
                <div>
                  <h3 style={{ fontSize: '1.125rem', fontWeight: '600', color: '#111827' }}>
                    Delete Docket Entry
                  </h3>
                  <p style={{ fontSize: '0.875rem', color: '#6b7280', marginTop: '0.25rem' }}>
                    This action cannot be undone.
                  </p>
                </div>
              </div>

              <p style={{ fontSize: '0.875rem', color: '#374151', marginBottom: '1.5rem' }}>
                Are you sure you want to delete "{deletingEntry.title}"? This will also delete all associated documents.
              </p>

              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem' }}>
                <button
                  onClick={() => {
                    setShowDeleteModal(false);
                    setDeletingEntry(null);
                  }}
                  style={{
                    padding: '0.5rem 1rem',
                    border: '1px solid #d1d5db',
                    borderRadius: '0.375rem',
                    color: '#374151',
                    backgroundColor: 'white',
                    cursor: 'pointer',
                    fontSize: '0.875rem'
                  }}
                >
                  Cancel
                </button>
                <button
                  onClick={handleConfirmDelete}
                  disabled={submitting}
                  style={{
                    padding: '0.5rem 1rem',
                    backgroundColor: submitting ? '#9ca3af' : '#dc2626',
                    color: 'white',
                    borderRadius: '0.375rem',
                    border: 'none',
                    cursor: submitting ? 'not-allowed' : 'pointer',
                    fontSize: '0.875rem',
                    fontWeight: '500'
                  }}
                >
                  {submitting ? 'Deleting...' : 'Delete Entry'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
