import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { MGMT_BASE } from '../auth/authConfig';

const CATEGORIES = ['Operations', 'Technical'];

const CATEGORY_COLORS = {
  Operations:  { bg: '#f3e8ff', text: '#6b21a8' },
  Technical:   { bg: '#dcfce7', text: '#166534' },
};

function formatBytes(bytes) {
  if (!bytes) return '—';
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1048576).toFixed(1)} MB`;
}

function formatDate(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleString('en-US', {
    month: 'short', day: 'numeric', year: 'numeric',
    hour: 'numeric', minute: '2-digit'
  });
}

function CategoryBadge({ category }) {
  const style = CATEGORY_COLORS[category] || { bg: '#f1f5f9', text: '#475569' };
  return (
    <span style={{
      background: style.bg, color: style.text,
      padding: '2px 8px', borderRadius: 12,
      fontSize: 11, fontWeight: 600, letterSpacing: 0.3
    }}>
      {category || 'Uncategorized'}
    </span>
  );
}

function FileIcon({ mimeType }) {
  if (!mimeType) return '📄';
  if (mimeType.includes('pdf'))  return '📕';
  if (mimeType.includes('word') || mimeType.includes('document')) return '📘';
  if (mimeType.includes('sheet') || mimeType.includes('excel'))   return '📗';
  if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return '📙';
  if (mimeType.includes('image')) return '🖼';
  if (mimeType.includes('text')) return '📄';
  if (mimeType.includes('zip') || mimeType.includes('compressed')) return '📦';
  return '📄';
}

export default function DocumentsPanel() {
  const { getIdToken, sessionUser } = useAuth();

  const [docs,        setDocs]        = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [error,       setError]       = useState(null);
  const [uploading,   setUploading]   = useState(false);
  const [uploadError, setUploadError] = useState(null);
  const [deleteId,    setDeleteId]    = useState(null);  // confirm dialog
  const [deleting,    setDeleting]    = useState(false);
  const [downloading, setDownloading] = useState(null);  // docId being downloaded
  const [filterCat,   setFilterCat]   = useState('');
  const [search,      setSearch]      = useState('');

  // Upload form state
  const [showUpload,  setShowUpload]  = useState(false);
  const [uploadFile,  setUploadFile]  = useState(null);
  const [uploadCat,   setUploadCat]   = useState('Technical');
  const [uploadDesc,  setUploadDesc]  = useState('');
  const fileInputRef = useRef();

  const authHeader = async () => {
    const token = await getIdToken();
    return token ? { Authorization: `Bearer ${token}` } : {};
  };

  // ─── Load documents ─────────────────────────────────────────────────────────

  const loadDocs = async () => {
    setLoading(true);
    setError(null);
    try {
      const resp = await fetch(`${MGMT_BASE}/api/documents/list`, {
        method: 'POST',
        headers: { ...await authHeader(), 'Content-Type': 'application/json' },
        body: JSON.stringify({ categories: CATEGORIES })
      });
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      const data = await resp.json();
      setDocs(data.documents || []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { loadDocs(); }, []);

  // ─── Upload ──────────────────────────────────────────────────────────────────

  const handleUpload = async () => {
    if (!uploadFile) return;
    setUploading(true);
    setUploadError(null);
    try {
      const form = new FormData();
      form.append('file',        uploadFile);
      form.append('category',    uploadCat);
      form.append('description', uploadDesc);
      form.append('uploadedBy',  sessionUser?.name || sessionUser?.email || 'Unknown');

      const resp = await fetch(`${MGMT_BASE}/api/documents`, {
        method: 'POST',
        headers: await authHeader(),   // no Content-Type — browser sets multipart boundary
        body: form
      });
      if (!resp.ok) {
        const txt = await resp.text();
        throw new Error(`HTTP ${resp.status}: ${txt}`);
      }
      setShowUpload(false);
      setUploadFile(null);
      setUploadDesc('');
      setUploadCat('Technical');
      await loadDocs();
    } catch (err) {
      setUploadError(err.message);
    } finally {
      setUploading(false);
    }
  };

  // ─── Download ────────────────────────────────────────────────────────────────

  const handleDownload = async (doc) => {
    setDownloading(doc.docId);
    try {
      const resp = await fetch(`${MGMT_BASE}/api/documents/${doc.docId}/download`, {
        headers: await authHeader()
      });
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      const blob = await resp.blob();
      const url  = URL.createObjectURL(blob);
      const a    = document.createElement('a');
      a.href = url;
      a.download = doc.docFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (err) {
      alert(`Download failed: ${err.message}`);
    } finally {
      setDownloading(null);
    }
  };

  // ─── Delete ──────────────────────────────────────────────────────────────────

  const handleDelete = async () => {
    if (!deleteId) return;
    setDeleting(true);
    try {
      const resp = await fetch(`${MGMT_BASE}/api/documents/${deleteId}`, {
        method: 'DELETE',
        headers: await authHeader()
      });
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      setDeleteId(null);
      await loadDocs();
    } catch (err) {
      alert(`Delete failed: ${err.message}`);
    } finally {
      setDeleting(false);
    }
  };

  // ─── Filtered list ────────────────────────────────────────────────────────────

  const filtered = docs.filter(d => {
    const matchCat  = !filterCat || d.docCategory === filterCat;
    const matchSrch = !search    ||
      d.docFileName.toLowerCase().includes(search.toLowerCase()) ||
      (d.docDescription || '').toLowerCase().includes(search.toLowerCase()) ||
      (d.docUploadedBy  || '').toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSrch;
  });

  // ─── Render ───────────────────────────────────────────────────────────────────

  return (
    <div className="content-panel" style={{ maxWidth: 1000 }}>

      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 16, color: '#1e293b' }}>Project Documents</h3>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: '#64748b' }}>
            {docs.length} document{docs.length !== 1 ? 's' : ''} stored
          </p>
        </div>
        <button
          className="token-btn token-btn-primary"
          onClick={() => { setShowUpload(true); setUploadError(null); }}
          style={{ display: 'flex', alignItems: 'center', gap: 6 }}
        >
          ↑ Upload Document
        </button>
      </div>

      {/* Upload form */}
      {showUpload && (
        <div style={{
          background: '#f8fafc', border: '1px solid #e2e8f0', borderRadius: 8,
          padding: 20, marginBottom: 20
        }}>
          <div style={{ fontWeight: 600, marginBottom: 14, color: '#1e293b' }}>Upload New Document</div>

          {/* File picker */}
          <div style={{ marginBottom: 12 }}>
            <label style={labelStyle}>File</label>
            <div
              style={{
                border: `2px dashed ${uploadFile ? '#0066cc' : '#cbd5e1'}`,
                borderRadius: 6, padding: '16px 20px', textAlign: 'center',
                cursor: 'pointer', background: uploadFile ? '#eff6ff' : '#fff',
                transition: 'all 0.2s'
              }}
              onClick={() => fileInputRef.current?.click()}
            >
              {uploadFile ? (
                <span style={{ color: '#0066cc', fontWeight: 500 }}>
                  {FileIcon(uploadFile.type)} {uploadFile.name} ({formatBytes(uploadFile.size)})
                </span>
              ) : (
                <span style={{ color: '#94a3b8' }}>Click to select a file</span>
              )}
              <input
                ref={fileInputRef}
                type="file"
                style={{ display: 'none' }}
                onChange={e => setUploadFile(e.target.files[0] || null)}
              />
            </div>
          </div>

          {/* Category + Description row */}
          <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 12, marginBottom: 12 }}>
            <div>
              <label style={labelStyle}>Category</label>
              <select
                value={uploadCat}
                onChange={e => setUploadCat(e.target.value)}
                style={inputStyle}
              >
                {CATEGORIES.map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Description (optional)</label>
              <input
                type="text"
                value={uploadDesc}
                onChange={e => setUploadDesc(e.target.value)}
                placeholder="Brief description of this document"
                style={inputStyle}
              />
            </div>
          </div>

          {uploadError && (
            <div style={{ color: '#dc2626', fontSize: 13, marginBottom: 10 }}>
              ⚠ {uploadError}
            </div>
          )}

          <div style={{ display: 'flex', gap: 8 }}>
            <button
              className="token-btn token-btn-primary"
              onClick={handleUpload}
              disabled={!uploadFile || uploading}
            >
              {uploading ? '⟳ Uploading…' : '↑ Upload'}
            </button>
            <button
              className="token-btn"
              onClick={() => { setShowUpload(false); setUploadFile(null); setUploadError(null); }}
              disabled={uploading}
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center' }}>
        <input
          type="text"
          placeholder="Search documents…"
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{ ...inputStyle, flex: 1, maxWidth: 280 }}
        />
        <select
          value={filterCat}
          onChange={e => setFilterCat(e.target.value)}
          style={{ ...inputStyle, width: 150 }}
        >
          <option value="">All Categories</option>
          {CATEGORIES.map(c => <option key={c}>{c}</option>)}
        </select>
        <button className="token-btn" onClick={loadDocs} title="Refresh">⟳</button>
      </div>

      {/* Content */}
      {loading ? (
        <div style={{ textAlign: 'center', padding: 40, color: '#94a3b8' }}>Loading documents…</div>
      ) : error ? (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <div style={{ color: '#dc2626', marginBottom: 8 }}>⚠ {error}</div>
          <button className="token-btn" onClick={loadDocs}>Retry</button>
        </div>
      ) : filtered.length === 0 ? (
        <div style={{
          textAlign: 'center', padding: 48,
          border: '1px dashed #e2e8f0', borderRadius: 8, color: '#94a3b8'
        }}>
          {docs.length === 0
            ? <>No documents yet. Click <strong>Upload Document</strong> to add the first one.</>
            : 'No documents match the current filter.'}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {filtered.map(doc => (
            <div
              key={doc.docId}
              style={{
                background: '#fff', border: '1px solid #e2e8f0', borderRadius: 8,
                padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14
              }}
            >
              {/* Icon */}
              <span style={{ fontSize: 24, flexShrink: 0 }}>
                {FileIcon(doc.docMimeType)}
              </span>

              {/* Main info */}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{
                    fontWeight: 600, fontSize: 14, color: '#1e293b',
                    overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'
                  }}>
                    {doc.docFileName}
                  </span>
                  <CategoryBadge category={doc.docCategory} />
                </div>
                {doc.docDescription && (
                  <div style={{ fontSize: 13, color: '#64748b', marginBottom: 4 }}>
                    {doc.docDescription}
                  </div>
                )}
                <div style={{ fontSize: 12, color: '#94a3b8', display: 'flex', gap: 16 }}>
                  <span>{formatBytes(doc.docFileSize)}</span>
                  <span>Uploaded by {doc.docUploadedBy || '—'}</span>
                  <span>{formatDate(doc.docUploadedAt)}</span>
                </div>
              </div>

              {/* Actions */}
              <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                <button
                  className="token-btn token-btn-primary"
                  onClick={() => handleDownload(doc)}
                  disabled={downloading === doc.docId}
                  style={{ fontSize: 12, padding: '5px 12px' }}
                >
                  {downloading === doc.docId ? '⟳' : '↓ Download'}
                </button>
                <button
                  className="token-btn"
                  onClick={() => setDeleteId(doc.docId)}
                  style={{ fontSize: 12, padding: '5px 12px', color: '#dc2626', borderColor: '#fecaca' }}
                >
                  🗑 Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Delete confirmation dialog */}
      {deleteId && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000
        }}>
          <div style={{
            background: '#fff', borderRadius: 10, padding: 28,
            maxWidth: 380, width: '90%', boxShadow: '0 20px 60px rgba(0,0,0,0.3)'
          }}>
            <div style={{ fontWeight: 700, fontSize: 16, marginBottom: 8 }}>Delete Document?</div>
            <div style={{ color: '#64748b', fontSize: 14, marginBottom: 20 }}>
              {(() => {
                const doc = docs.find(d => d.docId === deleteId);
                return doc
                  ? <>Are you sure you want to delete <strong>{doc.docFileName}</strong>? This cannot be undone.</>
                  : 'Are you sure you want to delete this document? This cannot be undone.';
              })()}
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <button
                className="token-btn"
                onClick={() => setDeleteId(null)}
                disabled={deleting}
              >
                Cancel
              </button>
              <button
                className="token-btn"
                onClick={handleDelete}
                disabled={deleting}
                style={{ background: '#dc2626', color: '#fff', borderColor: '#dc2626' }}
              >
                {deleting ? 'Deleting…' : 'Delete'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Shared input/label styles
const labelStyle = {
  display: 'block', fontSize: 12, fontWeight: 600,
  color: '#475569', marginBottom: 5, letterSpacing: 0.3
};

const inputStyle = {
  width: '100%', padding: '7px 10px',
  border: '1px solid #cbd5e1', borderRadius: 6,
  fontSize: 13, color: '#1e293b', background: '#fff',
  outline: 'none', boxSizing: 'border-box'
};
