/**
 * Analytics — Verstehe Reichweite, Performance und Affiliate-Umsätze im Detail
 * Referenz: docs/design-references/screen-analytics.png
 */

import { useState } from 'react';
import { useLocation } from 'wouter';
import {
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
  PieChart, Pie, Cell, FunnelChart, Funnel, LabelList,
} from 'recharts';
import { ChevronLeft, ChevronRight, Download, MoreHorizontal } from 'lucide-react';

const PERF_DATA = [
  { date: '2. Mai', TikTok: 320000, Instagram: 240000, LinkedIn: 120000, Twitter: 80000, YouTube: 40000 },
  { date: '6. Mai', TikTok: 380000, Instagram: 260000, LinkedIn: 130000, Twitter: 85000, YouTube: 45000 },
  { date: '10. Mai', TikTok: 420000, Instagram: 280000, LinkedIn: 140000, Twitter: 90000, YouTube: 50000 },
  { date: '14. Mai', TikTok: 480000, Instagram: 310000, LinkedIn: 155000, Twitter: 95000, YouTube: 55000 },
  { date: '18. Mai', TikTok: 520000, Instagram: 330000, LinkedIn: 165000, Twitter: 100000, YouTube: 60000 },
  { date: '22. Mai', TikTok: 600000, Instagram: 360000, LinkedIn: 180000, Twitter: 110000, YouTube: 65000 },
  { date: '26. Mai', TikTok: 680000, Instagram: 400000, LinkedIn: 200000, Twitter: 120000, YouTube: 70000 },
  { date: '30. Mai', TikTok: 750000, Instagram: 430000, LinkedIn: 215000, Twitter: 130000, YouTube: 75000 },
  { date: '1. Jun', TikTok: 800000, Instagram: 450000, LinkedIn: 225000, Twitter: 135000, YouTube: 80000 },
];

const CHANNEL_COLORS: Record<string, string> = {
  TikTok: '#00d4ff', Instagram: '#e1306c', LinkedIn: '#0077b5', Twitter: '#94a3b8', YouTube: '#ff0000',
};

const PIE_DATA = [
  { name: 'TikTok', value: 45, reach: '1,12 Mio.' },
  { name: 'Instagram', value: 29, reach: '721 Tsd.' },
  { name: 'LinkedIn', value: 13.2, reach: '328 Tsd.' },
  { name: 'Twitter', value: 7.7, reach: '192 Tsd.' },
  { name: 'YouTube', value: 5, reach: '124 Tsd.' },
];

const PIE_COLORS = ['#00d4ff', '#e1306c', '#0077b5', '#94a3b8', '#ff0000'];

const FUNNEL_DATA = [
  { name: 'Impressionen', value: 2480000, label: '2,48 Mio.', trend: '+28%', color: '#60a5fa' },
  { name: 'Klicks', value: 18743, label: '18.743', trend: '+21%', color: '#a78bfa' },
  { name: 'Conversions', value: 1824, label: '1.824', trend: '+23%', color: '#10b981' },
  { name: 'Umsatz', value: 24780, label: '€24.780', trend: '+24%', color: '#00d4ff' },
];

