import React, { useMemo } from 'react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { BSRRecord } from '../types';
import { BuyBoxWarningBadge } from './BuyBoxWarningBadge';

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 }) => {
  const activeMarkets = useMemo(() => {
    const m = new Set(bsrData.map(r => r.market));
    return Array.from(m).sort();
  }, [bsrData]);

  const useDailyResolution = useMemo(() => {
    const withDate = bsrData.filter(r => r.date).length;
    return withDate > bsrData.length / 2;
  }, [bsrData]);

  const uniqueAsins = useMemo(() => {
    const asinSet = new Set(bsrData.map(r => r.asin.trim().toUpperCase()));
    return Array.from(asinSet);
  }, [bsrData]);

  const productInfo = useMemo(() => {
    if (uniqueAsins.length !== 1) return null;
    const asin = uniqueAsins[0];
    const metadata = asinMetadata?.get(asin);
    if (!metadata) return null;

    let topCategory = '';
    let detailCategory = '';
    for (const r of bsrData) {
      if (!topCategory && r.topLevelName) topCategory = r.topLevelName;
      if (!detailCategory && r.detailLevelName) detailCategory = r.detailLevelName;
      if (topCategory && detailCategory) break;
    }

    return {
      asin,
      sku: metadata.sku,
      title: metadata.title,
      line: metadata.line,
      topCategory,
      detailCategory
    };
  }, [uniqueAsins, asinMetadata, bsrData]);

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

        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;

        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;

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

  // Exact color values based on the screenshot
  const cardBg = '#161b24';
  const orangeHex = '#f37526';
  const cyanHex = '#2acbd6';
  const purpleHex = '#7950f2';
  const gridLineColor = '#ffffff';

  return (
    <div className="p-4 md:p-6 lg:px-8 pb-24 max-w-[800px] mx-auto space-y-6">

      {/* Product Details Header Card */}
      {productInfo && (
        <div className="bg-[#161b24] border border-[#2a3040] rounded-2xl p-6 shadow-md relative">
          <div className="flex items-start justify-between gap-4">
            <div className="flex flex-col gap-3 flex-1">
              <div>
                <span className="inline-block bg-[#1f2b4a] text-[#4f86f7] text-[10px] font-bold uppercase tracking-wider px-2.5 py-1 rounded-[4px] mb-3">
                  PRODUCT DETAILS
                </span>
                <h2 className="text-xl md:text-2xl font-bold text-white mb-1">
                  {productInfo.title}
                </h2>
              </div>

              <div className="flex items-center gap-6 mt-1">
                <div className="text-[13px] md:text-sm">
                  <span className="text-[#64748b] font-semibold mr-2">SKU:</span>
                  <span className="text-[#e2e8f0] font-medium">{productInfo.sku}</span>
                </div>
                <div className="text-[13px] md:text-sm">
                  <span className="text-[#64748b] font-semibold mr-2">ASIN:</span>
                  <span className="text-[#4f86f7] font-medium tracking-wide">{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-[#161b24] border border-[#2a3040] rounded-2xl p-6 shadow-md flex flex-col">
        <div className="mb-4">
          <div className="flex flex-wrap items-center gap-3 mb-1">
            <h3 className="text-[17px] font-semibold text-white tracking-wide">Top Level BSR Trend</h3>
            {productInfo?.topCategory && (
              <span className="text-[11px] font-medium text-[#e2e8f0] bg-[#334155]/60 px-2.5 py-0.5 rounded border border-[#475569]/50 tracking-wider">
                {productInfo.topCategory}
              </span>
            )}
          </div>
          <p className="text-[13px] text-[#64748b]">Weekly Average Rank • Lower is better</p>
        </div>

        <div className="h-[220px] w-full mt-2">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={topBsrChartData} margin={{ top: 20, right: 20, left: -20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="0" stroke={gridLineColor} strokeOpacity={0.03} vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dy={10}
              />
              <YAxis
                reversed
                domain={['auto', 'auto']}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dx={-10}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#111827', border: '1px solid #374151', borderRadius: '8px', color: '#fff' }}
                itemStyle={{ fontSize: '12px' }}
                labelStyle={{ color: '#9ca3af', fontSize: '11px', marginBottom: '4px' }}
                cursor={{ stroke: '#374151', strokeWidth: 1, strokeDasharray: '3 3' }}
              />
              {activeMarkets.map((m) => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_bsr`}
                  name={`${m} BSR`}
                  stroke={orangeHex}
                  strokeWidth={2.5}
                  fillOpacity={1}
                  fill="transparent"
                  activeDot={{ r: 6, strokeWidth: 0, fill: orangeHex }}
                  dot={{ r: 4, fill: cardBg, strokeWidth: 2, stroke: orangeHex }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Exact Legend matching screenshot */}
        <div className="mt-6 flex justify-center items-center gap-2">
          {activeMarkets.length > 0 && (
            <div className="flex items-center gap-2">
              <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: orangeHex }}></div>
              <span className="text-[12px] text-[#8b9bb4]">{activeMarkets[0]} BSR</span>
            </div>
          )}
        </div>
      </div>

      {/* Detail Level BSR Trend Chart */}
      <div className="bg-[#161b24] border border-[#2a3040] rounded-2xl p-6 shadow-md flex flex-col">
        <div className="mb-4">
          <div className="flex flex-wrap items-center gap-3 mb-1">
            <h3 className="text-[17px] font-semibold text-white tracking-wide">Detail Level BSR Trend</h3>
            {productInfo?.detailCategory && (
              <span className="text-[11px] font-medium text-[#e2e8f0] bg-[#334155]/60 px-2.5 py-0.5 rounded border border-[#475569]/50 tracking-wider">
                {productInfo.detailCategory}
              </span>
            )}
          </div>
          <p className="text-[13px] text-[#64748b]">Sub-category Performance • Filtered ASINs</p>
        </div>

        <div className="h-[220px] w-full mt-2">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={detailBsrChartData} margin={{ top: 20, right: 20, left: -20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="0" stroke={gridLineColor} strokeOpacity={0.03} vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dy={10}
              />
              <YAxis
                reversed
                domain={['auto', 'auto']}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dx={-10}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#111827', border: '1px solid #374151', borderRadius: '8px', color: '#fff' }}
                itemStyle={{ fontSize: '12px' }}
                labelStyle={{ color: '#9ca3af', fontSize: '11px', marginBottom: '4px' }}
                cursor={{ stroke: '#374151', strokeWidth: 1, strokeDasharray: '3 3' }}
              />
              {activeMarkets.map((m) => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_bsr`}
                  name="Category Rank"
                  stroke={cyanHex}
                  strokeWidth={2.5}
                  fillOpacity={1}
                  fill="transparent"
                  activeDot={{ r: 6, strokeWidth: 0, fill: cyanHex }}
                  dot={{ r: 4, fill: cardBg, strokeWidth: 2, stroke: cyanHex }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Exact Legend matching screenshot */}
        <div className="mt-6 flex justify-center items-center gap-2">
          <div className="flex items-center gap-2">
            <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: cyanHex }}></div>
            <span className="text-[12px] text-[#8b9bb4]">Category Rank</span>
          </div>
        </div>
      </div>

      {/* Average Rating Chart */}
      <div className="bg-[#161b24] border border-[#2a3040] rounded-2xl p-6 shadow-md flex flex-col">
        <div className="mb-4">
          <h3 className="text-[17px] font-semibold text-white tracking-wide mb-1">Average Rating</h3>
          <p className="text-[13px] text-[#64748b]">Weekly Average (1.0 - 5.0)</p>
        </div>

        <div className="h-[220px] w-full mt-2">
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={ratingChartData} margin={{ top: 20, right: 20, left: -20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="0" stroke={gridLineColor} strokeOpacity={0.03} vertical={false} />
              <XAxis
                dataKey="label"
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dy={10}
              />
              <YAxis
                domain={[0, 5]}
                axisLine={false}
                tickLine={false}
                tick={{ fill: '#64748b', fontSize: 11, fontWeight: 500 }}
                dx={-10}
              />
              <Tooltip
                contentStyle={{ backgroundColor: '#111827', border: '1px solid #374151', borderRadius: '8px', color: '#fff' }}
                itemStyle={{ fontSize: '12px' }}
                labelStyle={{ color: '#9ca3af', fontSize: '11px', marginBottom: '4px' }}
                cursor={{ stroke: '#374151', strokeWidth: 1, strokeDasharray: '3 3' }}
              />
              {activeMarkets.map((m) => (
                <Area
                  key={m}
                  type="monotone"
                  dataKey={`${m}_rating`}
                  name="Star Rating"
                  stroke={purpleHex}
                  strokeWidth={2.5}
                  fillOpacity={1}
                  fill="transparent"
                  activeDot={{ r: 6, strokeWidth: 0, fill: purpleHex }}
                  dot={{ r: 4, fill: cardBg, strokeWidth: 2, stroke: purpleHex }}
                />
              ))}
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Exact Legend matching screenshot */}
        <div className="mt-6 flex justify-center items-center gap-2">
          <div className="flex items-center gap-2">
            <div className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: purpleHex }}></div>
            <span className="text-[12px] text-[#8b9bb4]">Star Rating</span>
          </div>
        </div>
      </div>

    </div>
  );
};

export default VendorDataView;
