import React, { useMemo, useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Cell } from 'recharts';
import { BSRRecord } from '../types';
import { BuyBoxWarningBadge } from './BuyBoxWarningBadge';

const MARKET_COLORS: Record<string, string> = {
  DE: '#3b82f6',
  UK: '#ef4444',
  IT: '#22c55e',
  FR: '#a855f7',
  ES: '#f59e0b',
};

interface VendorDataViewProps {
  bsrData: BSRRecord[];
  asinMetadata?: Map<string, { sku: string; title: string; line: string }>;
  buyBoxLostMap?: Map<string, { countries: string[]; reasons: Record<string, string> }>;
}

interface ChartPoint {
  label: string;
  sortKey: string;
  [key: string]: number | string | null;
}

const VendorDataView: React.FC<VendorDataViewProps> = ({ bsrData = [], asinMetadata, buyBoxLostMap }) => {
  // Determine active markets in filtered data for series generation
  const activeMarkets = useMemo(() => {
    const m = new Set(bsrData.map(r => r.market));
    return Array.from(m).sort();
  }, [bsrData]);

  // Determine if daily resolution is available (>= half the records have a date)
  const useDailyResolution = useMemo(() => {
    const withDate = bsrData.filter(r => r.date).length;
    return withDate > bsrData.length / 2;
  }, [bsrData]);

  // Get unique ASINs in filtered data
  const uniqueAsins = useMemo(() => {
    const asinSet = new Set(bsrData.map(r => r.asin.trim().toUpperCase()));
    return Array.from(asinSet);
  }, [bsrData]);

  // Get product info when single ASIN is selected
  const productInfo = useMemo(() => {
    if (uniqueAsins.length !== 1) return null;
    const asin = uniqueAsins[0];
    const metadata = asinMetadata?.get(asin);
    if (!metadata) return null;
    return {
      asin,
      sku: metadata.sku,
      title: metadata.title,
      line: metadata.line,
    };
  }, [uniqueAsins, asinMetadata]);

  // Aggregate Data for Charts — daily if dates available, else weekly
  const { topBsrChartData, detailBsrChartData, ratingChartData } = useMemo(() => {
    // Group by date string (YYYY-MM-DD) or by week number
    const byBucket = new Map<string, BSRRecord[]>();

    bsrData.forEach(r => {
      const key = useDailyResolution && r.date ? r.date : `W${String(r.week).padStart(2, '0')}`;
      if (!byBucket.has(key)) byBucket.set(key, []);
      byBucket.get(key)!.push(r);
    });

    const sortedKeys = Array.from(byBucket.keys()).sort();

    const topBsrChartData: ChartPoint[] = [];
    const detailBsrChartData: ChartPoint[] = [];
    const ratingChartData: ChartPoint[] = [];

    sortedKeys.forEach(key => {
      const rows = byBucket.get(key)!;

      // Human-readable label
      let label: string;
      if (useDailyResolution && key.includes('-')) {
        // YYYY-MM-DD → "DD MMM"
        const d = new Date(key + 'T12:00:00Z');
        label = d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
      } else {
        label = key; // e.g. "W08"
      }

      const topPoint: ChartPoint = { label, sortKey: key };
      const detailPoint: ChartPoint = { label, sortKey: key };
      const ratingPoint: ChartPoint = { label, sortKey: key };

      activeMarkets.forEach(m => {
        const marketRows = rows.filter(r => r.market === m);

        // Top BSR
        const topBsrRows = marketRows.filter(r => r.topLevelBSR != null);
        topPoint[`${m}_bsr`] = topBsrRows.length > 0
          ? Math.round(topBsrRows.reduce((sum, r) => sum + r.topLevelBSR!, 0) / topBsrRows.length)
          : null;

        // Detail BSR
        const detailBsrRows = marketRows.filter(r => r.detailLevelBSR != null);
        detailPoint[`${m}_bsr`] = detailBsrRows.length > 0
          ? Math.round(detailBsrRows.reduce((sum, r) => sum + r.detailLevelBSR!, 0) / detailBsrRows.length)
          : null;

        // Rating
        const ratingRows = marketRows.filter(r => r.avgRating != null);
        ratingPoint[`${m}_rating`] = ratingRows.length > 0
          ? Math.round((ratingRows.reduce((sum, r) => sum + r.avgRating!, 0) / ratingRows.length) * 10) / 10
          : null;
      });

      topBsrChartData.push(topPoint);
      detailBsrChartData.push(detailPoint);
      ratingChartData.push(ratingPoint);
    });

    return { topBsrChartData, detailBsrChartData, ratingChartData };
  }, [bsrData, activeMarkets, useDailyResolution]);

  if (bsrData.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4">
        <div className="p-4 bg-emerald-500/10 rounded-full text-emerald-400">
          <svg className="w-12 h-12" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 0 1 3 19.875v-6.75ZM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V8.625ZM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 0 1-1.125-1.125V4.125Z" />
          </svg>
        </div>
        <h2 className="text-xl font-bold text-slate-200">No BSR Data Yet</h2>
        <p className="text-sm text-slate-400 max-w-md">
          Ensure BSR.xlsx is present and loading to see Top Level BSR, Detail Level BSR, and Average Rating trends.
        </p>
      </div>
    );
  }

  const resolutionLabel = useDailyResolution ? 'Daily Avg' : 'Weekly Avg';

  return (
    <div className="space-y-6 p-4 pb-24 md:pb-4">
      <div className="flex flex-wrap gap-3 items-center">
        <span className="text-slate-500 text-xs ml-auto">{bsrData.length.toLocaleString()} records filtered</span>
      </div>

      {/* Product Info Card - Only shown when single ASIN is selected */}
      {productInfo && (
        <div className="bg-gradient-to-r from-indigo-500/10 to-purple-500/10 border border-indigo-500/30 rounded-xl p-4 animate-fade-in">
          <div className="flex items-start gap-4">
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-2">
                <span className="text-[10px] font-black text-indigo-400 uppercase tracking-widest bg-indigo-500/20 px-2 py-0.5 rounded">
                  Product Details
                </span>
              </div>
              <div className="space-y-1.5">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs text-slate-500 font-bold uppercase tracking-wider">SKU:</span>
                  <span className="text-sm font-mono font-bold text-slate-200">{productInfo.sku}</span>
                </div>
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs text-slate-500 font-bold uppercase tracking-wider">ASIN:</span>
                  <span className="text-sm font-mono font-bold text-indigo-400">{productInfo.asin}</span>
                </div>
                <div className="flex items-start gap-2">
                  <span className="text-xs text-slate-500 font-bold uppercase tracking-wider mt-0.5">Title:</span>
                  <span className="text-sm font-medium text-slate-300">{productInfo.title}</span>
                </div>
              </div>
            </div>
            <div className="flex-shrink-0">
              <BuyBoxWarningBadge asin={productInfo.asin} buyBoxLostMap={buyBoxLostMap} />
            </div>
          </div>
        </div>
      )}

      {/* Top Level BSR Trend Chart */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-4">
        <h3 className="text-lg font-bold text-slate-200 mb-4">Top Level BSR Trend ({resolutionLabel})</h3>
        <p className="text-xs text-slate-500 mb-3">Lower rank = better position. Averaged across filtered ASINs per market.</p>
        <ResponsiveContainer width="100%" height={350}>
          <BarChart data={topBsrChartData} barGap={4} barCategoryGap="20%">
            <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
            <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 11 }} interval="preserveStartEnd" />
            <YAxis reversed tick={{ fill: '#94a3b8', fontSize: 11 }} domain={['auto', 'auto']} />
            <Tooltip
              contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
              labelStyle={{ color: '#e2e8f0' }}
              cursor={{ fill: 'rgba(255,255,255,0.05)' }}
            />
            <Legend />
            {activeMarkets.map(m => (
              <Bar
                key={m}
                dataKey={`${m}_bsr`}
                name={`${m} BSR`}
                fill={MARKET_COLORS[m] || '#6b7280'}
                radius={[4, 4, 0, 0]}
              />
            ))}
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* Detail Level BSR Trend Chart */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-4">
        <h3 className="text-lg font-bold text-slate-200 mb-4">Detail Level BSR Trend ({resolutionLabel})</h3>
        <p className="text-xs text-slate-500 mb-3">Lower rank = better position. Averaged across filtered ASINs per market.</p>
        <ResponsiveContainer width="100%" height={350}>
          <BarChart data={detailBsrChartData} barGap={4} barCategoryGap="20%">
            <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
            <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 11 }} interval="preserveStartEnd" />
            <YAxis reversed tick={{ fill: '#94a3b8', fontSize: 11 }} domain={['auto', 'auto']} />
            <Tooltip
              contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
              labelStyle={{ color: '#e2e8f0' }}
              cursor={{ fill: 'rgba(255,255,255,0.05)' }}
            />
            <Legend />
            {activeMarkets.map(m => (
              <Bar
                key={m}
                dataKey={`${m}_bsr`}
                name={`${m} BSR`}
                fill={MARKET_COLORS[m] || '#6b7280'}
                radius={[4, 4, 0, 0]}
              />
            ))}
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* Average Rating Chart */}
      <div className="bg-slate-900/50 border border-slate-800 rounded-xl p-4">
        <h3 className="text-lg font-bold text-slate-200 mb-4">Average Rating ({resolutionLabel})</h3>
        <p className="text-xs text-slate-500 mb-3">Averaged across filtered ASINs per market.</p>
        <ResponsiveContainer width="100%" height={350}>
          <BarChart data={ratingChartData} barGap={4} barCategoryGap="20%">
            <CartesianGrid strokeDasharray="3 3" stroke="#334155" vertical={false} />
            <XAxis dataKey="label" tick={{ fill: '#94a3b8', fontSize: 11 }} interval="preserveStartEnd" />
            <YAxis domain={[0, 5]} tick={{ fill: '#94a3b8', fontSize: 11 }} />
            <Tooltip
              contentStyle={{ backgroundColor: '#1e293b', border: '1px solid #334155', borderRadius: '8px' }}
              labelStyle={{ color: '#e2e8f0' }}
              cursor={{ fill: 'rgba(255,255,255,0.05)' }}
            />
            <Legend />
            {activeMarkets.map(m => (
              <Bar
                key={m}
                dataKey={`${m}_rating`}
                name={`${m} Rating`}
                fill={MARKET_COLORS[m] || '#6b7280'}
                radius={[4, 4, 0, 0]}
              />
            ))}
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default VendorDataView;
