import React, { useMemo, useState, useEffect, useCallback } from 'react';
import * as XLSX from 'xlsx';
import { ProductForecastData, FilterState } from '../types';
import { DownloadIcon } from './Icons';
import { StockBadge } from './StockBadge';
import { InColumnStockFilter } from './InColumnStockFilter';
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    LineChart, Line, Legend, ComposedChart, Area
} from 'recharts';

interface ForecastViewProps {
    data: ProductForecastData[];
    filters: FilterState;
    top50Ranking?: {
        eu: Map<string, number>;
        uk: Map<string, number>;
    };
    stockMap?: Map<string, number>;
    stockFilter: string[];
    onStockFilterChange: (newFilters: string[]) => void;
}

const MONTH_ORDER = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// Top 50 Badge Component (reused logic)
// Top 50 Badge Component (matched to image)
const Top50Badge: React.FC<{ rank: number; label: string; theme?: 'amber' | 'indigo' | 'blue' }> = ({ rank, label }) => {
    return (
        <div className="flex items-center gap-1.5 px-2 py-1 rounded bg-[#8b5cf6] text-white border border-white/10 shadow-lg">
            <span className="text-xs">🏆</span>
            <span className="text-[10px] font-black uppercase tracking-tighter">{label} {rank}</span>
        </div>
    );
};

const ForecastRow: React.FC<{
    item: ProductForecastData;
    activeMonths: string[];
    top50Ranking?: { eu: Map<string, number>; uk: Map<string, number> };
    stockMap?: Map<string, number>;
}> = React.memo(({ item, activeMonths, top50Ranking, stockMap }) => {
    const asin = item.asin.toUpperCase();

    // Top 50 Badges logic
    const ranks: { rank: number; label: string; theme: 'blue' | 'indigo' }[] = [];
    if (top50Ranking) {
        const rankEU = top50Ranking.eu.get(asin);
        const rankUK = top50Ranking.uk.get(asin);
        if (rankEU) ranks.push({ rank: rankEU, label: 'EU', theme: 'indigo' });
        if (rankUK) ranks.push({ rank: rankUK, label: 'UK', theme: 'blue' });
    }

    // Monthly Forecast Calculation
    const filteredForecast = item.monthlyData
        .filter(md => activeMonths.includes(md.month))
        .reduce((acc, md) => acc + md.forecastUnits, 0);

    // Actual Sales for 2026 (Selected Period)
    const actualPeriod = item.monthlyData
        .filter(md => activeMonths.includes(md.month))
        .reduce((acc, md) => acc + md.actualUnits, 0);

    // Total annual actual for achievement percentage
    const actualTotal = item.monthlyData.reduce((acc, md) => acc + md.actualUnits, 0);
    const totalAchievement = item.annualForecast > 0 ? (actualTotal / item.annualForecast) * 100 : 0;

    return (
        <tr key={item.asin} className="hover:bg-indigo-500/5 transition-colors group">
            <td className="px-6 py-4">
                <div className="flex flex-col gap-1.5">
                    <div className="flex items-center gap-3">
                        {ranks.map((r, i) => (
                            <Top50Badge key={i} rank={r.rank} label={r.label} theme={r.theme} />
                        ))}
                        <span className="font-black text-sm text-[#818cf8] uppercase tracking-tight">{item.sku}</span>
                        <div className="px-2 py-0.5 rounded bg-slate-800/80 border border-white/5 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                            {item.asin}
                        </div>
                    </div>
                    <div className="flex items-start gap-2 text-[13px] font-medium text-slate-100 leading-snug group-hover:text-white transition-colors">
                        <span className="truncate max-w-[170px]">{item.title}</span>
                        {stockMap && (
                            <StockBadge stock={stockMap.get(item.sku?.replace(/(DE|EN)$/i, ''))} />
                        )}
                    </div>
                    <div className="text-[10px] font-black text-[#ec4899] uppercase tracking-[0.15em]">
                        {item.line}
                    </div>
                </div>
            </td>
            <td className="px-6 py-4 text-right font-mono font-bold text-slate-400">
                {filteredForecast.toLocaleString('de-DE')}
            </td>
            <td className="px-6 py-4 text-right font-mono font-bold text-emerald-400">
                {actualPeriod.toLocaleString('de-DE')}
            </td>
            <td className="px-6 py-4 text-right">
                <div className="flex flex-col items-end gap-1">
                    <span className={`px-2 py-1 rounded text-xs font-black ${totalAchievement >= 50 ? 'bg-emerald-500/10 text-emerald-400' : totalAchievement >= 10 ? 'bg-indigo-500/10 text-indigo-400' : 'bg-slate-800 text-slate-500'}`}>
                        {totalAchievement.toFixed(1)}%
                    </span>
                    <span className="text-[9px] text-slate-500 font-bold uppercase">of Annual {item.annualForecast.toLocaleString('de-DE')}</span>
                </div>
            </td>
            <td className="px-6 py-4">
                <div className="flex flex-col items-center gap-2">
                    <div className="w-24 h-1.5 bg-slate-800 rounded-full overflow-hidden border border-white/5">
                        <div
                            className={`h-full transition-all duration-500 rounded-full ${totalAchievement >= 100 ? 'bg-emerald-500' : totalAchievement >= 50 ? 'bg-indigo-500' : 'bg-amber-500/50'}`}
                            style={{ width: `${Math.min(100, totalAchievement)}%` }}
                        />
                    </div>
                    <div className="flex items-center gap-1.5">
                        {totalAchievement >= 100 ? (
                            <div className="px-1.5 py-0.5 rounded text-[8px] font-black bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 uppercase tracking-tighter animate-pulse">
                                Target Hit
                            </div>
                        ) : totalAchievement > 0 ? (
                            <div className="text-[9px] font-bold text-slate-500 italic">
                                {totalAchievement.toFixed(0)}% Done
                            </div>
                        ) : null}
                    </div>
                </div>
            </td>
        </tr>
    );
});