const CONTENT_ROWS = [
  { title: 'Shelly Plug S Gen3 im Fokus', category: 'Smart Home Review', platform: 'TikTok', impressions: 512340, impressionsTrend: 26, engagement: 33742, engagementTrend: 18, clicks: 2914, clicksTrend: 22, revenue: '€4.932', revenueTrend: 31, image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=40&h=40&fit=crop' },
  { title: 'Airfryer Trends 2025', category: 'Küchen & Leben', platform: 'Instagram', impressions: 387211, impressionsTrend: 19, engagement: 24118, engagementTrend: 14, clicks: 2145, clicksTrend: 18, revenue: '€3.781', revenueTrend: 21, image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=40&h=40&fit=crop' },
  { title: 'Balkonkraftwerk im Aufwind', category: 'Energie sparen', platform: 'LinkedIn', impressions: 298567, impressionsTrend: 17, engagement: 15402, engagementTrend: 12, clicks: 1876, clicksTrend: 16, revenue: '€3.126', revenueTrend: 19, image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=40&h=40&fit=crop' },
  { title: 'KI-News Update', category: 'Tech & Innovation', platform: 'Twitter', impressions: 192853, impressionsTrend: 9, engagement: 9421, engagementTrend: 8, clicks: 823, clicksTrend: 11, revenue: '€1.342', revenueTrend: 15, image: 'https://images.unsplash.com/photo-1677442135703-1787eea5ce01?w=40&h=40&fit=crop' },
  { title: 'Smart Metering erklärt', category: 'Energie einfach verstehen', platform: 'YouTube', impressions: 161902, impressionsTrend: 13, engagement: 7821, engagementTrend: 10, clicks: 612, clicksTrend: 9, revenue: '€1.107', revenueTrend: 12, image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=40&h=40&fit=crop' },
];

const PLATFORM_ICONS: Record<string, string> = { TikTok: '🎵', Instagram: '📸', LinkedIn: '💼', Twitter: '✗', YouTube: '▶' };

const TOP_CONTENT = [
  { rank: 1, title: 'Shelly Plug S Gen3 im Fokus', revenue: '€4.932', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { rank: 2, title: 'Airfryer Trends 2025', revenue: '€3.781', image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=60&h=60&fit=crop' },
  { rank: 3, title: 'Balkonkraftwerk', revenue: '€3.126', image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=60&h=60&fit=crop' },
  { rank: 4, title: 'KI-News Update', revenue: '€1.342', image: 'https://images.unsplash.com/photo-1677442135703-1787eea5ce01?w=60&h=60&fit=crop' },
  { rank: 5, title: 'Smart Metering erklärt', revenue: '€1.107', image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=60&h=60&fit=crop' },
];

const RANK_COLORS = ['#f59e0b', '#94a3b8', '#cd7f32', '#64748b', '#64748b'];

function formatNum(n: number) {
  if (n >= 1000000) return `${(n / 1000000).toFixed(2)} Mio.`;
  if (n >= 1000) return `${(n / 1000).toFixed(0)} Tsd.`;
  return n.toLocaleString('de-DE');
}

export default function Analytics() {
  const [metric, setMetric] = useState('Reichweite');
  const [period, setPeriod] = useState('Täglich');
  const [timePeriod, setTimePeriod] = useState('30 Tage');

  return (
    <div className="p-5 animate-fade-in-up space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Analytics</h1>
          <p className="text-sm mt-0.5" style={{ color: 'var(--muted-foreground)' }}>Verstehe Reichweite, Performance und Affiliate-Umsätze im Detail.</p>
        </div>
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-1.5 px-3 py-1.5 rounded" style={{ background: 'var(--atlas-surface)', border: '1px solid var(--atlas-border)' }}>
            <span className="text-xs" style={{ color: 'var(--foreground)' }}>26. Mai – 1. Juni 2025</span>
          </div>
          {['7 Tage', '30 Tage', 'Benutzerdefiniert'].map(p => (
            <button
              key={p}
              onClick={() => setTimePeriod(p)}
              className="text-xs px-3 py-1.5 rounded transition-all"
              style={{
                background: timePeriod === p ? 'var(--atlas-cyan)' : 'var(--atlas-surface)',
                color: timePeriod === p ? 'var(--atlas-navy)' : 'var(--muted-foreground)',
                border: `1px solid ${timePeriod === p ? 'var(--atlas-cyan)' : 'var(--atlas-border)'}`,
                fontWeight: timePeriod === p ? 600 : 400,
              }}
            >
              {p}
            </button>
          ))}
        </div>
      </div>

      {/* KPI Bar */}
      <div className="grid grid-cols-5 gap-3">
        {[
          { label: 'Reichweite gesamt', value: '2,48 Mio.', trend: '↑ 28%', color: '#60a5fa', icon: '👥' },
          { label: 'Engagement-Rate', value: '4,32 %', trend: '↑ 15%', color: '#e1306c', icon: '❤️' },
          { label: 'Klicks auf Affiliate-Links', value: '18.743', trend: '↑ 21%', color: '#10b981', icon: '🔗' },
          { label: 'Affiliate-Umsatz', value: '€24.780', trend: '↑ 24%', color: '#a78bfa', icon: '💎' },
          { label: 'Top Kanal', value: 'TikTok', sub: '1,12 Mio. Reichweite', color: '#00d4ff', icon: '🎵' },
        ].map((kpi, i) => (
          <div key={i} className="atlas-kpi-card">
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{kpi.label}</span>
              <span style={{ fontSize: '14px' }}>{kpi.icon}</span>
            </div>
            <div className="font-bold" style={{ fontFamily: 'var(--font-mono)', color: kpi.color, fontSize: i === 4 ? '1rem' : '1.25rem' }}>{kpi.value}</div>
            <div className="text-xs mt-1" style={{ color: 'var(--atlas-green)' }}>{kpi.trend || kpi.sub} vs. vorherige 30 Tage</div>
          </div>
        ))}
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-3 gap-4">
        {/* Performance über Zeit */}
        <div className="col-span-2 atlas-card p-4">
          <div className="flex items-center justify-between mb-3">
            <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Performance über Zeit</h2>
            <div className="flex items-center gap-2">
              <select
                className="text-xs px-2 py-1 rounded"
                style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}
                value={metric}
                onChange={e => setMetric(e.target.value)}
              >
                <option>Reichweite</option>
                <option>Engagement</option>
                <option>Klicks</option>
              </select>
              <select
                className="text-xs px-2 py-1 rounded"
                style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}
                value={period}
                onChange={e => setPeriod(e.target.value)}
              >
                <option>Täglich</option>
                <option>Wöchentlich</option>
              </select>
            </div>
          </div>
          <ResponsiveContainer width="100%" height={200}>
            <LineChart data={PERF_DATA} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.05)" />
              <XAxis dataKey="date" tick={{ fill: '#64748b', fontSize: 10 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fill: '#64748b', fontSize: 10 }} axisLine={false} tickLine={false} tickFormatter={v => v >= 1000 ? `${v / 1000}K` : v.toString()} />
              <Tooltip
                contentStyle={{ background: '#0f1629', border: '1px solid #1e2d4a', borderRadius: '6px', fontSize: '11px' }}
                labelStyle={{ color: '#94a3b8' }}
                formatter={(v: number) => [formatNum(v), '']}
              />
              <Legend wrapperStyle={{ fontSize: '10px' }} />
              {Object.keys(CHANNEL_COLORS).map(ch => (
                <Line key={ch} type="monotone" dataKey={ch} stroke={CHANNEL_COLORS[ch]} strokeWidth={1.5} dot={false} />
              ))}
            </LineChart>
          </ResponsiveContainer>
        </div>

        {/* Reichweite nach Kanal */}
        <div className="atlas-card p-4">
          <h2 className="text-sm font-semibold mb-3" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Reichweite nach Kanal</h2>
          <div className="flex justify-center mb-3">
            <div className="relative" style={{ width: '140px', height: '140px' }}>
              <PieChart width={140} height={140}>
                <Pie data={PIE_DATA} cx={65} cy={65} innerRadius={42} outerRadius={65} dataKey="value" startAngle={90} endAngle={-270}>
                  {PIE_DATA.map((_, i) => <Cell key={i} fill={PIE_COLORS[i]} />)}
                </Pie>
              </PieChart>
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                <div className="text-sm font-bold" style={{ fontFamily: 'var(--font-mono)', color: 'var(--atlas-cyan)' }}>2,48 Mio.</div>
                <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Gesamt</div>
              </div>
            </div>
          </div>
          <div className="space-y-1.5">
            {PIE_DATA.map((d, i) => (
              <div key={d.name} className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: PIE_COLORS[i] }} />
                <span className="text-xs flex-1" style={{ color: 'var(--foreground)' }}>{d.name}</span>
                <span className="text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>{d.reach}</span>
                <span className="text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>({d.value}%)</span>
              </div>
            ))}
          </div>
          <div className="text-xs mt-2" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Zeitraum: 26. Mai – 1. Juni 2025</div>
        </div>
      </div>

      {/* Content Performance Table + Funnel */}
      <div className="grid grid-cols-3 gap-4">
        {/* Table */}
        <div className="col-span-2 atlas-card overflow-hidden">
          <div className="p-3 flex items-center justify-between" style={{ borderBottom: '1px solid var(--atlas-border)' }}>
            <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Content Performance</h2>
            <div className="flex items-center gap-2">
              <select className="text-xs px-2 py-1 rounded" style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
                <option>Sortieren nach: Umsatz</option>
              </select>
              <button className="atlas-btn-ghost text-xs gap-1"><Download size={11} /> Exportieren</button>
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--atlas-border)' }}>
                {['Inhalt', 'Plattform', 'Impressionen', 'Engagement', 'Klicks', 'Umsatz'].map(h => (
                  <th key={h} style={{ padding: '8px 10px', textAlign: 'left' }}>
                    <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{h}</span>
                  </th>
                ))}
                <th />
              </tr>
            </thead>
            <tbody>
              {CONTENT_ROWS.map((row, i) => (
                <tr key={i} style={{ borderBottom: i < CONTENT_ROWS.length - 1 ? '1px solid var(--atlas-border)' : 'none' }}>
                  <td style={{ padding: '8px 10px' }}>
                    <div className="flex items-center gap-2">
                      <img src={row.image} alt={row.title} className="rounded" style={{ width: '32px', height: '32px', objectFit: 'cover' }} onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                      <div>
                        <div className="text-xs font-medium" style={{ color: 'var(--foreground)' }}>{row.title}</div>
                        <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>{row.category}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <span className="text-xs">{PLATFORM_ICONS[row.platform]}</span>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <div className="text-xs font-mono" style={{ color: 'var(--foreground)' }}>{row.impressions.toLocaleString('de-DE')}</div>
                    <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑ {row.impressionsTrend}%</div>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <div className="text-xs font-mono" style={{ color: 'var(--foreground)' }}>{row.engagement.toLocaleString('de-DE')}</div>
                    <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑ {row.engagementTrend}%</div>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <div className="text-xs font-mono" style={{ color: 'var(--foreground)' }}>{row.clicks.toLocaleString('de-DE')}</div>
                    <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑ {row.clicksTrend}%</div>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <div className="text-xs font-bold font-mono" style={{ color: 'var(--atlas-green)' }}>{row.revenue}</div>
                    <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑ {row.revenueTrend}%</div>
                  </td>
                  <td style={{ padding: '8px 10px' }}>
                    <button style={{ color: 'var(--muted-foreground)' }}><MoreHorizontal size={12} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="flex items-center justify-between px-3 py-2" style={{ borderTop: '1px solid var(--atlas-border)' }}>
            <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>1–5 von 25 Einträgen</span>
            <div className="flex items-center gap-1">
              <button className="atlas-btn-ghost p-1"><ChevronLeft size={12} /></button>
              {[1,2,3,4,5].map(p => (
                <button key={p} className="w-6 h-6 text-xs rounded" style={{ background: p === 1 ? 'oklch(0.82 0.18 210 / 0.12)' : 'transparent', color: p === 1 ? 'var(--atlas-cyan)' : 'var(--muted-foreground)' }}>{p}</button>
              ))}
              <button className="atlas-btn-ghost p-1"><ChevronRight size={12} /></button>
            </div>
            <select className="text-xs px-2 py-1 rounded" style={{ background: 'var(--atlas-surface)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
              <option>5 pro Seite</option>
            </select>
          </div>
        </div>

        {/* Funnel + Insights */}
        <div className="space-y-3">
          <div className="atlas-card p-4">
            <div className="flex items-center justify-between mb-3">
              <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Performance-Funnel</h2>
              <select className="text-xs px-2 py-1 rounded" style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
                <option>Gesamt (alle Kanäle)</option>
              </select>
            </div>
            <div className="space-y-2">
              {FUNNEL_DATA.map((stage, i) => (
                <div key={stage.name}>
                  <div className="flex items-center justify-between mb-1">
                    <div className="flex items-center gap-2">
                      <div className="w-4 h-4 rounded flex items-center justify-center" style={{ background: `${stage.color}20` }}>
                        <span style={{ fontSize: '10px' }}>{['👁', '🖱', '🛒', '💎'][i]}</span>
                      </div>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{stage.name}</span>
                    </div>
                    <div className="text-right">
                      <div className="text-xs font-bold" style={{ fontFamily: 'var(--font-mono)', color: stage.color }}>{stage.label}</div>
                      <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑ {stage.trend}</div>
                    </div>
                  </div>
                  <div className="h-1.5 rounded-full" style={{ background: 'var(--atlas-navy)' }}>
                    <div
                      className="h-full rounded-full"
                      style={{ width: `${[100, 0.76, 0.074, 1][i] || Math.max(2, (stage.value / 2480000) * 100)}%`, background: stage.color }}
                    />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="atlas-card p-3">
            <div className="text-xs font-semibold mb-2" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Insights</div>
            <div className="space-y-2">
              {[
                { color: '#f59e0b', text: 'TikTok liefert die höchste Reichweite, Instagram die beste Engagement-Rate.' },
                { color: '#10b981', text: 'Inhalte zu Smart Home & Küche generieren den höchsten Umsatz.' },
                { color: '#a78bfa', text: 'Deine CTR ist um 21% gestiegen – stark über dem Vorjahreswert.' },
              ].map((ins, i) => (
                <div key={i} className="flex gap-2">
                  <div className="w-1.5 h-1.5 rounded-full mt-1.5 flex-shrink-0" style={{ background: ins.color }} />
                  <p className="text-xs" style={{ color: 'var(--muted-foreground)', lineHeight: '1.5' }}>{ins.text}</p>
                </div>
              ))}
            </div>
            <button className="text-xs mt-2" style={{ color: 'var(--atlas-cyan)' }}>Alle Insights anzeigen →</button>
          </div>
        </div>
      </div>

      {/* Top Inhalte */}
      <div className="atlas-card p-4">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Top Inhalte</h2>
          <button className="text-xs" style={{ color: 'var(--atlas-cyan)' }}>Alle Inhalte anzeigen →</button>
        </div>
        <div className="flex gap-3">
          {TOP_CONTENT.map((item, i) => (
            <div key={i} className="flex-1 atlas-card p-2 cursor-pointer atlas-card-hover">
              <div className="relative mb-2">
                <img src={item.image} alt={item.title} className="w-full rounded" style={{ aspectRatio: '1/1', objectFit: 'cover' }} onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                <div
                  className="absolute top-1 left-1 w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold"
                  style={{ background: `${RANK_COLORS[i]}20`, color: RANK_COLORS[i], border: `1px solid ${RANK_COLORS[i]}40`, fontFamily: 'var(--font-mono)', fontSize: '0.6rem' }}
                >
                  {item.rank}
                </div>
              </div>
              <div className="text-xs font-medium truncate" style={{ color: 'var(--foreground)', fontSize: '0.6875rem' }}>{item.title}</div>
              <div className="text-xs font-bold mt-0.5" style={{ color: 'var(--atlas-green)', fontFamily: 'var(--font-mono)' }}>{item.revenue} Umsatz</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
