/**
 * Produkte — Verwalte Produktdaten, Affiliate-Links und Content-Potenziale
 * Referenz: docs/design-references/screen-produkte.png
 */

import { useState } from 'react';
import { useLocation } from 'wouter';
import { Search, Filter, ChevronLeft, ChevronRight, Link, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { useCatalog } from '@/hooks/useCatalog';

const FILTER_TABS = ['Alle', 'Smart Home', 'Kitchen', 'Energie', 'News Tie-in', 'High Potential', 'Verfügbar'];

const MOCK_PRODUCTS = [
  { id: '1', name: 'Shelly Plug S Gen3', sku: 'SPS-3GEN3', category: 'Smart Home', price: '€24,95', retailer: 'Amazon', available: true, score: 92, scoreTrend: 18, affiliate: true, image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { id: '2', name: 'Shelly Plus 1', sku: 'SHPL-1', category: 'Smart Home', price: '€19,95', retailer: 'Alternate', available: true, score: 88, scoreTrend: 12, affiliate: true, image: 'https://images.unsplash.com/photo-1558618047-3c8c76ca7d13?w=60&h=60&fit=crop' },
  { id: '3', name: 'Shelly Wall Display', sku: 'SWD-1', category: 'Smart Home', price: '€89,00', retailer: 'Amazon', available: true, score: 85, scoreTrend: 10, affiliate: true, image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { id: '4', name: 'Airfryer Pro X', sku: 'AF-PRO-X', category: 'Kitchen', price: '€129,00', retailer: 'MediaMarkt', available: true, score: 90, scoreTrend: 22, affiliate: true, image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=60&h=60&fit=crop' },
  { id: '5', name: 'Balkonkraftwerk Starter', sku: 'BK-START-800', category: 'Energie', price: '€499,00', retailer: 'ManoMano', available: true, score: 87, scoreTrend: 16, affiliate: true, image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=60&h=60&fit=crop' },
];

const TOP_PRODUCTS = [
  { rank: 1, name: 'Shelly Plug S Gen3', category: 'Smart Home', score: 92, clicks: 1246, trend: 18 },
  { rank: 2, name: 'Airfryer Pro X', category: 'Kitchen', score: 90, clicks: 1102, trend: 22 },
  { rank: 3, name: 'Shelly Plus 1', category: 'Smart Home', score: 88, clicks: 934, trend: 12 },
  { rank: 4, name: 'Balkonkraftwerk Starter', category: 'Energie', score: 87, clicks: 887, trend: 16 },
  { rank: 5, name: 'Shelly Wall Display', category: 'Smart Home', score: 85, clicks: 731, trend: 10 },
];

function ScoreBadge({ score }: { score: number }) {
  const color = score >= 90 ? '#10b981' : score >= 80 ? '#00d4ff' : '#f59e0b';
  return (
    <div
      className="flex items-center justify-center rounded-full font-bold"
      style={{ width: '40px', height: '40px', background: `${color}20`, border: `2px solid ${color}`, color, fontFamily: 'var(--font-mono)', fontSize: '0.875rem' }}
    >
      {score}
    </div>
  );
}

export default function Products() {
  const [, navigate] = useLocation();
  const [activeFilter, setActiveFilter] = useState('Alle');
  const [search, setSearch] = useState('');
  const { products: catalogProducts } = useCatalog();

  const products = catalogProducts.length > 0
    ? catalogProducts.slice(0, 5).map((p, i) => ({
        ...MOCK_PRODUCTS[i % MOCK_PRODUCTS.length],
        id: p.id,
        name: p.name,
        price: `€${p.price?.toFixed(2) || '0,00'}`,
      }))
    : MOCK_PRODUCTS;

  const copyAffiliateLink = (product: typeof MOCK_PRODUCTS[0]) => {
    const url = `https://shelly.shop/${product.sku.toLowerCase()}?utm_source=atlassocial&utm_medium=social&utm_campaign=${product.sku.toLowerCase()}`;
    navigator.clipboard.writeText(url);
    toast.success(`Affiliate-Link für ${product.name} kopiert`);
  };

  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)' }}>Produkte</h1>
          <p className="text-sm mt-0.5" style={{ color: 'var(--muted-foreground)' }}>Verwalte Produktdaten, Affiliate-Links und Content-Potenziale.</p>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-xs px-2 py-1 rounded" style={{ background: 'var(--atlas-surface)', border: '1px solid var(--atlas-border)', color: 'var(--muted-foreground)' }}>7 Tage</span>
        </div>
      </div>

      {/* KPI Bar */}
      <div className="grid grid-cols-4 gap-3">
        {[
          { label: 'Produkte aktiv', value: '156', trend: '↑ 12% vs. letzte Woche', color: '#60a5fa' },
          { label: 'Mit Affiliate-Link', value: '128', trend: '↑ 18% vs. letzte Woche', color: '#a78bfa' },
          { label: 'Top Performer (Score)', value: 'Shelly Plug S Gen3', sub: 'Score 92', color: '#f59e0b' },
          { label: 'Ø Conversion', value: '3,24%', trend: '↑ 0,6% vs. letzte Woche', color: '#00d4ff' },
        ].map((kpi, i) => (
          <div key={i} className="atlas-kpi-card">
            <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)' }}>{kpi.label}</div>
            <div className="font-bold" style={{ fontFamily: 'var(--font-mono)', color: kpi.color, fontSize: i === 2 ? '0.875rem' : '1.25rem' }}>{kpi.value}</div>
            <div className="text-xs mt-1" style={{ color: 'var(--muted-foreground)' }}>{kpi.trend || kpi.sub}</div>
          </div>
        ))}
      </div>

      {/* Filter Tabs */}
      <div className="flex items-center gap-1.5 flex-wrap">
        {FILTER_TABS.map(tab => (
          <button
            key={tab}
            onClick={() => setActiveFilter(tab)}
            className="px-3 py-1.5 rounded text-xs font-medium transition-all"
            style={{
              background: activeFilter === tab ? 'oklch(0.82 0.18 210 / 0.12)' : 'var(--atlas-surface)',
              color: activeFilter === tab ? 'var(--atlas-cyan)' : 'var(--muted-foreground)',
              border: `1px solid ${activeFilter === tab ? 'oklch(0.82 0.18 210 / 0.3)' : 'var(--atlas-border)'}`,
            }}
          >
            {tab}
          </button>
        ))}
        <div className="ml-auto flex items-center gap-2">
          <div className="relative">
            <Search size={12} className="absolute left-2 top-1/2 -translate-y-1/2" style={{ color: 'var(--muted-foreground)' }} />
            <input
              className="atlas-input pl-7 text-xs"
              placeholder="Produkte suchen..."
              value={search}
              onChange={e => setSearch(e.target.value)}
              style={{ width: '180px' }}
            />
          </div>
          <button className="atlas-btn-ghost p-1.5"><Filter size={13} /></button>
        </div>
      </div>

      <div className="flex gap-4">
        {/* Product Table */}
        <div className="flex-1 min-w-0">
          <div className="atlas-card overflow-hidden">
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--atlas-border)' }}>
                  {['Produkt', 'Kategorie', 'Preis', 'Händler', 'Verfügbarkeit', 'Content Score ⓘ', 'Affiliate', 'Aktionen'].map(h => (
                    <th key={h} style={{ padding: '10px 12px', textAlign: 'left' }}>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{h}</span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {products.map((product, i) => (
                  <tr key={product.id} style={{ borderBottom: i < products.length - 1 ? '1px solid var(--atlas-border)' : 'none' }}>
                    <td style={{ padding: '10px 12px' }}>
                      <div className="flex items-center gap-2">
                        <img src={product.image} alt={product.name} className="rounded" style={{ width: '40px', height: '40px', objectFit: 'cover' }} onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                        <div>
                          <div className="text-xs font-medium" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-display)' }}>{product.name}</div>
                          <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)', fontSize: '0.6rem' }}>{product.sku}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <span className="text-xs px-2 py-0.5 rounded" style={{ background: 'oklch(0.82 0.18 210 / 0.08)', color: 'var(--atlas-cyan)', border: '1px solid oklch(0.82 0.18 210 / 0.2)', fontSize: '0.6rem' }}>
                        {product.category}
                      </span>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <span className="text-xs font-bold" style={{ fontFamily: 'var(--font-mono)', color: 'var(--foreground)' }}>{product.price}</span>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{product.retailer}</span>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <div className="flex items-center gap-1">
                        <div className="atlas-status-dot online" />
                        <span className="text-xs" style={{ color: 'var(--atlas-green)' }}>Verfügbar</span>
                      </div>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <div className="flex items-center gap-2">
                        <ScoreBadge score={product.score} />
                        <div>
                          <div className="text-xs" style={{ color: 'var(--atlas-green)', fontFamily: 'var(--font-mono)' }}>↑ +{product.scoreTrend}%</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <div className="flex items-center gap-1">
                        <Link size={11} style={{ color: 'var(--atlas-cyan)' }} />
                        <span className="text-xs" style={{ color: 'var(--atlas-cyan)' }}>Aktiv</span>
                      </div>
                    </td>
                    <td style={{ padding: '10px 12px' }}>
                      <div className="flex flex-col gap-1">
                        <button
                          onClick={() => navigate('/drafts')}
                          className="text-xs px-2 py-1 rounded whitespace-nowrap"
                          style={{ background: 'var(--atlas-cyan)', color: 'var(--atlas-navy)', fontWeight: 600, fontSize: '0.6rem' }}
                        >
                          Als Draft nutzen
                        </button>
                        <button
                          onClick={() => copyAffiliateLink(product)}
                          className="text-xs px-2 py-1 rounded whitespace-nowrap"
                          style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--muted-foreground)', fontSize: '0.6rem' }}
                        >
                          Link kopieren
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {/* Pagination */}
            <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 156 Produkten</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>
                ))}
                <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>... 32</span>
                <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>
                <option>10 pro Seite</option>
              </select>
            </div>
          </div>
        </div>

        {/* Right Sidebar */}
        <div className="w-56 flex-shrink-0 space-y-3">
          <div className="atlas-card p-3">
            <div className="text-xs font-semibold mb-2" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Top Produkte für Content</div>
            <div className="flex gap-2 mb-2">
              <button className="text-xs px-2 py-1 rounded" style={{ background: 'oklch(0.82 0.18 210 / 0.12)', color: 'var(--atlas-cyan)', border: '1px solid oklch(0.82 0.18 210 / 0.3)' }}>Nach Score</button>
              <button className="text-xs px-2 py-1 rounded" style={{ background: 'transparent', color: 'var(--muted-foreground)', border: '1px solid var(--atlas-border)' }}>Nach erw. Klicks</button>
            </div>
            <div className="space-y-2">
              {TOP_PRODUCTS.map(p => (
                <div key={p.rank} className="flex items-center gap-2">
                  <span className="text-xs font-bold" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)', width: '16px' }}>({p.rank})</span>
                  <div className="flex-1 min-w-0">
                    <div className="text-xs truncate" style={{ color: 'var(--foreground)' }}>{p.name}</div>
                    <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>{p.category} · Erw. Klicks {p.clicks.toLocaleString('de-DE')}</div>
                  </div>
                  <div className="text-right">
                    <div className="text-xs font-bold" style={{ fontFamily: 'var(--font-mono)', color: 'var(--atlas-cyan)' }}>{p.score}</div>
                    <div className="text-xs" style={{ color: 'var(--atlas-green)', fontSize: '0.6rem' }}>↑{p.trend}%</div>
                  </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">
              {[
                'Smart Home Produkte erzielen aktuell die höchste Engagement-Rate (+14%).',
                'Fokus auf Shelly Plug S Gen3 beibehalten.',
              ].map((t, 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: 'var(--atlas-cyan)' }} />
                  <p className="text-xs" style={{ color: 'var(--muted-foreground)', lineHeight: '1.5' }}>{t}</p>
                </div>
              ))}
            </div>
            <button className="text-xs mt-2" style={{ color: 'var(--atlas-cyan)' }}>Weitere Insights anzeigen →</button>
          </div>
        </div>
      </div>
    </div>
  );
}