const ForecastView: React.FC<ForecastViewProps> = ({ data, filters, top50Ranking, stockMap, stockFilter, onStockFilterChange }) => {
    const [searchTerm, setSearchTerm] = useState('');
    const [showOnlyTop50, setShowOnlyTop50] = useState(false);
    const [top50Mode, setTop50Mode] = useState<'eu' | 'uk'>('eu');
    const [displayCount, setDisplayCount] = useState(50);

    // Auto-detect best Top 50 mode based on data
    useEffect(() => {
        const hasUK = data.some(p => p.line.toLowerCase().includes('uk') || (p.monthlyData && p.actualUnits > 0 && filters.customer.some(c => c.toLowerCase().includes('uk'))));
        const hasEU = data.some(p => !p.line.toLowerCase().includes('uk'));

        // Simplified detection: if we have a lot of EU products, default EU, otherwise check UK
        if (hasUK && !hasEU) setTop50Mode('uk');
    }, [data, filters.customer]);

    // Determine the "Current Month" based on available 2026 data
    const lastDataMonthIdx = useMemo(() => {
        let maxIdx = 0; // Default Jan
        data.forEach(p => {
            p.monthlyData.forEach((md, idx) => {
                if (md.actualUnits > 0 && idx > maxIdx) {
                    maxIdx = idx;
                }
            });
        });
        return maxIdx;
    }, [data]);

    // Active months for "Monthly Forecast" calculation
    const activeMonths = useMemo(() => {
        if (filters.month && filters.month.length > 0) {
            // Map e.g. "Apr-24" or just "Apr" to the short name
            return filters.month.map(m => m.split('-')[0]);
        }
        // If no filter, use Jan to lastDataMonth
        return MONTH_ORDER.slice(0, lastDataMonthIdx + 1);
    }, [filters.month, lastDataMonthIdx]);

    // Base Global Filtering (Line, ASIN, SKU, Title)
    const baseFilteredData = useMemo(() => {
        let result = data;

        if (filters.line && filters.line.length > 0) {
            result = result.filter(p => filters.line.includes(p.line));
        }
        if (filters.asin && filters.asin.length > 0) {
            result = result.filter(p => filters.asin.includes(p.asin));
        }
        if (filters.sku && filters.sku.length > 0) {
            result = result.filter(p => filters.sku.includes(p.sku));
        }
        if (filters.title && filters.title.length > 0) {
            result = result.filter(p => filters.title.includes(p.title));
        }

        return result;
    }, [data, filters.line, filters.asin, filters.sku, filters.title]);

    // Global Aggregate Data (respects filters) - Single Pass Optimization
    const { globalMonthlyData, globalSummary } = useMemo(() => {
        const monthlyStats = MONTH_ORDER.map(m => ({ name: m, Forecast: 0, Actual: 0 }));
        let periodForecast = 0;
        let periodActual = 0;
        let annualForecast = 0;
        let annualActual = 0;

        baseFilteredData.forEach(p => {
            annualForecast += (p.annualForecast || 0);
            p.monthlyData.forEach((md, idx) => {
                const units = (md.actualUnits || 0);
                const fc = (md.forecastUnits || 0);

                annualActual += units;

                // Update monthly stats (assuming MONTH_ORDER matches p.monthlyData order)
                if (monthlyStats[idx]) {
                    monthlyStats[idx].Forecast += fc;
                    monthlyStats[idx].Actual += units;
                }

                if (activeMonths.includes(md.month)) {
                    periodForecast += fc;
                    periodActual += units;
                }
            });
        });

        const periodFulfillment = periodForecast > 0 ? (periodActual / periodForecast) * 100 : 0;
        const annualFulfillment = annualForecast > 0 ? (annualActual / annualForecast) * 100 : 0;

        return {
            globalMonthlyData: monthlyStats,
            globalSummary: {
                periodForecast,
                periodActual,
                periodFulfillment,
                annualForecast,
                annualActual,
                annualFulfillment
            }
        };
    }, [baseFilteredData, activeMonths]);


    const filteredProducts = useMemo(() => {
        let result = baseFilteredData;

        if (searchTerm) {
            const s = searchTerm.toLowerCase();
            result = result.filter(p =>
                p.asin.toLowerCase().includes(s) ||
                p.sku.toLowerCase().includes(s) ||
                p.title.toLowerCase().includes(s)
            );
        }

        if (showOnlyTop50 && top50Ranking) {
            const currentRankMap = top50Mode === 'eu' ? top50Ranking.eu : top50Ranking.uk;
            result = result.filter(p => currentRankMap.has(p.asin.toUpperCase()));
        }

        return result;
    }, [baseFilteredData, searchTerm, showOnlyTop50, top50Mode, top50Ranking]);

    const sortedProducts = useMemo(() => {
        const result = [...filteredProducts];

        if (showOnlyTop50 && top50Ranking) {
            const currentRankMap = top50Mode === 'eu' ? top50Ranking.eu : top50Ranking.uk;
            result.sort((a, b) => {
                const rankA = currentRankMap.get(a.asin.toUpperCase()) || 999;
                const rankB = currentRankMap.get(b.asin.toUpperCase()) || 999;
                return rankA - rankB;
            });
        } else {
            result.sort((a, b) => b.annualForecast - a.annualForecast);
        }

        return result;
    }, [filteredProducts, showOnlyTop50, top50Mode, top50Ranking]);

    const handleExportExcel = useCallback(() => {
        const exportData = sortedProducts.map(p => {
            const rowData: any = {
                ASIN: p.asin,
                SKU: p.sku,
                Title: p.title,
                'Product Line': p.line,
                'Annual Forecast': Math.round(p.annualForecast),
                'Annual Actual': Math.round(p.actualUnits),
                'Annual Fulfillment (%)': p.annualForecast > 0 ? Number(((p.actualUnits / p.annualForecast) * 100).toFixed(1)) : 0,
                'Period Forecast': 0,
                'Period Actual': 0,
            };

            p.monthlyData.forEach(md => {
                if (activeMonths.includes(md.month)) {
                    rowData['Period Forecast'] += md.forecastUnits;
                    rowData['Period Actual'] += md.actualUnits;
                }
            });

            rowData['Period Fulfillment (%)'] = rowData['Period Forecast'] > 0
                ? Number(((rowData['Period Actual'] / rowData['Period Forecast']) * 100).toFixed(1))
                : 0;

            // Add monthly details
            MONTH_ORDER.forEach(m => {
                const md = p.monthlyData.find(d => d.month === m);
                rowData[`${m} FC`] = md ? Math.round(md.forecastUnits) : 0;
                rowData[`${m} ACT`] = md ? Math.round(md.actualUnits) : 0;
            });

            return rowData;
        });

        const ws = XLSX.utils.json_to_sheet(exportData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Forecast Overview');
        XLSX.writeFile(wb, `Forecast_Export_${new Date().toISOString().slice(0, 10)}.xlsx`);
    }, [sortedProducts, activeMonths]);

    return (
        <div className="p-6 space-y-6 max-w-7xl mx-auto animate-fade-in pb-24">

            {/* Summary Cards */}
            <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
                {/* Annual Forecast Card */}
                <div className="bg-slate-900/50 border border-slate-800 rounded-2xl p-4 shadow-xl relative overflow-hidden group">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-slate-500/5 rounded-full -mr-16 -mt-16 blur-3xl"></div>
                    <h3 className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1">Annual Forecast Total</h3>
                    <div className="text-2xl font-black text-slate-300">
                        {globalSummary.annualForecast.toLocaleString('de-DE')} <span className="text-xs font-medium text-slate-600">Units</span>
                    </div>
                </div>

                <div className="bg-slate-900 border border-border rounded-2xl p-4 shadow-xl relative overflow-hidden group">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/10 rounded-full -mr-16 -mt-16 blur-3xl group-hover:bg-indigo-500/20 transition-all"></div>
                    <h3 className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1">Total Forecast (Period)</h3>
                    <div className="text-2xl font-black text-white">
                        {globalSummary.periodForecast.toLocaleString('de-DE')} <span className="text-xs font-medium text-slate-500">Units</span>
                    </div>
                </div>

                <div className="bg-slate-900 border border-border rounded-2xl p-4 shadow-xl relative overflow-hidden group">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-emerald-500/10 rounded-full -mr-16 -mt-16 blur-3xl group-hover:bg-emerald-500/20 transition-all"></div>
                    <h3 className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1">Total Actual Sales (Period)</h3>
                    <div className="text-2xl font-black text-emerald-400">
                        {globalSummary.periodActual.toLocaleString('de-DE')} <span className="text-xs font-medium text-slate-500">Units</span>
                    </div>
                </div>

                <div className="bg-slate-900 border border-indigo-500/30 rounded-2xl p-4 shadow-xl relative overflow-hidden group">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/20 rounded-full -mr-16 -mt-16 blur-3xl"></div>
                    <h3 className="text-[10px] font-black text-indigo-400 uppercase tracking-widest mb-1">Fulfillment (Period)</h3>
                    <div className="flex items-baseline gap-2">
                        <div className={`text-2xl font-black ${globalSummary.periodFulfillment >= 100 ? 'text-emerald-400' : 'text-indigo-400'}`}>
                            {globalSummary.periodFulfillment.toFixed(1)}%
                        </div>
                    </div>
                    {/* Fulfillment Progress Bar */}
                    <div className="mt-2 w-full h-1.5 bg-slate-800 rounded-full overflow-hidden">
                        <div
                            className="h-full bg-gradient-to-r from-indigo-500 to-fuchsia-500 shadow-[0_0_8px_rgba(99,102,241,0.5)] transition-all duration-1000"
                            style={{ width: `${Math.min(100, globalSummary.periodFulfillment)}%` }}
                        ></div>
                    </div>
                </div>

                {/* Annual Fulfillment Card */}
                <div className="bg-slate-900/50 border border-slate-800 rounded-2xl p-4 shadow-xl relative overflow-hidden group">
                    <div className="absolute top-0 right-0 w-32 h-32 bg-slate-500/5 rounded-full -mr-16 -mt-16 blur-3xl"></div>
                    <h3 className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-1">Annual Fulfillment %</h3>
                    <div className="text-2xl font-black text-slate-400">
                        {globalSummary.annualFulfillment.toFixed(1)}%
                    </div>
                    <div className="mt-2 w-full h-1.5 bg-slate-800/50 rounded-full overflow-hidden">
                        <div
                            className="h-full bg-slate-700 transition-all duration-1000"
                            style={{ width: `${Math.min(100, globalSummary.annualFulfillment)}%` }}
                        ></div>
                    </div>
                </div>
            </div>

            {/* Main Trend Chart */}
            <div className="bg-slate-900 border border-border rounded-2xl p-6 shadow-xl">
                <div className="flex justify-between items-center mb-6">
                    <h3 className="text-lg font-bold text-white flex items-center gap-2">
                        <svg className="w-5 h-5 text-indigo-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" /></svg>
                        Monthly Evolution: Forecast vs Actual
                    </h3>
                </div>
                <div className="h-96">
                    <ResponsiveContainer width="100%" height="100%">
                        <ComposedChart data={globalMonthlyData}>
                            <CartesianGrid strokeDasharray="3 3" stroke="#1e293b" vertical={false} />
                            <XAxis dataKey="name" stroke="#64748b" />
                            <YAxis stroke="#64748b" />
                            <Tooltip
                                contentStyle={{ backgroundColor: '#0f172a', borderColor: '#1e293b', borderRadius: '12px', padding: '12px' }}
                                itemStyle={{ fontWeight: 'bold' }}
                            />
                            <Legend verticalAlign="top" height={36} />
                            <Bar dataKey="Actual" fill="#10b981" radius={[4, 4, 0, 0]} name="Actual Sales" barSize={40} />
                            <Line type="monotone" dataKey="Forecast" stroke="#6366f1" strokeWidth={4} dot={{ r: 6, fill: '#6366f1' }} name="Forecast Target" />
                            <Area type="monotone" dataKey="Forecast" fill="#6366f1" fillOpacity={0.05} stroke="none" />
                        </ComposedChart>
                    </ResponsiveContainer>
                </div>
            </div>

            {/* Product Table */}
            <div className="bg-slate-900 border border-border rounded-2xl shadow-xl overflow-hidden">
                <div className="p-6 border-b border-border flex flex-col md:flex-row justify-between gap-4">
                    <h3 className="text-lg font-bold text-white uppercase tracking-tight">Product Performance Comparison</h3>
                    <div className="flex flex-col md:flex-row items-center gap-4">
                        {/* Top 50 Toggle */}
                        <div className="flex items-center bg-slate-950 p-1 rounded-lg border border-slate-700">
                            <button
                                onClick={() => setShowOnlyTop50(!showOnlyTop50)}
                                className={`px-3 py-1.5 rounded-md text-xs font-black transition-all flex items-center gap-2 ${showOnlyTop50 ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-500/20' : 'text-slate-500 hover:text-slate-300'}`}
                            >
                                <span className="text-sm">🏆</span>
                                Top 50
                            </button>
                            {showOnlyTop50 && (
                                <div className="flex items-center ml-1 border-l border-slate-700 pl-1">
                                    <button
                                        onClick={() => setTop50Mode('eu')}
                                        className={`px-2 py-1 rounded text-[10px] font-bold transition-colors ${top50Mode === 'eu' ? 'text-indigo-400 bg-indigo-500/10' : 'text-slate-600 hover:text-slate-400'}`}
                                    >
                                        EU
                                    </button>
                                    <button
                                        onClick={() => setTop50Mode('uk')}
                                        className={`px-2 py-1 rounded text-[10px] font-bold transition-colors ${top50Mode === 'uk' ? 'text-indigo-400 bg-indigo-500/10' : 'text-slate-600 hover:text-slate-400'}`}
                                    >
                                        UK
                                    </button>
                                </div>
                            )}
                        </div>
                        <div className="relative">
                            <input
                                type="text"
                                placeholder="Search by ASIN, SKU or Title..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="bg-slate-950 border border-slate-700 rounded-lg px-10 py-2 text-sm text-slate-200 focus:outline-none focus:border-indigo-500 w-full md:w-80"
                            />
                            <svg className="absolute left-3 top-2.5 w-4 h-4 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                        </div>
                        <button
                            onClick={handleExportExcel}
                            className="flex items-center gap-2 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-bold border border-white/10 transition-all shadow-lg active:scale-95"
                            title="Export to Excel"
                        >
                            <DownloadIcon />
                            <span>Export</span>
                        </button>
                    </div>
                </div>
                <div className="overflow-x-auto">
                    <table className="w-full text-left text-sm whitespace-nowrap">
                        <thead className="bg-slate-950 text-slate-500 uppercase text-[10px] font-black tracking-widest border-b border-border sticky top-0 z-20">
                            <tr className="relative z-30">
                                <th className="px-6 py-4">
                                    <div className="flex items-center gap-2">
                                        <span>Product Info</span>
                                        <InColumnStockFilter
                                            currentFilters={stockFilter}
                                            onFilterChange={onStockFilterChange}
                                        />
                                    </div>
                                </th>
                                <th className="px-6 py-4 text-right">Forecast (Period)</th>
                                <th className="px-6 py-4 text-right">Actual Units Sales 2026</th>
                                <th className="px-6 py-4 text-right">Fc 26 Achievement</th>
                                <th className="px-6 py-4 text-center">YTD Achievement</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800">
                            {sortedProducts.length > 0 ? (
                                (() => {
                                    const displayItems = sortedProducts.slice(0, displayCount);
                                    return (
                                        <>
                                            {displayItems.map(p => (
                                                <ForecastRow
                                                    key={p.asin}
                                                    item={p}
                                                    activeMonths={activeMonths}
                                                    top50Ranking={top50Ranking}
                                                    stockMap={stockMap}
                                                />
                                            ))}
                                            {displayCount < sortedProducts.length && (
                                                <tr>
                                                    <td colSpan={5} className="px-6 py-6 text-center bg-slate-900/40 backdrop-blur-sm border-t border-white/5">
                                                        <button
                                                            onClick={() => setDisplayCount(prev => prev + 100)}
                                                            className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-xl text-xs font-black uppercase tracking-widest shadow-xl transition-all active:scale-95 border border-indigo-400/30"
                                                        >
                                                            Load More SKUs ({sortedProducts.length - displayCount} remaining)
                                                        </button>
                                                    </td>
                                                </tr>
                                            )}
                                        </>
                                    );
                                })()
                            ) : (
                                <tr>
                                    <td colSpan={5} className="px-6 py-10 text-center text-slate-500 italic">
                                        No products found matching your filters...
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
};

export default ForecastView;
