import React, { useMemo } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } 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: '#f97316',
};

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
  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
  const { topBsrChartData, detailBsrChartData, ratingChartData } = useMemo(() => {
    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)!;

      let label: string;
      if (useDailyResolution && key.includes('-')) {
        const d = new Date(key + 'T12:00:00Z');
        label = d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
      } else {
        label = key;
      }

      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>
    );
  }

  return (
    <div className="space-y-6 p-4 pb-24 md:pb-4 max-w-5xl mx-auto">
      {/* Header Info */}
      <div className="flex flex-wrap gap-3 items-center justify-between">
        <h2 className="text-2xl font-black text-slate-100 uppercase tracking-tight">Vendor Analytics</h2>
        <span className="bg-slate-800 text-slate-400 text-[10px] px-2 py-1 rounded font-bold uppercase tracking-wider border border-slate-700">
          {bsrData.length.toLocaleString()} records filtered
        </span>
      </div>

      {/* Product Info Card */}
      {productInfo && (
        <div className="bg-[#151b2b] border border-[#1e293b] rounded-2xl p-6 shadow-2xl relative overflow-hidden group">
          <div className="absolute top-0 left-0 w-1 h-full bg-indigo-500"></div>
          <div className="flex items-start justify-between gap-4">
            <div className="space-y-4 flex-1">
              <div>
                <span className="text-[10px] font-black text-indigo-400 uppercase tracking-widest bg-indigo-500/10 px-2 py-1 rounded mb-2 inline-block">
                  Product Details
                </span>
                <h3 className="text-xl md:text-2xl font-black text-white leading-tight uppercase tracking-tight">
                  {productInfo.title}
                </h3>
              </div>

              <div className="flex flex-wrap gap-x-8 gap-y-2">
                <div className="flex items-center gap-2">
                  <span className="text-[10px] text-slate-500 font-black uppercase tracking-widest">SKU:</span>
                  <span className="text-base font-bold text-slate-200">{productInfo.sku}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[10px] text-slate-500 font-black uppercase tracking-widest">ASIN:</span>
                  <span className="text-base font-bold text-indigo-400 font-mono tracking-tight">{productInfo.asin}</span>
                </div>
              </div>
            </div>
            <div className="flex-shrink-0 pt-1">
              <BuyBoxWarningBadge asin={productInfo.asin} buyBoxLostMap={buyBoxLostMap} />
            </div>
          </div>
        </div>
      )}

      {/* Top Level BSR Trend Chart */}
      <div className="bg-[#151b2b] border border-[#1e293b] rounded-2xl p-6 shadow-xl">
        <div className="mb-6">
          <h3 className="text-lg font-black text-white uppercase tracking-tight">Top Level BSR Trend</h3>
          <p className="text-xs text-slate-500 font-medium">Weekly Average Rank • <span className="text-orange-500/80">Lower is better</span></p>
        </div>
        <div className="h-[350px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={topBsrChartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
              <defs>
                <linearGradient id="colorTop" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#f43f5e" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="#f43f5e" stopOpacity={0} />
                </linearGradient>
                {activeMarkets.map(m => (
                  <linearGradient key={m} id={`grad_top_${m}`} x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor={MARKET_COLORS[m] || '#f97316'} stopOpacity={0.3} />
                    <stop offset="95%" stopColor={MARKET_COLORS[m] || '#f97316'} stopOpacity={0} />
                  </linearGradient>
                ))}
              </defs>
              <CartesianGrid strokeDasharray="0" stroke="#1e293b" vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                dy={10}
              />
              <YAxis
                reversed
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                domain={['auto', 'auto']}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '12px', boxShadow: '0 20px 25px -5px rgb(0 0 0 / 0.1)' }}
                itemStyle={{ fontSize: '11px', fontWeight: 700 }}
                labelStyle={{ color: '#94a3b8', fontSize: '10px', marginBottom: '4px', fontWeight: 800, textTransform: 'uppercase' }}
                cursor={{ stroke: '#334155', strokeWidth: 1 }}
              />
              {activeMarkets.map(m => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_bsr`}
                  name={`${m} BSR`}
                  stroke={MARKET_COLORS[m] || '#f97316'}
                  strokeWidth={3}
                  fillOpacity={1}
                  fill={`url(#grad_top_${m})`}
                  dot={{ r: 4, fill: '#151b2b', strokeWidth: 2, stroke: MARKET_COLORS[m] || '#f97316' }}
                  activeDot={{ r: 6, strokeWidth: 0 }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="mt-4 flex flex-wrap gap-4 justify-center">
          {activeMarkets.map(m => (
            <div key={m} className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full" style={{ backgroundColor: MARKET_COLORS[m] }}></div>
              <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{m} BSR</span>
            </div>
          ))}
        </div>
      </div>

      {/* Detail Level BSR Trend Chart */}
      <div className="bg-[#151b2b] border border-[#1e293b] rounded-2xl p-6 shadow-xl">
        <div className="mb-6">
          <h3 className="text-lg font-black text-white uppercase tracking-tight">Detail Level BSR Trend</h3>
          <p className="text-xs text-slate-500 font-medium">Sub-category Performance • <span className="text-cyan-500/80">Filtered ASINs</span></p>
        </div>
        <div className="h-[350px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={detailBsrChartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
              <defs>
                {activeMarkets.map(m => (
                  <linearGradient key={m} id={`grad_detail_${m}`} x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor={MARKET_COLORS[m] || '#06b6d4'} stopOpacity={0.3} />
                    <stop offset="95%" stopColor={MARKET_COLORS[m] || '#06b6d4'} stopOpacity={0} />
                  </linearGradient>
                ))}
              </defs>
              <CartesianGrid strokeDasharray="0" stroke="#1e293b" vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                dy={10}
              />
              <YAxis
                reversed
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                domain={['auto', 'auto']}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '12px' }}
                itemStyle={{ fontSize: '11px', fontWeight: 700 }}
                labelStyle={{ color: '#94a3b8', fontSize: '10px', marginBottom: '4px', fontWeight: 800, textTransform: 'uppercase' }}
                cursor={{ stroke: '#334155', strokeWidth: 1 }}
              />
              {activeMarkets.map(m => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_bsr`}
                  name={`${m} Category Rank`}
                  stroke={MARKET_COLORS[m] || '#06b6d4'}
                  strokeWidth={3}
                  fillOpacity={1}
                  fill={`url(#grad_detail_${m})`}
                  dot={{ r: 4, fill: '#151b2b', strokeWidth: 2, stroke: MARKET_COLORS[m] || '#06b6d4' }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="mt-4 flex flex-wrap gap-4 justify-center">
          {activeMarkets.map(m => (
            <div key={m} className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full" style={{ backgroundColor: MARKET_COLORS[m] }}></div>
              <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{m} Category Rank</span>
            </div>
          ))}
        </div>
      </div>

      {/* Average Rating Chart */}
      <div className="bg-[#151b2b] border border-[#1e293b] rounded-2xl p-6 shadow-xl">
        <div className="mb-6">
          <h3 className="text-lg font-black text-white uppercase tracking-tight">Average Rating</h3>
          <p className="text-xs text-slate-500 font-medium">Weekly Average • <span className="text-purple-500/80">1.0 - 5.0 Stars</span></p>
        </div>
        <div className="h-[350px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={ratingChartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
              <defs>
                {activeMarkets.map(m => (
                  <linearGradient key={m} id={`grad_rating_${m}`} x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor={MARKET_COLORS[m] || '#a855f7'} stopOpacity={0.3} />
                    <stop offset="95%" stopColor={MARKET_COLORS[m] || '#a855f7'} stopOpacity={0} />
                  </linearGradient>
                ))}
              </defs>
              <CartesianGrid strokeDasharray="0" stroke="#1e293b" vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                dy={10}
              />
              <YAxis
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#475569', fontSize: 10, fontWeight: 700 }}
                domain={[0, 5]}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#0f172a', border: '1px solid #1e293b', borderRadius: '12px' }}
                itemStyle={{ fontSize: '11px', fontWeight: 700 }}
                labelStyle={{ color: '#94a3b8', fontSize: '10px', marginBottom: '4px', fontWeight: 800, textTransform: 'uppercase' }}
                cursor={{ stroke: '#334155', strokeWidth: 1 }}
              />
              {activeMarkets.map(m => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_rating`}
                  name={`${m} Star Rating`}
                  stroke={MARKET_COLORS[m] || '#a855f7'}
                  strokeWidth={3}
                  fillOpacity={1}
                  fill={`url(#grad_rating_${m})`}
                  dot={{ r: 4, fill: '#151b2b', strokeWidth: 2, stroke: MARKET_COLORS[m] || '#a855f7' }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>
        <div className="mt-4 flex flex-wrap gap-4 justify-center">
          {activeMarkets.map(m => (
            <div key={m} className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full" style={{ backgroundColor: MARKET_COLORS[m] }}></div>
              <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">{m} Star Rating</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default VendorDataView;
