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

/**
 * CampaignsPanel — Admin view of all initiatives across all clients.
 * Each initiative can have multiple channel campaigns (Google Ads, Meta, TikTok).
 * Includes filters: status, client, date range.
 */

const STATUSES = [
    { value: '',          label: 'All Statuses' },
    { value: 'draft',     label: 'Draft' },
    { value: 'staged',    label: 'Staged' },
    { value: 'active',    label: 'Active' },
    { value: 'paused',    label: 'Paused' },
    { value: 'completed', label: 'Completed' },
    { value: 'error',     label: 'Error' },
];

export default function CampaignsPanel() {
    const { data, apiCall, refresh } = useAdmin();

    // Filter state
    const [statusFilter, setStatusFilter] = useState('');
    const [clientFilter, setClientFilter] = useState('');
    const [dateFrom, setDateFrom] = useState('');
    const [dateTo, setDateTo] = useState('');

    // Client list for dropdown
    const [clients, setClients] = useState([]);

    // Filtered data (null = use initial data prop)
    const [filteredData, setFilteredData] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const hasFilters = statusFilter || clientFilter || dateFrom || dateTo;
    const activeData = hasFilters ? filteredData : data;
    const initiatives = activeData?.initiatives || [];
    const totalCount = activeData?.totalCount ?? initiatives.length;

    // Fetch client list for dropdown on mount
    useEffect(() => {
        const loadClients = async () => {
            const result = await apiCall('/api/admin/clients');
            if (result.ok && result.clients) {
                setClients(result.clients);
            }
        };
        loadClients();
    }, [apiCall]);

    // Fetch with filters
    const fetchFiltered = useCallback(async () => {
        setLoading(true);
        setError(null);

        const params = new URLSearchParams();
        if (statusFilter) params.set('status', statusFilter);
        if (clientFilter) params.set('clientId', clientFilter);
        if (dateFrom) params.set('dateFrom', dateFrom);
        if (dateTo) params.set('dateTo', dateTo);

        const qs = params.toString();
        const result = await apiCall(`/api/admin/campaigns${qs ? '?' + qs : ''}`);

        if (result.ok) {
            setFilteredData(result);
        } else {
            setError(result.error || 'Failed to load campaigns');
        }
        setLoading(false);
    }, [apiCall, statusFilter, clientFilter, dateFrom, dateTo]);

    // Refetch when filters change
    useEffect(() => {
        if (!hasFilters) {
            setFilteredData(null);
            return;
        }
        const timer = setTimeout(fetchFiltered, 200);
        return () => clearTimeout(timer);
    }, [hasFilters, fetchFiltered]);

    const clearFilters = () => {
        setStatusFilter('');
        setClientFilter('');
        setDateFrom('');
        setDateTo('');
        setFilteredData(null);
    };

    return (
        <div className="table-panel">
            <div className="panel-header">
                <h2>Campaigns ({totalCount})</h2>
                <button className="btn-action" onClick={hasFilters ? fetchFiltered : refresh}>
                    ↻ Refresh
                </button>
            </div>

            {/* ─── Filter Bar ──────────────────────────────────── */}
            <div className="filter-bar">
                <div className="filter-group">
                    <label className="filter-label">Status</label>
                    <select
                        className="filter-select"
                        value={statusFilter}
                        onChange={e => setStatusFilter(e.target.value)}
                    >
                        {STATUSES.map(s => (
                            <option key={s.value} value={s.value}>{s.label}</option>
                        ))}
                    </select>
                </div>

                <div className="filter-group">
                    <label className="filter-label">Client</label>
                    <select
                        className="filter-select"
                        value={clientFilter}
                        onChange={e => setClientFilter(e.target.value)}
                    >
                        <option value="">All Clients</option>
                        {clients.map(c => (
                            <option key={c.clientId} value={c.clientId}>
                                {c.clientName}
                            </option>
                        ))}
                    </select>
                </div>

                <div className="filter-group">
                    <label className="filter-label">From</label>
                    <input
                        type="date"
                        className="filter-input"
                        value={dateFrom}
                        onChange={e => setDateFrom(e.target.value)}
                    />
                </div>

                <div className="filter-group">
                    <label className="filter-label">To</label>
                    <input
                        type="date"
                        className="filter-input"
                        value={dateTo}
                        onChange={e => setDateTo(e.target.value)}
                    />
                </div>

                {hasFilters && (
                    <button className="btn-clear-filters" onClick={clearFilters}>
                        ✕ Clear
                    </button>
                )}
            </div>

            {/* ─── Loading / Error ─────────────────────────────── */}
            {loading && (
                <div style={{ padding: '20px', textAlign: 'center', color: '#6b7280' }}>
                    Loading...
                </div>
            )}

            {error && (
                <div className="error-message" style={{ margin: '12px 0' }}>
                    <strong>Error:</strong> {error}
                </div>
            )}

            {/* ─── Table ───────────────────────────────────────── */}
            {!loading && !error && initiatives.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-state-icon">{hasFilters ? '🔍' : '📢'}</div>
                    <h3>{hasFilters ? 'No matching campaigns' : 'No campaigns yet'}</h3>
                    <p>
                        {hasFilters
                            ? 'Try adjusting your filters to find what you\'re looking for.'
                            : 'Campaigns will appear here once clients create them through the wizard.'}
                    </p>
                </div>
            ) : !loading && !error && (
                <table className="data-table">
                    <thead>
                        <tr>
                            <th style={{ width: 28 }}></th>
                            <th>Client</th>
                            <th>Campaign</th>
                            <th>Objective</th>
                            <th>Budget</th>
                            <th>Channels</th>
                            <th>Status</th>
                            <th>Dates</th>
                        </tr>
                    </thead>
                    <tbody>
                        {initiatives.map(init => (
                            <InitiativeRow key={init.initiativeId} initiative={init} />
                        ))}
                    </tbody>
                </table>
            )}
        </div>
    );
}

