import React, { useState, useEffect } from 'react';
import { Loader, AlertCircle, Upload } from 'lucide-react';
import {
    ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ReferenceLine,
    PieChart, Pie, Cell, ResponsiveContainer
} from 'recharts';
import BulkUploadModal from './BulkUploadModal';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';
const TEAL = '#14B8A6';
const EMERALD = '#10B981';
const AMBER = '#F59E0B';
const RED = '#EF4444';

// ---------------------------------------------------------------------------
// VCL Stats Bar (Task 11)
// ---------------------------------------------------------------------------
function VCLStatsBar({ stats }) {
    if (!stats) return null;

    const cards = [
        { label: 'Total Devices', value: stats.total_devices, color: '#CBD5E1' },
        { label: 'In-Scope', value: stats.in_scope, color: '#94A3B8' },
        { label: 'Compliant', value: stats.compliant, color: EMERALD },
        { label: 'Non-Compliant', value: stats.non_compliant, color: RED },
        { label: 'Remediations Req.', value: stats.remediations_required, color: AMBER },
        { label: 'Current %', value: `${stats.compliance_pct}%`, color: TEAL },
        { label: 'Target %', value: `${stats.target_pct}%`, color: AMBER },
    ];

    return (
        <div style={{ display: 'flex', gap: '0.75rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
            {cards.map(card => (
                <div key={card.label} style={{
                    flex: '1 1 0',
                    minWidth: '120px',
                    background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
                    border: '1px solid rgba(20,184,166,0.15)',
                    borderRadius: '0.5rem',
                    padding: '0.875rem 1rem',
                    textAlign: 'center',
                }}>
                    <div style={{
                        fontFamily: 'monospace', fontSize: '1.25rem', fontWeight: '700',
                        color: card.color, marginBottom: '0.25rem',
                    }}>
                        {card.value}
                    </div>
                    <div style={{
                        fontSize: '0.62rem', fontFamily: 'monospace', textTransform: 'uppercase',
                        letterSpacing: '0.08em', color: '#475569',
                    }}>
                        {card.label}
                    </div>
                </div>
            ))}
        </div>
    );
}

// ---------------------------------------------------------------------------
// Compliance Overview Trend Chart (Task 12)
// ---------------------------------------------------------------------------
function ComplianceOverviewChart({ trendData, targetPct }) {
    if (!trendData || trendData.length === 0) {
        return (
            <div style={{ padding: '2rem', textAlign: 'center', color: '#475569', fontFamily: 'monospace', fontSize: '0.8rem' }}>
                No trend data available
            </div>
        );
    }

    const AXIS_STYLE = { fill: '#64748B', fontSize: '0.68rem', fontFamily: 'monospace' };

    return (
        <div style={{
            background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
            border: '1px solid rgba(20,184,166,0.15)',
            borderRadius: '0.5rem',
            padding: '1.25rem',
            marginBottom: '1.5rem',
        }}>
            <div style={{
                fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase',
                letterSpacing: '0.1em', color: '#475569', marginBottom: '1rem',
            }}>
                Compliance Overview
            </div>
            <ResponsiveContainer width="100%" height={280}>
                <ComposedChart data={trendData}>
                    <CartesianGrid stroke="rgba(255,255,255,0.05)" strokeDasharray="3 3" />
                    <XAxis dataKey="month" tick={AXIS_STYLE} />
                    <YAxis yAxisId="count" tick={AXIS_STYLE} />
                    <YAxis yAxisId="pct" orientation="right" domain={[0, 100]} unit="%" tick={AXIS_STYLE} />
                    <Tooltip
                        contentStyle={{
                            background: 'rgba(15,23,42,0.95)',
                            border: '1px solid rgba(20,184,166,0.3)',
                            borderRadius: '0.375rem',
                            fontFamily: 'monospace',
                            fontSize: '0.72rem',
                            color: '#CBD5E1',
                        }}
                    />
                    <Legend wrapperStyle={{ fontFamily: 'monospace', fontSize: '0.68rem', color: '#94A3B8' }} />
                    <Bar yAxisId="count" dataKey="compliant_count" fill={EMERALD} fillOpacity={0.7} name="Compliant" />
                    <Line yAxisId="pct" dataKey="compliance_pct" stroke={TEAL} strokeWidth={2} dot={{ r: 3 }} name="Actual %" />
                    {trendData.length >= 2 && (
                        <Line yAxisId="pct" dataKey="forecast_pct" stroke={TEAL} strokeWidth={2} strokeDasharray="5 3" dot={false} name="Forecast %" />
                    )}
                    <ReferenceLine yAxisId="pct" y={targetPct || 95} stroke={AMBER} strokeDasharray="4 4" label={{ value: 'Target', fill: AMBER, fontSize: '0.68rem', fontFamily: 'monospace' }} />
                </ComposedChart>
            </ResponsiveContainer>
        </div>
    );
}

// ---------------------------------------------------------------------------
// Non-Compliant Assets Donut Chart (Task 13)
// ---------------------------------------------------------------------------
function NonCompliantDonutChart({ donut }) {
    if (!donut) return null;

    const data = [
        { name: 'Blocked', count: donut.blocked?.count || 0, pct: donut.blocked?.pct || 0 },
        { name: 'In-Progress', count: donut.in_progress?.count || 0, pct: donut.in_progress?.pct || 0 },
    ].filter(d => d.count > 0);

    if (data.length === 0) {
        return (
            <div style={{ padding: '2rem', textAlign: 'center', color: '#475569', fontFamily: 'monospace', fontSize: '0.8rem' }}>
                No non-compliant assets
            </div>
        );
    }

    const COLORS = [RED, AMBER];

    const renderLabel = ({ name, count, pct }) => `${name}: ${count} (${pct}%)`;

    return (
        <div style={{
            background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
            border: '1px solid rgba(20,184,166,0.15)',
            borderRadius: '0.5rem',
            padding: '1.25rem',
        }}>
            <div style={{
                fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase',
                letterSpacing: '0.1em', color: '#475569', marginBottom: '1rem',
            }}>
                Status of Non-Compliant Assets
            </div>
            <ResponsiveContainer width="100%" height={220}>
                <PieChart>
                    <Pie
                        data={data}
                        innerRadius={60}
                        outerRadius={90}
                        dataKey="count"
                        nameKey="name"
                        label={renderLabel}
                        labelLine={{ stroke: '#475569' }}
                    >
                        {data.map((entry, index) => (
                            <Cell key={entry.name} fill={COLORS[index % COLORS.length]} />
                        ))}
                    </Pie>
                    <Legend wrapperStyle={{ fontFamily: 'monospace', fontSize: '0.68rem', color: '#94A3B8' }} />
                    <Tooltip
                        contentStyle={{
                            background: 'rgba(15,23,42,0.95)',
                            border: '1px solid rgba(20,184,166,0.3)',
                            borderRadius: '0.375rem',
                            fontFamily: 'monospace',
                            fontSize: '0.72rem',
                            color: '#CBD5E1',
                        }}
                    />
                </PieChart>
            </ResponsiveContainer>
        </div>
    );
}

// ---------------------------------------------------------------------------
// Inline Editable Cell Component
// ---------------------------------------------------------------------------
function EditableCell({ value, type, onSave, style, placeholder }) {
    const [editing, setEditing] = useState(false);
    const [draft, setDraft] = useState(value || '');

    useEffect(() => {
        setDraft(value || '');
    }, [value]);

    const handleSave = () => {
        setEditing(false);
        const newValue = type === 'number' ? (draft === '' ? 0 : parseInt(draft, 10)) : draft;
        if (newValue !== value) {
            onSave(newValue);
        }
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            handleSave();
        } else if (e.key === 'Escape') {
            setDraft(value || '');
            setEditing(false);
        }
    };

    if (editing) {
        const inputStyle = {
            background: 'rgba(15,23,42,0.9)',
            border: `1px solid ${TEAL}`,
            borderRadius: '0.25rem',
            color: '#CBD5E1',
            fontFamily: 'monospace',
            fontSize: '0.7rem',
            padding: '0.25rem 0.4rem',
            width: '100%',
            outline: 'none',
            boxShadow: `0 0 0 1px ${TEAL}40`,
        };

        return (
            <input
                type={type || 'text'}
                value={draft}
                onChange={e => setDraft(e.target.value)}
                onBlur={handleSave}
                onKeyDown={handleKeyDown}
                style={{ ...inputStyle, ...style }}
                autoFocus
                placeholder={placeholder}
            />
        );
    }

    const displayValue = type === 'number' ? (value || 0) : (value || '');
    return (
        <span
            onClick={() => setEditing(true)}
            style={{
                cursor: 'pointer',
                display: 'inline-block',
                minWidth: '30px',
                minHeight: '1.2em',
                padding: '0.1rem 0.25rem',
                borderRadius: '0.2rem',
                transition: 'background 0.15s',
                ...(style || {}),
            }}
            onMouseEnter={e => { e.currentTarget.style.background = 'rgba(20,184,166,0.08)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; }}
            title="Click to edit"
        >
            {displayValue || <span style={{ color: '#475569', fontStyle: 'italic' }}>{placeholder || '—'}</span>}
        </span>
    );
}

// ---------------------------------------------------------------------------
// Heavy Hitters Table (Task 14)
// ---------------------------------------------------------------------------
function HeavyHittersTable({ heavyHitters, onMetadataUpdate }) {
    if (!heavyHitters || heavyHitters.length === 0) {
        return (
            <div style={{ padding: '1.5rem', textAlign: 'center', color: '#475569', fontFamily: 'monospace', fontSize: '0.8rem' }}>
                No heavy hitters data
            </div>
        );
    }

    const headerStyle = {
        padding: '0.625rem 0.75rem',
        fontSize: '0.62rem', fontFamily: 'monospace', textTransform: 'uppercase',
        letterSpacing: '0.08em', color: TEAL, fontWeight: '600',
        borderBottom: '1px solid rgba(20,184,166,0.2)',
        textAlign: 'left',
    };

    const cellStyle = {
        padding: '0.625rem 0.75rem',
        fontSize: '0.75rem', fontFamily: 'monospace', color: '#CBD5E1',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
    };

    return (
        <div style={{
            background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
            border: '1px solid rgba(20,184,166,0.15)',
            borderRadius: '0.5rem',
            overflow: 'hidden',
            marginBottom: '1.5rem',
        }}>
            <div style={{
                padding: '1rem 1.25rem 0.5rem',
                fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase',
                letterSpacing: '0.1em', color: '#475569',
            }}>
                Heavy Hitters
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                    <tr>
                        <th style={headerStyle}>Vertical / Team</th>
                        <th style={{ ...headerStyle, textAlign: 'right' }}>Non-Compliant</th>
                        <th style={headerStyle}>Compliance Date</th>
                        <th style={headerStyle}>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    {heavyHitters.map((row, i) => (
                        <tr key={i}>
                            <td style={cellStyle}>
                                <div>{row.vertical}</div>
                                {row.team && <div style={{ fontSize: '0.65rem', color: '#64748B' }}>{row.team}</div>}
                            </td>
                            <td style={{ ...cellStyle, textAlign: 'right', color: RED, fontWeight: '600' }}>
                                {row.non_compliant}
                            </td>
                            <td style={cellStyle}>
                                <EditableCell
                                    value={row.compliance_date || ''}
                                    type="text"
                                    placeholder="e.g. Q3 2026"
                                    onSave={(val) => onMetadataUpdate && onMetadataUpdate(row.vertical || row.team, { compliance_date: val || null })}
                                />
                            </td>
                            <td style={{ ...cellStyle, color: '#94A3B8', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                <EditableCell
                                    value={row.notes || ''}
                                    type="text"
                                    placeholder="Add notes"
                                    onSave={(val) => onMetadataUpdate && onMetadataUpdate(row.vertical || row.team, { notes: val })}
                                />
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

// ---------------------------------------------------------------------------
// Vertical Breakdown Table (Task 15)
// ---------------------------------------------------------------------------
function VerticalBreakdownTable({ verticalBreakdown, onMetadataUpdate }) {
    if (!verticalBreakdown || verticalBreakdown.length === 0) {
        return (
            <div style={{ padding: '1.5rem', textAlign: 'center', color: '#475569', fontFamily: 'monospace', fontSize: '0.8rem' }}>
                No vertical breakdown data
            </div>
        );
    }

    // Collect all actual burndown months and forecast burndown months
    const allActualMonths = new Set();
    const allForecastMonths = new Set();
    verticalBreakdown.forEach(row => {
        if (row.actual_burndown) Object.keys(row.actual_burndown).forEach(m => allActualMonths.add(m));
        if (row.forecast_burndown) Object.keys(row.forecast_burndown).forEach(m => allForecastMonths.add(m));
    });
    const actualMonths = [...allActualMonths].sort();
    const forecastMonths = [...allForecastMonths].sort();

    const headerStyle = {
        padding: '0.5rem 0.5rem',
        fontSize: '0.58rem', fontFamily: 'monospace', textTransform: 'uppercase',
        letterSpacing: '0.06em', color: TEAL, fontWeight: '600',
        borderBottom: '1px solid rgba(20,184,166,0.2)',
        textAlign: 'left', whiteSpace: 'nowrap',
    };

    const cellStyle = {
        padding: '0.5rem 0.5rem',
        fontSize: '0.7rem', fontFamily: 'monospace', color: '#CBD5E1',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        whiteSpace: 'nowrap',
    };

    return (
        <div style={{
            background: 'linear-gradient(135deg, rgba(30,41,59,0.95) 0%, rgba(15,23,42,0.98) 100%)',
            border: '1px solid rgba(20,184,166,0.15)',
            borderRadius: '0.5rem',
            overflow: 'auto',
            marginBottom: '1.5rem',
        }}>
            <div style={{
                padding: '1rem 1.25rem 0.5rem',
                fontSize: '0.68rem', fontFamily: 'monospace', textTransform: 'uppercase',
                letterSpacing: '0.1em', color: '#475569',
            }}>
                Vertical Breakdown
            </div>
            <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '900px' }}>
                    <thead>
                        <tr>
                            <th style={headerStyle}>Vertical</th>
                            <th style={{ ...headerStyle, textAlign: 'right' }}>Compliance %</th>
                            <th style={headerStyle}>Team</th>
                            <th style={{ ...headerStyle, textAlign: 'right' }}>Non-Compliant</th>
                            {actualMonths.map(m => (
                                <th key={`a-${m}`} style={{ ...headerStyle, textAlign: 'right', color: '#94A3B8' }}>
                                    {m.slice(5)}
                                </th>
                            ))}
                            {forecastMonths.map(m => (
                                <th key={`f-${m}`} style={{ ...headerStyle, textAlign: 'right', color: AMBER }}>
                                    {m.slice(5)}*
                                </th>
                            ))}
                            <th style={{ ...headerStyle, textAlign: 'right' }}>Blockers</th>
                            <th style={{ ...headerStyle, textAlign: 'right' }}>RAs</th>
                            <th style={headerStyle}>Notes</th>
                        </tr>
                    </thead>
                    <tbody>
                        {verticalBreakdown.map((row, i) => (
                            <tr key={i}>
                                <td style={cellStyle}>{row.vertical}</td>
                                <td style={{ ...cellStyle, textAlign: 'right', color: TEAL }}>
                                    {row.compliance_pct}%
                                </td>
                                <td style={{ ...cellStyle, color: '#94A3B8' }}>{row.team || ''}</td>
                                <td style={{ ...cellStyle, textAlign: 'right', color: row.non_compliant > 0 ? RED : '#64748B' }}>
                                    {row.non_compliant}
                                </td>
                                {actualMonths.map(m => (
                                    <td key={`a-${m}`} style={{ ...cellStyle, textAlign: 'right', color: '#94A3B8' }}>
                                        {(row.actual_burndown && row.actual_burndown[m]) || 0}
                                    </td>
                                ))}
                                {forecastMonths.map(m => (
                                    <td key={`f-${m}`} style={{ ...cellStyle, textAlign: 'right', color: AMBER }}>
                                        {(row.forecast_burndown && row.forecast_burndown[m]) || 0}
                                    </td>
                                ))}
                                <td style={{ ...cellStyle, textAlign: 'right', color: row.blockers > 0 ? RED : '#64748B' }}>
                                    {row.blockers || 0}
                                </td>
                                <td style={{ ...cellStyle, textAlign: 'right', color: '#94A3B8' }}>
                                    <EditableCell
                                        value={row.risk_acceptances || 0}
                                        type="number"
                                        placeholder="0"
                                        onSave={(val) => onMetadataUpdate && onMetadataUpdate(row.vertical || row.team, { risk_acceptances: val })}
                                        style={{ textAlign: 'right', width: '50px' }}
                                    />
                                </td>
                                <td style={{ ...cellStyle, color: '#94A3B8', maxWidth: '150px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                                    <EditableCell
                                        value={row.notes || ''}
                                        type="text"
                                        placeholder="Add notes"
                                        onSave={(val) => onMetadataUpdate && onMetadataUpdate(row.vertical || row.team, { notes: val })}
                                    />
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ---------------------------------------------------------------------------
// VCL Report Page (Task 10)
// ---------------------------------------------------------------------------
export default function VCLReportPage() {
    const [stats, setStats] = useState(null);
    const [trendData, setTrendData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showBulkUpload, setShowBulkUpload] = useState(false);

    const handleMetadataUpdate = async (team, fields) => {
        try {
            const res = await fetch(`${API_BASE}/compliance/vcl/vertical-metadata/${encodeURIComponent(team)}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify(fields),
            });
            if (!res.ok) {
                const data = await res.json().catch(() => ({}));
                console.error('Failed to update metadata:', data.error || res.statusText);
                return;
            }
            // Optimistically update local state
            setStats(prev => {
                if (!prev) return prev;
                const updated = { ...prev };
                if (updated.heavy_hitters) {
                    updated.heavy_hitters = updated.heavy_hitters.map(hh =>
                        (hh.vertical === team || hh.team === team) ? { ...hh, ...fields } : hh
                    );
                }
                if (updated.vertical_breakdown) {
                    updated.vertical_breakdown = updated.vertical_breakdown.map(vb =>
                        (vb.vertical === team || vb.team === team) ? { ...vb, ...fields } : vb
                    );
                }
                return updated;
            });
        } catch (err) {
            console.error('Metadata update error:', err);
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            setLoading(true);
            setError(null);
            try {
                const [statsRes, trendRes] = await Promise.all([
                    fetch(`${API_BASE}/compliance/vcl/stats`, { credentials: 'include' }),
                    fetch(`${API_BASE}/compliance/vcl/trend`, { credentials: 'include' }),
                ]);

                if (!statsRes.ok) throw new Error('Failed to load VCL stats');
                if (!trendRes.ok) throw new Error('Failed to load VCL trend data');

                const statsData = await statsRes.json();
                const trendDataJson = await trendRes.json();

                setStats(statsData);
                setTrendData(trendDataJson.months || []);
            } catch (err) {
                setError(err.message);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

    if (loading) {
        return (
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '4rem' }}>
                <Loader style={{ width: '32px', height: '32px', color: TEAL, animation: 'spin 1s linear infinite' }} />
            </div>
        );
    }

    if (error) {
        return (
            <div style={{ padding: '2rem', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem', color: '#F87171', fontSize: '0.85rem', fontFamily: 'monospace' }}>
                <AlertCircle style={{ width: '18px', height: '18px' }} />
                {error}
            </div>
        );
    }

    return (
        <div style={{ marginTop: '1rem' }}>
            {/* Page sub-header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.25rem' }}>
                <div style={{
                    fontSize: '0.72rem', fontFamily: 'monospace', textTransform: 'uppercase',
                    letterSpacing: '0.1em', color: '#475569',
                }}>
                    VCL Executive Report
                </div>
                <button
                    onClick={() => setShowBulkUpload(true)}
                    style={{
                        display: 'flex', alignItems: 'center', gap: '0.4rem',
                        padding: '0.5rem 1rem',
                        background: `${TEAL}15`,
                        border: `1px solid ${TEAL}60`,
                        borderRadius: '0.375rem',
                        color: TEAL,
                        fontSize: '0.72rem', fontFamily: 'monospace', fontWeight: '600',
                        textTransform: 'uppercase', letterSpacing: '0.05em',
                        cursor: 'pointer', transition: 'all 0.15s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = `${TEAL}25`; e.currentTarget.style.borderColor = TEAL; }}
                    onMouseLeave={e => { e.currentTarget.style.background = `${TEAL}15`; e.currentTarget.style.borderColor = `${TEAL}60`; }}
                >
                    <Upload style={{ width: '14px', height: '14px' }} />
                    Bulk Upload
                </button>
            </div>

            {/* Stats Bar */}
            <VCLStatsBar stats={stats?.stats} />

            {/* Charts row */}
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '1.5rem', marginBottom: '1.5rem' }}>
                <ComplianceOverviewChart trendData={trendData} targetPct={stats?.stats?.target_pct} />
                <NonCompliantDonutChart donut={stats?.donut} />
            </div>

            {/* Heavy Hitters */}
            <HeavyHittersTable heavyHitters={stats?.heavy_hitters} onMetadataUpdate={handleMetadataUpdate} />

            {/* Vertical Breakdown */}
            <VerticalBreakdownTable verticalBreakdown={stats?.vertical_breakdown} onMetadataUpdate={handleMetadataUpdate} />

            {/* Bulk Upload Modal */}
            {showBulkUpload && (
                <BulkUploadModal onClose={() => setShowBulkUpload(false)} />
            )}
        </div>
    );
}
