import React, { useState, useEffect, useCallback, useRef } 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 ──────────────────────────────────────────────────────────────────
const 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`;
};

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

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

    // Client picker
    const [clients, setClients]               = useState([]);
    const [clientsLoading, setClientsLoading] = useState(true);
    const [selectedClientId, setSelectedClientId]     = useState('');
    const [selectedClientName, setSelectedClientName] = useState('');

    // Document list
    const [docs, setDocs]           = useState([]);
    const [loading, setLoading]     = useState(false);
    const [error, setError]         = useState(null);
    const [downloading, setDownloading] = useState(null);
    const [deleteId, setDeleteId]   = useState(null);
    const [deleting, setDeleting]   = useState(false);

    // Upload form
    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 fileInputRef = useRef();

    // ── Load client list ──────────────────────────────────────────────────────
    useEffect(() => {
        (async () => {
            setClientsLoading(true);
            try {
                const result = await apiCall('/api/admin/clients/list', 'POST', { page: 1, pageSize: 200 });
                if (result?.ok && Array.isArray(result.clients)) {
                    setClients(result.clients);
                }
            } catch { /* ignore */ }
            finally { setClientsLoading(false); }
        })();
    }, [apiCall]);

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

    const handleClientChange = (e) => {
        const cid  = e.target.value;
        const name = clients.find(c => (c.cltId || c.clientId) === cid)?.cltName || cid;
        setSelectedClientId(cid);
        setSelectedClientName(name);
        setDocs([]);
        setError(null);
        setShowUpload(false);
        if (cid) loadDocs(cid);
    };

    // ── Upload ────────────────────────────────────────────────────────────────
    const handleUpload = async () => {
        if (!uploadFile) { setUploadError('Please select a file'); return; }
        if (!selectedClientId) { setUploadError('No client selected'); return; }

        setUploading(true);
        setUploadError(null);
        try {
            const formData = new FormData();
            formData.append('file', uploadFile);
            formData.append('clientId', selectedClientId);
            formData.append('category', uploadCat);
            formData.append('description', uploadDesc);

            const result = await apiCall('/api/admin/client-documents/upload', {
                method: 'POST',
                body: formData,
            });

            if (!result?.ok) throw new Error(result?.error || result?.message || 'Upload failed');

            setShowUpload(false);
            setUploadFile(null);
            setUploadDesc('');
            setUploadCat('Business');
            await loadDocs(selectedClientId);
        } catch (err) {
            setUploadError(err.message);
        } finally {
            setUploading(false);
        }
    };

    // ── Download ──────────────────────────────────────────────────────────────
    const handleDownload = async (doc) => {
        setDownloading(doc.docId);
        try {
            const result = await apiCall(`/api/admin/client-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/admin/client-documents/${deleteId}`, { method: 'DELETE' });
            if (!result?.ok) throw new Error(result?.error || result?.message || 'Delete failed');
            setDeleteId(null);
            await loadDocs(selectedClientId);
        } catch (err) {
            alert(`Delete failed: ${err.message}`);
        } finally {
            setDeleting(false);
        }
    };

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

            {/* Header */}
            <div className="panel-header">
                <div>
                    <h3 className="panel-title">Client Documents</h3>
                    <p className="panel-subtitle">Documents shared with or uploaded by clients</p>
                </div>
                {selectedClientId && (
                    <button
                        className="btn-action"
                        onClick={() => { setShowUpload(true); setUploadError(null); }}
                    >
                        ↑ Upload for {selectedClientName}
                    </button>
                )}
            </div>

            {/* Client picker */}
            <div style={{ marginBottom: 20 }}>
                <label className="form-label" style={{ marginBottom: 6 }}>Client</label>
                <select
                    className="form-select"
                    value={selectedClientId}
                    onChange={handleClientChange}
                    disabled={clientsLoading}
                    style={{ maxWidth: 320 }}
                >
                    <option value="">
                        {clientsLoading ? 'Loading…' : '— select a client —'}
                    </option>
                    {clients.map(c => {
                        const id   = c.cltId   || c.clientId;
                        const name = c.cltName || c.name;
                        return <option key={id} value={id}>{name}</option>;
                    })}
                </select>
            </div>

            {/* Upload form */}
            {showUpload && (
                <div className="admin-form" style={{ marginBottom: 20 }}>
                    <div className="form-title">Upload Document for {selectedClientName}</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',
                                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</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>
            )}

            {/* Empty prompt */}
            {!selectedClientId && (
                <div className="empty-state">Select a client to view their documents.</div>
            )}

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

            {/* Document list */}
            {selectedClientId && !loading && !error && (
                <>
                    {docs.length === 0 ? (
                        <div className="empty-state">
                            No documents for {selectedClientName} yet. Click Upload to add the first one.
                        </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>
                                {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 }}>{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 */}
            {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. This 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>
    );
}
