import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useAdmin } from '../../context/AdminContext';

// ─── Constants ────────────────────────────────────────────────────────────────
const CATEGORIES = ['Business', 'Technical', 'Legal', 'Operations', 'Financial'];

const CATEGORY_COLORS = {
    Business:    { bg: '#dbeafe', text: '#1e40af' },
    Technical:   { bg: '#dcfce7', text: '#166534' },
    Legal:       { bg: '#fef9c3', text: '#854d0e' },
    Operations:  { bg: '#ede9fe', text: '#5b21b6' },
    Financial:   { bg: '#fce7f3', text: '#9d174d' },
};

// ─── Helpers ──────────────────────────────────────────────────────────────────
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 FileIcon({ mimeType }) {
    if (!mimeType) return <span>📄</span>;
    if (mimeType.includes('pdf'))                                   return <span>📕</span>;
    if (mimeType.includes('word') || mimeType.includes('document')) return <span>📘</span>;
    if (mimeType.includes('sheet') || mimeType.includes('excel'))   return <span>📗</span>;
    if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return <span>📙</span>;
    if (mimeType.includes('image'))                                 return <span>🖼️</span>;
    if (mimeType.includes('zip') || mimeType.includes('compressed')) return <span>📦</span>;
    return <span>📄</span>;
}

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,
            whiteSpace: 'nowrap',
        }}>
            {category || 'Uncategorized'}
        </span>
    );
}