// ─── Initiative row with expandable channel details ──────────────────────────

function InitiativeRow({ initiative }) {
    const [expanded, setExpanded] = useState(false);
    const channels = initiative.channels || [];

    return (
        <>
            <tr
                className="initiative-row"
                style={{ cursor: channels.length > 0 ? 'pointer' : 'default' }}
                onClick={() => channels.length > 0 && setExpanded(!expanded)}
            >
                <td style={{ textAlign: 'center', color: '#9ca3af', fontSize: 12 }}>
                    {channels.length > 0 && (
                        <span style={{
                            display: 'inline-block',
                            transition: 'transform 0.15s',
                            transform: expanded ? 'rotate(90deg)' : 'rotate(0deg)',
                        }}>▶</span>
                    )}
                </td>
                <td>{initiative.clientName || '—'}</td>
                <td style={{ fontWeight: 500 }}>{initiative.name || '—'}</td>
                <td>
                    <span className="objective-badge">
                        {formatObjective(initiative.objective)}
                    </span>
                </td>
                <td>{formatBudget(initiative.totalBudget, initiative.budgetPeriod)}</td>
                <td>
                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                        {channels.map((ch, i) => (
                            <ChannelBadge key={i} channel={ch} />
                        ))}
                        {channels.length === 0 && <span style={{ color: '#9ca3af' }}>—</span>}
                    </div>
                </td>
                <td><InitiativeStatusBadge status={initiative.status} /></td>
                <td style={{ fontSize: 13 }}>{formatDateRange(initiative.startDate, initiative.endDate)}</td>
            </tr>

            {/* Expanded channel detail rows */}
            {expanded && channels.map((ch, i) => (
                <tr key={`ch-${i}`} className="channel-detail-row">
                    <td></td>
                    <td colSpan="7">
                        <div className="channel-detail">
                            <ChannelIcon type={ch.channelType} />
                            <div className="channel-detail-info">
                                <span className="channel-detail-type">
                                    {formatChannelName(ch.channelType)}
                                </span>
                                <span className="channel-detail-alloc">
                                    {ch.allocationPct != null ? `${ch.allocationPct}%` : '—'}
                                    {ch.channelBudget != null && (
                                        <> · ${Number(ch.channelBudget).toLocaleString()}</>
                                    )}
                                </span>
                            </div>
                            <ChannelStatusBadge status={ch.status} />
                            {ch.externalCampaignId && (
                                <span className="channel-detail-ext" title={ch.externalCampaignId}>
                                    {truncateExtId(ch.externalCampaignId)}
                                </span>
                            )}
                            {ch.providerStatus && ch.providerStatus !== ch.status && (
                                <span className="channel-detail-provider">
                                    Provider: {ch.providerStatus}
                                </span>
                            )}
                        </div>
                    </td>
                </tr>
            ))}
        </>
    );
}

