import React, { useMemo, useState } from 'react';
import { CombinedKPIs } from '../types';
import { pivotWeeklySalesData, WeeklyPivotRow } from '../services/dataProcessor';

interface WeeklyGridProps {
    data: CombinedKPIs[];
}

type SortConfig = {
    key: string; // weekKey
    direction: 'asc' | 'desc';
} | null;

const WeeklyGrid: React.FC<WeeklyGridProps> = ({ data }) => {
    const { rows, weeks } = useMemo(() => pivotWeeklySalesData(data), [data]);

    // Default sort: most recent week, descending
    const [sortConfig, setSortConfig] = useState<SortConfig>(() => {
        if (weeks.length > 0) {
            return { key: weeks[0], direction: 'desc' };
        }
        return null;
    });

    const handleSort = (weekKey: string) => {
        setSortConfig(prev => {
            if (prev?.key === weekKey) {
                return { key: weekKey, direction: prev.direction === 'asc' ? 'desc' : 'asc' };
            }
            return { key: weekKey, direction: 'desc' };
        });
    };

    // Group and Sort rows
    const groupedRows = useMemo(() => {
        const groups: { [line: string]: WeeklyPivotRow[] } = {};

        // Clone and sort rows based on config
        const sortedRows = [...rows];
        if (sortConfig) {
            sortedRows.sort((a, b) => {
                const valA = a.unitsByWeek[sortConfig.key] || 0;
                const valB = b.unitsByWeek[sortConfig.key] || 0;
                if (sortConfig.direction === 'asc') {
                    return valA - valB;
                }
                return valB - valA;
            });
        }

        sortedRows.forEach(row => {
            const line = row.line || 'Uncategorized';
            if (!groups[line]) groups[line] = [];
            groups[line].push(row);
        });

        // Sort lines alphabetically
        return Object.keys(groups).sort().reduce((acc, line) => {
            acc[line] = groups[line];
            return acc;
        }, {} as { [line: string]: WeeklyPivotRow[] });
    }, [rows, sortConfig]);

    // Calculate totals per week
    const weekTotals = useMemo(() => {
        const totals: { [weekKey: string]: number } = {};
        weeks.forEach(week => {
            totals[week] = rows.reduce((sum, row) => sum + (row.unitsByWeek[week] || 0), 0);
        });
        return totals;
    }, [rows, weeks]);

    const renderGrowth = (current: number, previous: number) => {
        if (!previous || previous === 0) return null;
        const pct = ((current - previous) / previous) * 100;
        const isPositive = pct >= 0;

        return (
            <div className={`text-[8px] leading-none flex items-center justify-center gap-0.5 mt-0.5 font-bold ${isPositive ? 'text-emerald-400' : 'text-red-400'}`}>
                {isPositive ? '▲' : '▼'}{Math.abs(pct).toFixed(0)}%
            </div>
        );
    };

    return (
        <div className="bg-slate-900 border border-white/10 rounded-xl overflow-hidden animate-fade-in shadow-2xl">
            <div className="overflow-x-auto overflow-y-auto max-h-[calc(100vh-280px)]">
                <table className="w-full text-left border-collapse min-w-[max-content]">
                    <thead className="sticky top-0 z-20">
                        <tr className="bg-slate-900 border-b border-white/10">
                            <th className="p-2 text-[9px] font-black text-slate-400 uppercase tracking-widest sticky left-0 z-30 bg-slate-900 border-r border-white/10 min-w-[200px]">Product Details</th>
                            {weeks.map(week => (
                                <th
                                    key={week}
                                    className={`p-2 text-[9px] font-black uppercase tracking-widest text-center border-r border-white/10 w-24 cursor-pointer hover:bg-white/5 transition-colors select-none ${sortConfig?.key === week ? 'text-indigo-400 bg-white/[0.02]' : 'text-slate-400'}`}
                                    onClick={() => handleSort(week)}
                                >
                                    <div className="flex flex-col items-center gap-1">
                                        <span>{week.split('-')[1]}/{week.split('-')[0].slice(-2)}</span>
                                        {sortConfig?.key === week && (
                                            <span className="text-[10px]">{sortConfig.direction === 'asc' ? '↑' : '↓'}</span>
                                        )}
                                    </div>
                                </th>
                            ))}
                        </tr>
                        <tr className="bg-indigo-950/40 backdrop-blur-md border-b border-white/10">
                            <th className="p-2 text-xs font-black text-white sticky left-0 z-30 bg-indigo-900/60 border-r border-white/10">TOTALS</th>
                            {weeks.map((week, idx) => (
                                <th key={week} className="p-2 text-xs font-black text-white text-center border-r border-white/10">
                                    <div className="flex flex-col items-center">
                                        <span>{weekTotals[week]?.toLocaleString('de-DE')}</span>
                                        {renderGrowth(weekTotals[week], weekTotals[weeks[idx + 1]])}
                                    </div>
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-white/5">
                        {Object.entries(groupedRows).map(([line, lineRows]) => (
                            <React.Fragment key={line}>
                                {/* Category Header */}
                                <tr className="bg-slate-800/50">
                                    <td colSpan={weeks.length + 1} className="p-1 px-3 text-[10px] font-black text-fuchsia-400 uppercase tracking-widest bg-slate-800/80 border-b border-white/5">
                                        {line}
                                    </td>
                                </tr>
                                {lineRows.map((row) => (
                                    <tr key={row.id} className="hover:bg-white/[0.02] transition-colors group">
                                        <td className="p-2 py-1.5 sticky left-0 z-10 bg-slate-900 md:bg-slate-900/95 backdrop-blur-sm group-hover:bg-slate-800 border-r border-white/10">
                                            <div className="flex flex-col">
                                                <span className="text-[10px] font-black text-indigo-400 uppercase tracking-tighter truncate w-[180px]">{row.sku}</span>
                                                <span className="text-[9px] text-white/60 truncate w-[180px] leading-tight" title={row.title}>{row.title}</span>
                                            </div>
                                        </td>
                                        {weeks.map((week, idx) => {
                                            const val = row.unitsByWeek[week] || 0;
                                            const prevVal = row.unitsByWeek[weeks[idx + 1]] || 0;
                                            return (
                                                <td key={week} className={`p-2 py-1.5 text-center border-r border-white/5 align-middle ${sortConfig?.key === week ? 'bg-white/[0.01]' : ''}`}>
                                                    <div className="flex flex-col items-center justify-center">
                                                        <span className={`text-xs font-bold ${val > 0 ? (sortConfig?.key === week ? 'text-indigo-400' : 'text-white') : 'text-slate-700'}`}>
                                                            {val > 0 ? val.toLocaleString('de-DE') : '-'}
                                                        </span>
                                                        {val > 0 && renderGrowth(val, prevVal)}
                                                    </div>
                                                </td>
                                            );
                                        })}
                                    </tr>
                                ))}
                            </React.Fragment>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

export default WeeklyGrid;
