'use client';
import React, { useState, useMemo } from 'react';

export default function AdminDashboardClient({ 
  actions, 
  products,
  totalVisitors,
  totalProducts,
  analyticsSummary
}: { 
  actions: any[], 
  products: any[],
  totalVisitors: number,
  totalProducts: number,
  analyticsSummary?: any
}) {
  const [timeFilter, setTimeFilter] = useState<'weekly' | 'monthly'>('weekly');
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);

  // Reset selection when filter changes
  const handleFilterChange = (val: 'weekly' | 'monthly') => {
    setTimeFilter(val);
    setSelectedIndex(null);
  };

  const handlePrint = () => {
    window.print();
  };

  // 1. Determine active actions based on filters and selections
  const filteredActions = useMemo(() => {
    const now = new Date();
    if (selectedIndex !== null) {
      if (timeFilter === 'weekly') {
        const d = new Date(now);
        d.setDate(d.getDate() - ((5 - selectedIndex) * 7));
        const weekStart = new Date(d);
        weekStart.setDate(weekStart.getDate() - 7);
        return actions.filter(a => {
            const actDate = new Date(a.createdAt);
            return actDate >= weekStart && actDate <= d;
        });
      } else {
        const d = new Date(now);
        d.setMonth(d.getMonth() - (5 - selectedIndex));
        return actions.filter(a => {
            const actDate = new Date(a.createdAt);
            return actDate.getMonth() === d.getMonth() && actDate.getFullYear() === d.getFullYear();
        });
      }
    } else {
      let startTime = new Date();
      if (timeFilter === 'weekly') {
        startTime.setDate(now.getDate() - 42); 
      } else {
        startTime.setMonth(now.getMonth() - 5);
        startTime.setDate(1);
      }
      return actions.filter(a => new Date(a.createdAt) >= startTime);
    }
  }, [actions, timeFilter, selectedIndex]);

  // Process Live Conversion Stream Table (Synced)
  const visitorActivity = useMemo(() => {
    const userMap = new Map();
    const recentActions = [...filteredActions].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    
    recentActions.forEach(act => {
      const vid = act.visitorId || 'Unknown';
      if (!userMap.has(vid)) {
        userMap.set(vid, {
          user: vid,
          time: new Date(act.createdAt).toLocaleString(),
          itemsViewed: 0,
          clicks: 0
        });
      }
      const u = userMap.get(vid);
      if (act.actionType === 'VIEW') u.itemsViewed += 1;
      if (act.actionType === 'CLICK') u.clicks += 1;
    });

    return Array.from(userMap.values()).slice(0, 10).map(u => ({
      ...u,
      clicked: u.clicks > 0 ? 'Yes' : 'No'
    }));
  }, [filteredActions]);

  // Process High Interest Products (Synced) - with lightweight icons
  const highInterestProducts = useMemo(() => {
    const productMap = new Map();
    products.forEach(p => {
      // Generate deterministic avatar/icon based on product name initials
      const initials = p.name.split(' ').map((w: string) => w[0]).join('').slice(0, 2).toUpperCase();
      const iconColor = getIconColor(p.id);
      productMap.set(p.id, {
        name: p.name,
        initials,
        iconColor,
        affiliateLink: p.affiliateLink || '',
        views: 0,
        clicks: 0
      });
    });

    filteredActions.forEach(act => {
      if (act.entityId && productMap.has(act.entityId)) {
        const p = productMap.get(act.entityId);
        if (act.actionType === 'VIEW') p.views += 1;
        if (act.actionType === 'CLICK') p.clicks += 1;
      }
    });

    return Array.from(productMap.values())
      .filter(p => p.views > 0 || p.clicks > 0)
      .sort((a, b) => b.views - a.views)
      .slice(0, 5)
      .map(p => {
        let site = 'Unknown';
        if (p.affiliateLink.includes('amazon.com')) site = 'Amazon';
        else if (p.affiliateLink.includes('shareasale.com')) site = 'ShareASale';
        else if (p.affiliateLink.includes('clickbank.net')) site = 'ClickBank';
        else if (p.affiliateLink.length > 0) site = new URL(p.affiliateLink).hostname.replace('www.', '');
        return { ...p, site };
      });
  }, [filteredActions, products]);

  // Helper: Generate consistent color from string
  function getIconColor(seed: string): string {
    const colors = [
      'bg-emerald-500 text-white',
      'bg-blue-500 text-white',
      'bg-amber-500 text-white',
      'bg-rose-500 text-white',
      'bg-indigo-500 text-white',
      'bg-teal-500 text-white',
      'bg-orange-500 text-white',
      'bg-pink-500 text-white'
    ];
    let hash = 0;
    for (let i = 0; i < seed.length; i++) hash = seed.charCodeAt(i) + ((hash << 5) - hash);
    return colors[Math.abs(hash) % colors.length];
  }

  // Process Chart Data
  const chartData = useMemo(() => {
    const data = [];
    const now = new Date();

    if (timeFilter === 'weekly') {
      // Last 6 weeks
      for (let i = 5; i >= 0; i--) {
        const d = new Date(now);
        d.setDate(d.getDate() - (i * 7));
        
        // Calculate ISO week number roughly
        const startDate = new Date(d.getFullYear(), 0, 1);
        const days = Math.floor((d.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));
        const weekNumber = Math.ceil((days + startDate.getDay() + 1) / 7);
        
        const weekLabel = `Wk ${weekNumber}, ${d.getFullYear()}`;
        
        // To accurately count actions for the week in real life, you'd filter actions between [d - 7 days] and [d]
        const weekStart = new Date(d);
        weekStart.setDate(weekStart.getDate() - 7);
        const weekActions = actions.filter(a => {
            const actDate = new Date(a.createdAt);
            return actDate >= weekStart && actDate <= d;
        });
        
        const views = weekActions.filter(a => a.actionType === 'VIEW').length;
        const clicks = weekActions.filter(a => a.actionType === 'CLICK').length;
        const uniqueVisitors = new Set(weekActions.map(a => a.visitorId).filter(Boolean)).size;
        const uniqueProducts = new Set(weekActions.map(a => a.entityId).filter(Boolean)).size;
        
        data.push({ label: weekLabel, views, clicks, uniqueVisitors, uniqueProducts });
      }
    } else {
      // Last 6 months
      for (let i = 5; i >= 0; i--) {
        const d = new Date(now);
        d.setMonth(d.getMonth() - i);
        const monthLabel = `${d.toLocaleString('en-US', { month: 'short' })} ${d.getFullYear()}`;
        
        const monthActions = actions.filter(a => {
            const actDate = new Date(a.createdAt);
            return actDate.getMonth() === d.getMonth() && actDate.getFullYear() === d.getFullYear();
        });
        
        const views = monthActions.filter(a => a.actionType === 'VIEW').length;
        const clicks = monthActions.filter(a => a.actionType === 'CLICK').length;
        const uniqueVisitors = new Set(monthActions.map(a => a.visitorId).filter(Boolean)).size;
        const uniqueProducts = new Set(monthActions.map(a => a.entityId).filter(Boolean)).size;
        
        data.push({ label: monthLabel, views, clicks, uniqueVisitors, uniqueProducts });
      }
    }
    
    return data;
  }, [actions, timeFilter]);

  // Minimum scale logic + 30% padding so trendline and labels fit above bars cleanly
  const absoluteMax = Math.max(...chartData.map(d => Math.max(d.views, d.clicks)), 5);
  const maxChartValue = Math.ceil(absoluteMax * 1.3);

  const displayViews = selectedIndex !== null ? chartData[selectedIndex].views : filteredActions.filter(a => a.actionType === 'VIEW').length;
  const displayClicks = selectedIndex !== null ? chartData[selectedIndex].clicks : filteredActions.filter(a => a.actionType === 'CLICK').length;
  const displayVisitors = selectedIndex !== null ? chartData[selectedIndex].uniqueVisitors : new Set(filteredActions.map(a => a.visitorId).filter(Boolean)).size;
  const displayProducts = selectedIndex !== null ? chartData[selectedIndex].uniqueProducts : new Set(filteredActions.map(a => a.entityId).filter(Boolean)).size;

  const periodLabel = useMemo(() => {
    if (selectedIndex !== null) return chartData[selectedIndex].label;
    if (chartData.length > 0) return `${chartData[0].label} — ${chartData[chartData.length - 1].label}`;
    return '';
  }, [chartData, selectedIndex]);

  return (
    <div className="space-y-12 print:space-y-6">
      {/* Top Header Section */}
      <header className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 print:pb-4 print:border-b print:border-zinc-200">
        <div>
          <h1 className="text-4xl font-headline text-primary">Overview</h1>
          <p className="text-on-surface-variant mt-2 italic">
            Performance metrics and conversion insights.
            <span className="block md:inline font-bold text-emerald-600 print:text-zinc-800 md:ml-2 mt-1 md:mt-0">{periodLabel}</span>
          </p>
        </div>
        <div className="flex items-center gap-4">
          <select 
            value={timeFilter}
            onChange={(e) => handleFilterChange(e.target.value as any)}
            className="bg-white border border-outline-variant/30 rounded-xl px-4 py-2 text-sm font-bold text-primary focus:outline-none focus:ring-2 focus:ring-emerald-500/20 cursor-pointer"
          >
            <option value="weekly">Weekly</option>
            <option value="monthly">Month by Month</option>
          </select>
          <button 
            onClick={handlePrint}
            className="flex items-center gap-2 bg-zinc-900 text-white px-5 py-2.5 rounded-xl text-sm font-bold hover:bg-zinc-800 transition-colors shadow-sm print:hidden"
          >
            <span className="material-symbols-outlined text-sm">print</span>
            Print / Export
          </button>
        </div>
      </header>

      {/* Middle Section: Chart & Totals */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 print:gap-4 print:block">
        {/* Bar Charts Area */}
        <section className="lg:col-span-2 bg-white p-8 rounded-[2rem] shadow-sm border border-outline-variant/10 print:p-0 print:border-0 print:shadow-none print:mb-8">
          <div className="flex justify-between items-center mb-8 print:mb-4">
            <h2 className="text-xl font-headline text-primary italic">Activity Overview</h2>
            <div className="flex gap-4 text-xs font-bold text-zinc-500">
              <span className="flex items-center gap-2">
                <div className="w-4 h-0 border-t-2 border-dashed border-emerald-600"></div> Trend
              </span>
              <span className="flex items-center gap-2"><div className="w-3 h-3 rounded-full bg-emerald-500"></div> Views</span>
              <span className="flex items-center gap-2"><div className="w-3 h-3 rounded-full bg-amber-500"></div> Clicks</span>
            </div>
          </div>
          <div className="h-72 flex pt-4 relative">
            {/* Vertical Y-Axis */}
            <div className="w-8 flex flex-col justify-between items-end pr-2 text-[9px] font-bold text-zinc-400 pb-5">
              <span>{maxChartValue}</span>
              <span>{Math.floor(maxChartValue * 0.75)}</span>
              <span>{Math.floor(maxChartValue * 0.5)}</span>
              <span>{Math.floor(maxChartValue * 0.25)}</span>
              <span>0</span>
            </div>

            {/* Chart Area */}
            <div className="flex-1 flex items-end justify-between gap-4 relative h-full">
              {/* Dashed Trend Line (offset by -12% Y to sit above data labels) */}
              <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 w-full h-full pointer-events-none z-10">
                <polyline
                  fill="none"
                  stroke="#059669" // emerald-600
                  strokeWidth="2"
                  strokeDasharray="4 4"
                  vectorEffect="non-scaling-stroke"
                  points={chartData.map((d, i) => {
                    const x = (i + 0.5) * (100 / chartData.length);
                    const y = 100 - (d.views / maxChartValue) * 100 - 12; // Shift up above bars
                    return `${x},${y}`;
                  }).join(' ')}
                />
              </svg>

              {chartData.map((d, i) => {
                const isSelected = selectedIndex === i;
                const isFaded = selectedIndex !== null && !isSelected;
                return (
                <div 
                  key={i} 
                  onClick={() => setSelectedIndex(isSelected ? null : i)}
                  className={`flex-1 flex flex-col justify-end items-center gap-2 h-full cursor-pointer transition-all duration-300 z-20 pt-6 ${isFaded ? 'opacity-30' : 'opacity-100 hover:opacity-80'}`}
                >
                  <div className="w-full flex justify-center gap-1 md:gap-2 h-full items-end relative">
                    {/* Views Bar */}
                    <div className="relative w-1/2 flex flex-col justify-end items-center h-full">
                      <div 
                        className={`w-full rounded-t-sm absolute bottom-0 ${isSelected ? 'bg-emerald-600' : 'bg-emerald-500'}`}
                        style={{ height: `${(d.views / maxChartValue) * 100}%`, minHeight: '4px' }}
                      >
                         <span className="absolute -top-5 left-1/2 -translate-x-1/2 text-[10px] font-bold text-zinc-800">{d.views}</span>
                      </div>
                    </div>
                    {/* Clicks Bar */}
                    <div className="relative w-1/2 flex flex-col justify-end items-center h-full">
                      <div 
                        className={`w-full rounded-t-sm absolute bottom-0 ${isSelected ? 'bg-amber-600' : 'bg-amber-500'}`}
                        style={{ height: `${(d.clicks / maxChartValue) * 100}%`, minHeight: '4px' }}
                      >
                         <span className="absolute -top-5 left-1/2 -translate-x-1/2 text-[10px] font-bold text-zinc-800">{d.clicks}</span>
                      </div>
                    </div>
                  </div>
                  <span className={`text-[10px] font-bold whitespace-nowrap ${isSelected ? 'text-emerald-700' : 'text-zinc-700'}`}>{d.label}</span>
                </div>
              )})}
            </div>
          </div>
        </section>

        {/* Totals Area */}
        <section className="bg-white p-8 rounded-[2rem] shadow-sm border border-outline-variant/10 flex flex-col justify-center gap-6 relative overflow-hidden">
          {selectedIndex !== null && (
             <div className="absolute top-4 right-4 bg-emerald-50 text-emerald-700 text-[10px] font-bold px-2 py-1 rounded z-10 transition-opacity">
               Showing {chartData[selectedIndex].label}
             </div>
          )}
          
          <div className="space-y-2 transition-all pt-2">
            <p className="text-[10px] uppercase tracking-widest font-bold text-zinc-400">Total Views • <span className="text-zinc-500">{selectedIndex !== null ? chartData[selectedIndex].label : (timeFilter === 'weekly' ? 'Last 6 Weeks' : 'Last 6 Months')}</span></p>
            <p className="text-4xl font-headline text-emerald-600">{displayViews.toLocaleString()}</p>
          </div>
          <div className="h-px w-full bg-zinc-100" />
          <div className="space-y-2 transition-all">
            <p className="text-[10px] uppercase tracking-widest font-bold text-zinc-400">Link Clicks • <span className="text-zinc-500">{selectedIndex !== null ? chartData[selectedIndex].label : (timeFilter === 'weekly' ? 'Last 6 Weeks' : 'Last 6 Months')}</span></p>
            <p className="text-4xl font-headline text-amber-600">{displayClicks.toLocaleString()}</p>
          </div>
          <div className="h-px w-full bg-zinc-100" />
          <div className="space-y-2 transition-all">
            <p className="text-[10px] uppercase tracking-widest font-bold text-zinc-400">Unique Visitors • <span className="text-zinc-500">{selectedIndex !== null ? chartData[selectedIndex].label : (timeFilter === 'weekly' ? 'Last 6 Weeks' : 'Last 6 Months')}</span></p>
            <p className="text-3xl font-headline text-primary">{displayVisitors.toLocaleString()}</p>
          </div>
        </section>
      </div>

      {/* Bottom Section: Tables */}
      <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
        {/* Live Conversion Stream */}
        {/* Live Conversion Stream */}
        <section className="bg-white p-6 rounded-[2rem] shadow-sm border border-outline-variant/10 flex flex-col h-full">
          <h2 className="text-xl font-headline text-primary italic mb-4">User Activity Stream</h2>
          <div className="overflow-x-auto flex-1">
            <table className="w-full text-left text-sm text-zinc-800 border border-zinc-200">
              <thead className="text-xs uppercase tracking-widest text-zinc-700 bg-zinc-50 border-b border-zinc-200">
                <tr>
                  <th className="px-4 py-3 font-bold border-r border-zinc-200">Time</th>
                  <th className="px-4 py-3 font-bold border-r border-zinc-200">User / ID</th>
                  <th className="px-4 py-3 font-bold text-center border-r border-zinc-200">Items Viewed</th>
                  <th className="px-4 py-3 font-bold text-center">Link Clicked</th>
                </tr>
              </thead>
              <tbody>
                {visitorActivity.map((act, i) => (
                  <tr key={i} className="border-b border-zinc-200 hover:bg-zinc-50 transition-colors">
                    <td className="px-4 py-3 font-mono text-xs border-r border-zinc-200">{act.time}</td>
                    <td className="px-4 py-3 font-bold text-primary border-r border-zinc-200">{act.user.slice(0, 12)}...</td>
                    <td className="px-4 py-3 text-center border-r border-zinc-200 font-bold">{act.itemsViewed}</td>
                    <td className="px-4 py-3 text-center">
                      <span className={`px-2 py-1 rounded text-[10px] font-bold uppercase ${act.clicked === 'Yes' ? 'bg-amber-100 text-amber-800' : 'bg-zinc-100 text-zinc-600'}`}>
                        {act.clicked}
                      </span>
                    </td>
                  </tr>
                ))}
                {visitorActivity.length === 0 && (
                  <tr><td colSpan={4} className="py-8 text-center italic text-zinc-500">No recent activity</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </section>

        {/* High Interest Products */}
        <section className="bg-white p-6 rounded-[2rem] shadow-sm border border-outline-variant/10 flex flex-col h-full print:p-0 print:border-0 print:shadow-none print:break-inside-avoid">
          <h2 className="text-xl font-headline text-primary italic mb-4">High Interest Products</h2>
          <div className="overflow-x-auto flex-1">
            <table className="w-full text-left text-sm text-zinc-800 border border-zinc-200">
              <thead className="text-xs uppercase tracking-widest text-zinc-700 bg-zinc-50 border-b border-zinc-200">
                <tr>
                  <th className="px-4 py-3 font-bold border-r border-zinc-200">Product</th>
                  <th className="px-4 py-3 font-bold text-center border-r border-zinc-200">Views</th>
                  <th className="px-4 py-3 font-bold text-center border-r border-zinc-200">Link Clicks</th>
                  <th className="px-4 py-3 font-bold">Affiliate Site</th>
                </tr>
              </thead>
              <tbody>
                {highInterestProducts.map((p, i) => (
                  <tr key={i} className="border-b border-zinc-200 hover:bg-zinc-50 transition-colors">
                    <td className="px-4 py-3 flex items-center gap-3 border-r border-zinc-200">
                      {/* Lightweight initial-based icon */}
                      <div className={`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold ${p.iconColor || 'bg-emerald-500 text-white'}`}>
                        {p.initials || '??'}
                      </div>
                      <span className="font-bold text-primary truncate max-w-[150px]">{p.name}</span>
                    </td>
                    <td className="px-4 py-3 text-center border-r border-zinc-200 font-bold">{p.views}</td>
                    <td className="px-4 py-3 text-center font-bold text-amber-700 border-r border-zinc-200">{p.clicks}</td>
                    <td className="px-4 py-3">
                      <span className="px-2 py-1 bg-blue-100 text-blue-800 rounded text-xs font-bold">
                        {p.site}
                      </span>
                    </td>
                  </tr>
                ))}
                {highInterestProducts.length === 0 && (
                  <tr><td colSpan={4} className="py-8 text-center italic text-zinc-500">Not enough data to calculate interest.</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </section>
      </div>
    </div>
  );
}