// ─── Component ────────────────────────────────────────────────────────────────
export default function DocumentsPanel() {
    const { apiCall } = useAdmin();

    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);
    const [deleting,     setDeleting]     = useState(false);
    const [downloading,  setDownloading]  = useState(null);
    const [filterCat,    setFilterCat]    = useState('');
    const [search,       setSearch]       = useState('');

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

    // ─── Load ─────────────────────────────────────────────────────────────────
    const loadDocs = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const result = await apiCall('/api/documents/list', 'POST', {});
            if (result?.ok && Array.isArray(result.documents)) {
                setDocs(result.documents);
            } else {
                setError(result?.error || 'Failed to load documents');
            }
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [apiCall]);

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

    // ─── Upload ───────────────────────────────────────────────────────────────
    const handleUpload = async () => {
        if (!uploadFile) { setUploadError('Please select a file'); return; }
        setUploading(true);
        setUploadError(null);
        try {
            const formData = new FormData();
            formData.append('file', uploadFile);
            formData.append('category', uploadCat);
            formData.append('description', uploadDesc);

            // apiCall doesn't support FormData directly — use raw fetch with the
            // same auth header that apiCall would use
            const result = await apiCall('/api/documents', {
                method: 'POST',
                body: formData,
                // Don't set Content-Type — browser sets multipart boundary
                skipJson: true,
            });

            if (!result?.ok) throw new Error(result?.error || 'Upload failed');
            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 result = await apiCall(`/api/documents/${doc.docId}/download`, {
                rawResponse: true,
            });
            if (!result) throw new Error('No response');
            const blob = await result.blob();
            const url  = URL.createObjectURL(blob);
            const a    = document.createElement('a');
            a.href     = url;
            a.download = doc.docFileName;
            a.click();
            URL.revokeObjectURL(url);
        } catch (err) {
            alert(`Download failed: ${err.message}`);
        } finally {
            setDownloading(null);
        }
    };

    // ─── Delete ───────────────────────────────────────────────────────────────
    const handleDelete = async () => {
        if (!deleteId) return;
        setDeleting(true);
        try {
            const result = await apiCall(`/api/documents/${deleteId}`, { method: 'DELETE' });
            if (!result?.ok) throw new Error(result?.error || 'Delete failed');
            setDeleteId(null);
            await loadDocs();
        } catch (err) {
            alert(`Delete failed: ${err.message}`);
        } finally {
            setDeleting(false);
        }
    };

    // ─── Filter ───────────────────────────────────────────────────────────────
    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;
    });

    const categories = [...new Set(docs.map(d => d.docCategory).filter(Boolean))];

    // ─── Render ───────────────────────────────────────────────────────────────
    return (
        <div className="data-panel" style={{ maxWidth: 1000 }}>

            {/* Header */}
            <div className="panel-header">
                <div>
                    <h3 className="panel-title">Documents</h3>
                    <p className="panel-subtitle">
                        {loading ? 'Loading…' : `${docs.length} document${docs.length !== 1 ? 's' : ''}`}
                    </p>
                </div>
                <button
                    className="btn-action"
                    onClick={() => { setShowUpload(true); setUploadError(null); }}
                >
                    ↑ Upload Document
                </button>
            </div>

            {/* Upload form */}
            {showUpload && (
                <div className="admin-form" style={{ marginBottom: 20 }}>
                    <div className="form-title">Upload New Document</div>

                    {/* File picker */}
                    <div className="form-group">
                        <label className="form-label">File</label>
                        <div
                            style={{
                                border: `2px dashed ${uploadFile ? 'var(--accent)' : '#cbd5e1'}`,
                                borderRadius: 6, padding: '16px 20px', textAlign: 'center',
                                cursor: 'pointer', background: uploadFile ? '#eff6ff' : '#fff',
                                transition: 'all 0.2s',
                            }}
                            onClick={() => fileInputRef.current?.click()}
                        >
                            {uploadFile ? (
                                <div style={{ color: 'var(--accent)', fontWeight: 600 }}>
                                    📎 {uploadFile.name}
                                    <span style={{ color: '#64748b', fontWeight: 400, marginLeft: 8 }}>
                                        ({formatBytes(uploadFile.size)})
                                    </span>
                                </div>
                            ) : (
                                <div style={{ color: '#94a3b8' }}>
                                    Click to choose a file, or drag and drop
                                </div>
                            )}
                            <input
                                ref={fileInputRef}
                                type="file"
                                style={{ display: 'none' }}
                                onChange={e => setUploadFile(e.target.files?.[0] || null)}
                            />
                        </div>
                    </div>

                    {/* Category */}
                    <div className="form-group">
                        <label className="form-label">Category</label>
                        <select
                            className="form-select"
                            value={uploadCat}
                            onChange={e => setUploadCat(e.target.value)}
                        >
                            {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
                        </select>
                    </div>

                    {/* Description */}
                    <div className="form-group">
                        <label className="form-label">Description (optional)</label>
                        <input
                            className="form-input"
                            type="text"
                            placeholder="Brief description…"
                            value={uploadDesc}
                            onChange={e => setUploadDesc(e.target.value)}
                        />
                    </div>

                    {uploadError && (
                        <div className="error-message" style={{ marginBottom: 12 }}>{uploadError}</div>
                    )}

                    <div className="form-buttons">
                        <button
                            className="btn-action"
                            onClick={handleUpload}
                            disabled={uploading || !uploadFile}
                        >
                            {uploading ? 'Uploading…' : 'Upload'}
                        </button>
                        <button
                            className="btn-cancel"
                            onClick={() => { setShowUpload(false); setUploadFile(null); setUploadError(null); }}
                            disabled={uploading}
                        >
                            Cancel
                        </button>
                    </div>
                </div>
            )}

            {/* Filters */}
            {!loading && !error && docs.length > 0 && (
                <div className="filter-bar" style={{ marginBottom: 16, display: 'flex', gap: 10 }}>
                    <input
                        className="filter-input"
                        type="text"
                        placeholder="Search by name, description, uploader…"
                        value={search}
                        onChange={e => setSearch(e.target.value)}
                        style={{ flex: 1 }}
                    />
                    <select
                        className="filter-select"
                        value={filterCat}
                        onChange={e => setFilterCat(e.target.value)}
                        style={{ minWidth: 140 }}
                    >
                        <option value="">All Categories</option>
                        {categories.map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                    {(search || filterCat) && (
                        <button
                            className="btn-cancel"
                            onClick={() => { setSearch(''); setFilterCat(''); }}
                        >
                            Clear
                        </button>
                    )}
                </div>
            )}

            {/* States */}
            {loading && <div className="loading-message">Loading documents…</div>}
            {error   && <div className="error-message">{error}</div>}

            {/* Document list */}
            {!loading && !error && (
                <>
                    {filtered.length === 0 ? (
                        <div className="empty-state">
                            {docs.length === 0
                                ? 'No documents uploaded yet. Click Upload Document to add the first one.'
                                : 'No documents match your current filter.'}
                        </div>
                    ) : (
                        <table className="data-table">
                            <thead>
                                <tr>
                                    <th style={{ width: 36 }}></th>
                                    <th>File</th>
                                    <th>Category</th>
                                    <th>Size</th>
                                    <th>Uploaded By</th>
                                    <th>Date</th>
                                    <th style={{ width: 100 }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filtered.map(doc => (
                                    <tr key={doc.docId}>
                                        <td style={{ textAlign: 'center', fontSize: 18 }}>
                                            <FileIcon mimeType={doc.docMimeType} />
                                        </td>
                                        <td>
                                            <div style={{ fontWeight: 500, color: '#1e293b' }}>
                                                {doc.docFileName}
                                            </div>
                                            {doc.docDescription && (
                                                <div style={{ fontSize: 12, color: '#64748b', marginTop: 2 }}>
                                                    {doc.docDescription}
                                                </div>
                                            )}
                                        </td>
                                        <td><CategoryBadge category={doc.docCategory} /></td>
                                        <td style={{ color: '#64748b', fontSize: 13 }}>
                                            {formatBytes(doc.docFileSize)}
                                        </td>
                                        <td style={{ color: '#64748b', fontSize: 13 }}>
                                            {doc.docUploadedBy || '—'}
                                        </td>
                                        <td style={{ color: '#64748b', fontSize: 13 }}>
                                            {formatDate(doc.docUploadedAt)}
                                        </td>
                                        <td>
                                            <div style={{ display: 'flex', gap: 6 }}>
                                                <button
                                                    className="btn-icon"
                                                    title="Download"
                                                    disabled={downloading === doc.docId}
                                                    onClick={() => handleDownload(doc)}
                                                >
                                                    {downloading === doc.docId ? '…' : '↓'}
                                                </button>
                                                <button
                                                    className="btn-icon btn-icon-danger"
                                                    title="Delete"
                                                    onClick={() => setDeleteId(doc.docId)}
                                                >
                                                    ✕
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </>
            )}

            {/* Delete confirm dialog */}
            {deleteId && (
                <div className="modal-overlay">
                    <div className="modal-box">
                        <h4 className="modal-title">Delete Document?</h4>
                        <p className="modal-body">
                            This will permanently delete the document. This action cannot be undone.
                        </p>
                        <div className="modal-buttons">
                            <button
                                className="btn-danger"
                                onClick={handleDelete}
                                disabled={deleting}
                            >
                                {deleting ? 'Deleting…' : 'Delete'}
                            </button>
                            <button
                                className="btn-cancel"
                                onClick={() => setDeleteId(null)}
                                disabled={deleting}
                            >
                                Cancel
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
