'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Upload, FileText, ArrowLeft, AlertCircle, CheckCircle } from 'lucide-react';

interface DocketEntry {
  id: number;
  title: string;
  date: string;
  summary: string;
}

export default function UploadDocument() {
  const [docketEntries, setDocketEntries] = useState<DocketEntry[]>([]);
  const [selectedEntry, setSelectedEntry] = useState<number | null>(null);
  const [file, setFile] = useState<File | null>(null);
  const [title, setTitle] = useState('');
  const [uploading, setUploading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const router = useRouter();

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

    fetchDocketEntries();

    // Check if entryId is provided in URL params
    const urlParams = new URLSearchParams(window.location.search);
    const entryId = urlParams.get('entryId');
    if (entryId) {
      setSelectedEntry(Number(entryId));
    }
  }, [router]);

  const fetchDocketEntries = async () => {
    try {
      const response = await fetch('/api/docket-entries');
      if (!response.ok) throw new Error('Failed to fetch entries');
      const data = await response.json();
      setDocketEntries(data.entries || []);
    } catch (error) {
      setMessage({ type: 'error', text: 'Failed to load docket entries' });
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (selectedFile.type !== 'application/pdf') {
        setMessage({ type: 'error', text: 'Only PDF files are allowed' });
        return;
      }
      if (selectedFile.size > 10 * 1024 * 1024) { // 10MB
        setMessage({ type: 'error', text: 'File size must be less than 10MB' });
        return;
      }
      setFile(selectedFile);
      setMessage(null);
      
      // Auto-fill title from filename if empty
      if (!title) {
        const filename = selectedFile.name.replace('.pdf', '');
        setTitle(filename);
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!file || !selectedEntry) {
      setMessage({ type: 'error', text: 'Please select a file and docket entry' });
      return;
    }

    setUploading(true);
    setMessage(null);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('docketEntryId', selectedEntry.toString());
      formData.append('title', file.name.replace('.pdf', '')); // Use filename as title
      formData.append('summary', '');
      formData.append('notes', '');

      const token = localStorage.getItem('adminToken');
      const response = await fetch('/api/documents/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
        },
        body: formData,
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({ type: 'success', text: 'Document uploaded successfully!' });
        // Reset form
        setFile(null);
        setTitle('');
        setSelectedEntry(null);
        // Reset file input
        const fileInput = document.getElementById('file-upload') as HTMLInputElement;
        if (fileInput) fileInput.value = '';
      } else {
        setMessage({ type: 'error', text: data.message || 'Upload failed' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: 'Network error. Please try again.' });
    } finally {
      setUploading(false);
    }
  };

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

  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', flexDirection: 'column', alignItems: 'center', padding: '1.5rem 0', textAlign: 'center' }}>
            <div style={{ alignSelf: 'flex-start', marginBottom: '1rem' }}>
              <button
                onClick={() => router.push('/admin/dashboard')}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  color: '#7CAE7A',
                  backgroundColor: 'transparent',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                <ArrowLeft style={{ width: '1rem', height: '1rem' }} />
                Back to Dashboard
              </button>
            </div>
            <div style={{ textAlign: 'center' }}>
              <h1 style={{ fontSize: '1.5rem', fontWeight: 'bold', color: 'white', marginBottom: '0.5rem' }}>Upload Document</h1>
              <p style={{ fontSize: '0.875rem', color: '#7CAE7A' }}>Add a PDF document to a docket entry</p>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main style={{ maxWidth: '64rem', margin: '0 auto', padding: '0 1rem 2rem 1rem' }}>
        <div style={{
          backgroundColor: 'white',
          boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
          borderRadius: '0.5rem',
          border: '2px solid #e5e7eb',
          marginTop: '2rem'
        }}>
          <div style={{
            padding: '1.5rem',
            borderBottom: '1px solid #4E4A59'
          }}>
            <h2 style={{ fontSize: '1.125rem', fontWeight: '600', color: '#394053' }}>Document Upload</h2>
          </div>

          <form onSubmit={handleSubmit} style={{ padding: '1.5rem', display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
            {/* Docket Entry Selection or Display */}
            <div>
              <label style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                {selectedEntry && new URLSearchParams(window.location.search).get('entryId') ? 'Uploading to Docket Entry' : 'Select Docket Entry *'}
              </label>
              {selectedEntry && new URLSearchParams(window.location.search).get('entryId') ? (
                // Show selected entry info (read-only)
                <div style={{
                  width: '100%',
                  padding: '0.75rem',
                  border: '2px solid #7CAE7A',
                  borderRadius: '0.375rem',
                  backgroundColor: '#f0f9f0',
                  fontSize: '0.875rem',
                  color: '#166534'
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <div style={{
                      width: '1.5rem',
                      height: '1.5rem',
                      borderRadius: '50%',
                      backgroundColor: '#7CAE7A',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      color: 'white',
                      fontSize: '0.75rem',
                      fontWeight: 'bold'
                    }}>
                      ✓
                    </div>
                    <div>
                      {docketEntries.find(entry => entry.id === selectedEntry) && (
                        <span>
                          {formatDate(docketEntries.find(entry => entry.id === selectedEntry)!.date)} - {docketEntries.find(entry => entry.id === selectedEntry)!.title}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              ) : (
                // Show dropdown for manual selection
                <select
                  id="docket-entry"
                  value={selectedEntry || ''}
                  onChange={(e) => setSelectedEntry(Number(e.target.value) || null)}
                  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
                >
                  <option value="">Choose a docket entry...</option>
                  {docketEntries.map((entry) => (
                    <option key={entry.id} value={entry.id}>
                      {formatDate(entry.date)} - {entry.title}
                    </option>
                  ))}
                </select>
              )}
            </div>

            {/* File Upload */}
            <div>
              <label htmlFor="file-upload" style={{ display: 'block', fontSize: '0.875rem', fontWeight: '500', color: '#374151', marginBottom: '0.5rem' }}>
                PDF Document *
              </label>
              <div style={{
                marginTop: '0.25rem',
                display: 'flex',
                justifyContent: 'center',
                padding: '1.25rem 1.5rem',
                border: '2px dashed #839073',
                borderRadius: '0.375rem',
                transition: 'border-color 0.2s',
                cursor: 'pointer'
              }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = '#7CAE7A'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = '#839073'}
              >
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.25rem', textAlign: 'center' }}>
                  <Upload style={{ margin: '0 auto', height: '3rem', width: '3rem', color: '#839073' }} />
                  <div style={{ fontSize: '0.875rem', color: '#6b7280', textAlign: 'center' }}>
                    <label
                      htmlFor="file-upload"
                      style={{
                        position: 'relative',
                        cursor: 'pointer',
                        backgroundColor: 'white',
                        borderRadius: '0.375rem',
                        fontWeight: '500',
                        color: '#7CAE7A',
                        outline: 'none'
                      }}
                    >
                      <span>Upload a file</span>
                      <input
                        id="file-upload"
                        name="file-upload"
                        type="file"
                        accept=".pdf"
                        onChange={handleFileChange}
                        style={{ position: 'absolute', width: '1px', height: '1px', padding: '0', margin: '-1px', overflow: 'hidden', clip: 'rect(0, 0, 0, 0)', whiteSpace: 'nowrap', border: '0' }}
                        required
                      />
                    </label>
                    <span> or drag and drop</span>
                  </div>
                  <p style={{ fontSize: '0.75rem', color: '#6b7280' }}>PDF up to 10MB</p>
                  {file && (
                    <div style={{ marginTop: '0.5rem', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem', fontSize: '0.875rem', color: '#7CAE7A' }}>
                      <FileText style={{ width: '1rem', height: '1rem' }} />
                      {file.name}
                    </div>
                  )}
                </div>
              </div>
            </div>


            {/* Message */}
            {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>
            )}

            {/* Submit Button */}
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem' }}>
              <button
                type="button"
                onClick={() => router.push('/admin/dashboard')}
                style={{
                  padding: '0.5rem 1rem',
                  border: '1px solid #4E4A59',
                  borderRadius: '0.375rem',
                  color: '#374151',
                  backgroundColor: 'white',
                  cursor: 'pointer',
                  fontSize: '0.875rem'
                }}
                onMouseEnter={(e) => ((e.target as HTMLElement).style.backgroundColor = '#f9fafb')}
                onMouseLeave={(e) => ((e.target as HTMLElement).style.backgroundColor = 'white')}
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={uploading || !file || !selectedEntry}
                style={{
                  padding: '0.5rem 1.5rem',
                  backgroundColor: uploading || !file || !selectedEntry ? '#9ca3af' : '#7CAE7A',
                  color: 'white',
                  borderRadius: '0.375rem',
                  border: 'none',
                  cursor: uploading || !file || !selectedEntry ? 'not-allowed' : 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '0.5rem',
                  fontSize: '0.875rem',
                  fontWeight: '500'
                }}
                onMouseEnter={(e) => {
                  if (!uploading && file && selectedEntry) {
                    (e.target as HTMLElement).style.backgroundColor = '#6b9c69';
                  }
                }}
                onMouseLeave={(e) => {
                  if (!uploading && file && selectedEntry) {
                    (e.target as HTMLElement).style.backgroundColor = '#7CAE7A';
                  }
                }}
              >
                {uploading ? (
                  <>
                    <div style={{
                      width: '1rem',
                      height: '1rem',
                      border: '2px solid white',
                      borderTop: '2px solid transparent',
                      borderRadius: '50%',
                      animation: 'spin 1s linear infinite'
                    }}></div>
                    Uploading...
                  </>
                ) : (
                  <>
                    <Upload style={{ width: '1rem', height: '1rem' }} />
                    Upload Document
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
}