// ─── Badge components ────────────────────────────────────────────────────────

function ChannelBadge({ channel }) {
    const colors = {
        google_ads: { bg: '#e8f0fe', text: '#1a73e8', label: 'Google' },
        meta:       { bg: '#f3e8ff', text: '#7c3aed', label: 'Meta' },
        tiktok:     { bg: '#fff0f0', text: '#ff0050', label: 'TikTok' },
    };
    const c = colors[channel.channelType] || { bg: '#f3f4f6', text: '#6b7280', label: channel.channelType };
    const isError = channel.status === 'error';

    return (
        <span
            className="channel-badge"
            style={{
                background: isError ? '#fef2f2' : c.bg,
                color: isError ? '#dc2626' : c.text,
                opacity: isError ? 0.7 : 1,
            }}
            title={`${c.label} — ${channel.status} (${channel.allocationPct || 0}%)`}
        >
            {c.label}
            {channel.allocationPct != null && (
                <span style={{ opacity: 0.6, marginLeft: 3, fontSize: 10 }}>
                    {channel.allocationPct}%
                </span>
            )}
        </span>
    );
}

function InitiativeStatusBadge({ status }) {
    const s = (status || '').toLowerCase();
    let className = 'status-default';
    if (s === 'active' || s === 'launched') className = 'status-active';
    else if (s === 'staged' || s === 'pending' || s === 'draft') className = 'status-pending';
    else if (s === 'paused') className = 'status-warning';
    else if (s === 'error' || s === 'failed') className = 'status-error';
    else if (s === 'completed' || s === 'ended') className = 'status-inactive';

    return <span className={`status-badge ${className}`}>{status || '—'}</span>;
}

function ChannelStatusBadge({ status }) {
    const s = (status || '').toLowerCase();
    let className = 'status-default';
    if (s === 'active' || s === 'submitted') className = 'status-active';
    else if (s === 'pending' || s === 'draft' || s === 'pending_review') className = 'status-pending';
    else if (s === 'error') className = 'status-error';

    return <span className={`status-badge ${className}`} style={{ fontSize: 11 }}>{status || '—'}</span>;
}

function ChannelIcon({ type }) {
    const icons = {
        google_ads: '🔍',
        meta: '📘',
        tiktok: '🎵',
    };
    return <span style={{ fontSize: 16, marginRight: 6 }}>{icons[type] || '📢'}</span>;
}

// ─── Formatters ──────────────────────────────────────────────────────────────

function formatObjective(obj) {
    if (!obj) return '—';
    return obj.charAt(0).toUpperCase() + obj.slice(1).replace(/_/g, ' ');
}

function formatBudget(amount, period) {
    if (amount == null) return '—';
    const formatted = '$' + Number(amount).toLocaleString(undefined, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0,
    });
    if (period === 'monthly') return `${formatted}/mo`;
    if (period === 'daily') return `${formatted}/day`;
    return formatted;
}

function formatDateRange(start, end) {
    if (!start && !end) return '—';
    const fmt = (d) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '…';
    return `${fmt(start)} – ${fmt(end)}`;
}

function formatChannelName(type) {
    const names = {
        google_ads: 'Google Ads',
        meta: 'Meta Ads',
        tiktok: 'TikTok Ads',
    };
    return names[type] || type;
}

function truncateExtId(id) {
    if (!id) return '';
    const parts = id.split('/');
    if (parts.length >= 2) return `…/${parts.slice(-2).join('/')}`;
    return id.length > 20 ? '…' + id.slice(-18) : id;
}
