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

const SEV_STYLES = {
    critical: { border: '#fca5a5', bg: '#fff1f2', badge: { bg: '#fee2e2', color: '#991b1b' } },
    warning:  { border: '#fcd34d', bg: '#fffbeb', badge: { bg: '#fef9c3', color: '#854d0e' } },
    info:     { border: '#93c5fd', bg: '#eff6ff', badge: { bg: '#dbeafe', color: '#1e40af' } },
};

export default function RecommendationsPanel() {
    const { apiCall } = useAdmin();
    const [recs, setRecs]       = useState([]);
    const [loading, setLoading] = useState(true);
    const [acting, setActing]   = useState(null);

    const load = useCallback(async () => {
        setLoading(true);
        const res = await apiCall('/api/recommendations');
        setRecs(Array.isArray(res?.recommendations) ? res.recommendations :
                Array.isArray(res?.data) ? res.data : []);
        setLoading(false);
    }, [apiCall]);

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

    const dismiss = async (id) => {
        setActing(id);
        await apiCall(`/api/recommendations/${id}/dismiss`, 'POST');
        await load();
        setActing(null);
    };

    const resolve = async (id) => {
        setActing(id);
        await apiCall(`/api/recommendations/${id}/resolve`, 'POST');
        await load();
        setActing(null);
    };

    if (loading) return <div className="loading-message">Loading recommendations…</div>;

    if (recs.length === 0) {
        return (
            <div className="empty-state">
                <div style={{ fontSize: 36, marginBottom: 10 }}>✅</div>
                No active recommendations — your campaigns are looking good.
            </div>
        );
    }

    return (
        <div style={{ maxWidth: 800 }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, marginBottom: 20 }}>Recommendations</h2>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {recs.map((r, idx) => {
                    const id  = r.recommendationId || r.RecId || idx;
                    const sev = (r.severity || r.Severity || 'info').toLowerCase();
                    const st  = SEV_STYLES[sev] || SEV_STYLES.info;
                    return (
                        <div key={id} style={{ background: st.bg, border: `1px solid ${st.border}`, borderRadius: 10, padding: '16px 20px' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                                <div style={{ flex: 1 }}>
                                    <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 6 }}>
                                        <span style={{ background: st.badge.bg, color: st.badge.color, padding: '2px 8px', borderRadius: 10, fontSize: 11, fontWeight: 700, textTransform: 'uppercase' }}>
                                            {sev}
                                        </span>
                                        <span style={{ fontWeight: 600, fontSize: 14, color: '#0f172a' }}>
                                            {r.title || r.Title}
                                        </span>
                                    </div>
                                    <p style={{ margin: '0 0 8px', fontSize: 13, color: '#475569' }}>
                                        {r.description || r.Description}
                                    </p>
                                    {(r.recommendation || r.Recommendation) && (
                                        <p style={{ margin: 0, fontSize: 13, color: '#0f172a', fontWeight: 500 }}>
                                            💡 {r.recommendation || r.Recommendation}
                                        </p>
                                    )}
                                </div>
                                <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
                                    <button
                                        className="btn-action"
                                        style={{ fontSize: 12, padding: '6px 12px' }}
                                        disabled={acting === id}
                                        onClick={() => resolve(id)}
                                    >
                                        Resolve
                                    </button>
                                    <button
                                        className="btn-cancel"
                                        style={{ fontSize: 12, padding: '6px 12px' }}
                                        disabled={acting === id}
                                        onClick={() => dismiss(id)}
                                    >
                                        Dismiss
                                    </button>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
}
