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

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' },
};

const formatBytes = (b) => !b ? '—' : b < 1048576 ? `${(b/1024).toFixed(1)} KB` : `${(b/1048576).toFixed(1)} MB`;
const formatDate  = (iso) => !iso ? '—' : new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' });

function FileIcon({ mimeType = '' }) {
    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('image')) return <span>🖼️</span>;
    return <span>📄</span>;
}

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

export default function DocumentsPanel() {
    const { apiCall } = useAdmin();
    const [docs, setDocs]               = useState([]);
    const [loading, setLoading]         = useState(true);
    const [error, setError]             = useState(null);
    const [showUpload, setShowUpload]   = useState(false);
    const [uploadFile, setUploadFile]   = useState(null);
    const [uploadCat, setUploadCat]     = useState('Business');
    const [uploadDesc, setUploadDesc]   = useState('');
    const [uploading, setUploading]     = useState(false);
    const [uploadError, setUploadError] = useState(null);
    const [downloading, setDownloading] = useState(null);
    const [deleteId, setDeleteId]       = useState(null);
    const [deleting, setDeleting]       = useState(false);
    const fileInputRef = useRef();

    const load = useCallback(async () => {
        setLoading(true);
        setError(null);
        const res = await apiCall('/api/documents/list', 'POST', {});
        if (res?.ok !== false) {
            setDocs(Array.isArray(res?.documents) ? res.documents : []);
        } else {
            setError(res?.error || 'Failed to load documents');
        }
        setLoading(false);
    }, [apiCall]);

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

    const handleUpload = async () => {
        if (!uploadFile) { setUploadError('Please select a file'); return; }
        setUploading(true);
        setUploadError(null);
        try {
            const fd = new FormData();
            fd.append('file', uploadFile);
            fd.append('category', uploadCat);
            fd.append('description', uploadDesc);
            const res = await apiCall('/api/documents', { method: 'POST', body: fd });
            if (!res?.ok) throw new Error(res?.error || 'Upload failed');
            setShowUpload(false);
            setUploadFile(null);
            setUploadDesc('');
            await load();
        } catch (err) {
            setUploadError(err.message);
        } finally {
            setUploading(false);
        }
    };

    const handleDownload = async (doc) => {
        setDownloading(doc.docId);
        try {
            const res = await apiCall(`/api/documents/${doc.docId}/download`, { rawResponse: true });
            if (!res) throw new Error('No response');
            const blob = await res.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);
        }
    };

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

    return (
        <div className="data-panel" style={{ maxWidth: 900 }}>
            <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</button>
            </div>

            {showUpload && (
                <div className="admin-form" style={{ marginBottom: 20 }}>
                    <div className="form-title">Upload Document</div>
                    <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' }}
                            onClick={() => fileInputRef.current?.click()}>
                            {uploadFile
                                ? <div style={{ color: 'var(--accent)', fontWeight: 600 }}>📎 {uploadFile.name} <span style={{ color: '#64748b', fontWeight: 400 }}>({formatBytes(uploadFile.size)})</span></div>
                                : <div style={{ color: '#94a3b8' }}>Click to choose a file</div>}
                            <input ref={fileInputRef} type="file" style={{ display: 'none' }} onChange={e => setUploadFile(e.target.files?.[0] || null)} />
                        </div>
                    </div>
                    <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>
                    <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>
            )}

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

            {!loading && !error && docs.length === 0 && (
                <div className="empty-state">No documents yet. Upload your first document above.</div>
            )}

            {!loading && !error && docs.length > 0 && (
                <table className="data-table">
                    <thead>
                        <tr>
                            <th style={{ width: 36 }}></th>
                            <th>File</th>
                            <th>Category</th>
                            <th>Size</th>
                            <th>Uploaded</th>
                            <th style={{ width: 80 }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {docs.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 }}>{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>
            )}

            {deleteId && (
                <div className="modal-overlay">
                    <div className="modal-box">
                        <h4 className="modal-title">Delete Document?</h4>
                        <p className="modal-body">This will permanently remove the document.</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>
    );
}
