/**
 * Freigaben — Prüfe, priorisiere und genehmige Inhalte vor der Veröffentlichung
 * Referenz: docs/design-references/screen-freigaben.png
 */

import { useState } from 'react';
import { Filter, ChevronLeft, ChevronRight, MoreHorizontal, MessageSquare, Edit } from 'lucide-react';
import { toast } from 'sonner';

const FILTER_TABS = [
  { label: 'Alle', count: 48 },
  { label: 'Dringend', count: 7, color: '#ef4444' },
  { label: 'Mit Affiliate', count: 15 },
  { label: 'TikTok', count: 16 },
  { label: 'Instagram', count: 14 },
  { label: 'LinkedIn', count: 11 },
  { label: 'Review', count: 37 },
  { label: 'Blockiert', count: 3, color: '#ef4444' },
];

const QUEUE = [
  { priority: 'Dringend', title: 'Shelly Plug S Gen3 im Fokus', platform: 'TikTok', product: 'Shelly Plug S Gen3', affiliate: 'Tech Review Deals', scheduled: 'Heute 10:00', by: 'Lisa M.', byTime: '26. Mai, 08:15', status: 'Review', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Dringend', title: 'Smart Metering einfach erklärt', platform: 'Instagram', product: 'Smart Meter Gen3', affiliate: 'Energie & Smart Living', scheduled: 'Heute 12:00', by: 'Tom S.', byTime: '26. Mai, 07:45', status: 'Review', image: 'https://images.unsplash.com/photo-1509391366360-2e959784a276?w=60&h=60&fit=crop' },
  { priority: 'Hoch', title: 'Outdoor & Energy-Saving Content für Sommer', platform: 'LinkedIn', product: 'Outdoor Sensor Gen2', affiliate: 'SmartHome Tech', scheduled: 'Morgen 09:00', by: 'Anna K.', byTime: '26. Mai, 07:36', status: 'Review', image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=60&h=60&fit=crop' },
  { priority: 'Hoch', title: 'Airfryer Trends 2025 Top Picks', platform: 'TikTok', product: 'Airfryer Pro', affiliate: 'Küchen Inspiration', scheduled: '27. Mai 10:00', by: 'Mark D.', byTime: '26. Mai, 18:20', status: 'Review', image: 'https://images.unsplash.com/photo-1556909114-f6e7ad7d3136?w=60&h=60&fit=crop' },
  { priority: 'Mittel', title: 'LED Strips richtig integrieren', platform: 'Instagram', product: 'LED Strip RGBW', affiliate: 'Home & Style Creators', scheduled: '27. Mai 14:30', by: 'Sarah L.', byTime: '25. Mai, 17:50', status: 'Review', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Mittel', title: 'Sicherheit beginnt an der Tür', platform: 'LinkedIn', product: 'Door/Window 2', affiliate: 'Security First', scheduled: '28. Mai 09:00', by: 'Jonas P.', byTime: '25. Mai, 16:10', status: 'Review', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Niedrig', title: 'Automation Szenen richtig nutzen', platform: 'TikTok', product: 'Motion Sensor Gen2', affiliate: 'SmartHome Automation', scheduled: '28. Mai 16:00', by: 'Lisa M.', byTime: '25. Mai, 15:05', status: 'Review', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Niedrig', title: 'Shelly Plus Plug S im Alltag', platform: 'Instagram', product: 'Shelly Plus Plug S', affiliate: 'Budget Smart Home', scheduled: '29. Mai 10:00', by: 'Tom S.', byTime: '25. Mai, 14:30', status: 'Review', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Niedrig', title: 'Gesponserter Post – neues Bundle', platform: 'LinkedIn', product: 'Starter Bundle Pro', affiliate: 'Deals Germany', scheduled: '29. Mai 12:00', by: 'Mark D.', byTime: '25. Mai, 13:45', status: 'Blockiert', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
  { priority: 'Niedrig', title: 'Smart Meter Features im Detail', platform: 'TikTok', product: 'Smart Meter Gen3', affiliate: 'Tech & Energy Experts', scheduled: '29. Mai 14:00', by: 'Anna K.', byTime: '25. Mai, 13:15', status: 'Blockiert', image: 'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop' },
];

const PRIORITY_COLORS: Record<string, { bg: string; text: string }> = {
  Dringend: { bg: 'oklch(0.62 0.22 25 / 0.15)', text: '#ef4444' },
  Hoch: { bg: 'oklch(0.75 0.15 75 / 0.15)', text: '#f59e0b' },
  Mittel: { bg: 'oklch(0.82 0.18 210 / 0.1)', text: '#60a5fa' },
  Niedrig: { bg: 'oklch(0.5 0.05 240 / 0.1)', text: '#64748b' },
};

const STATUS_COLORS: Record<string, { bg: string; text: string }> = {
  Review: { bg: 'oklch(0.75 0.15 75 / 0.15)', text: '#f59e0b' },
  Blockiert: { bg: 'oklch(0.62 0.22 25 / 0.15)', text: '#ef4444' },
  Freigegeben: { bg: 'oklch(0.65 0.15 165 / 0.15)', text: '#10b981' },
};

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

const AUDIT_LOG = [
  { user: 'Lisa M.', action: 'hat zur Prüfung eingereicht', time: '26. Mai 2025, 08:15', color: '#60a5fa' },
  { user: 'Auto-Check', action: 'Textlänge OK, Hashtags OK, Link OK, Bildqualität OK', time: '26. Mai 2025, 07:36', color: '#10b981' },
  { user: 'Tom S.', action: 'hat auf Review gesetzt', time: '26. Mai 2025, 08:05', color: '#a78bfa' },
  { user: 'Anna K.', action: 'Kommentar: "Klingt gut! Vielleicht noch einen CTA ergänzen"', time: '26. Mai 2025, 08:12', color: '#f59e0b' },
];

export default function Approvals() {
  const [activeFilter, setActiveFilter] = useState('Alle');
  const [selectedItem, setSelectedItem] = useState(QUEUE[2]);
  const [queue, setQueue] = useState(QUEUE);

  const handleApprove = (title: string) => {
    setQueue(prev => prev.map(q => q.title === title ? { ...q, status: 'Freigegeben' } : q));
    toast.success(`"${title}" freigegeben`);
  };

  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)' }}>Freigaben</h1>
          <p className="text-sm mt-0.5" style={{ color: 'var(--muted-foreground)' }}>Prüfe, priorisiere und genehmige Inhalte vor der Veröffentlichung.</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(--foreground)' }}>26. Mai 2025</span>
          <select className="text-xs px-2 py-1.5 rounded" style={{ background: 'var(--atlas-surface)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
            <option>Alle Plattformen</option>
          </select>
          <button className="atlas-btn-ghost p-1.5"><Filter size={13} /></button>
        </div>
      </div>

      {/* KPI Bar */}
      <div className="grid grid-cols-4 gap-3">
        {[
          { label: 'Offene Freigaben', value: '48', trend: '↑ 12% vs. gestern', color: '#a78bfa' },
          { label: 'Dringend', value: '7', trend: '↑ 75% vs. gestern', color: '#ef4444' },
          { label: 'Durchschnittliche Prüfzeit', value: '3h 24m', trend: '↑ 18% vs. gestern', color: '#10b981' },
          { label: 'Heute freigegeben', value: '26', trend: '↑ 24% vs. gestern', 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="text-xl font-bold" style={{ fontFamily: 'var(--font-mono)', color: kpi.color }}>{kpi.value}</div>
            <div className="text-xs mt-1" style={{ color: 'var(--muted-foreground)' }}>{kpi.trend}</div>
          </div>
        ))}
      </div>

      {/* Filter Tabs */}
      <div className="flex items-center gap-1.5 flex-wrap">
        {FILTER_TABS.map(tab => (
          <button
            key={tab.label}
            onClick={() => setActiveFilter(tab.label)}
            className="flex items-center gap-1 px-3 py-1.5 rounded text-xs font-medium transition-all"
            style={{
              background: activeFilter === tab.label ? 'oklch(0.82 0.18 210 / 0.12)' : 'var(--atlas-surface)',
              color: activeFilter === tab.label ? 'var(--atlas-cyan)' : 'var(--muted-foreground)',
              border: `1px solid ${activeFilter === tab.label ? 'oklch(0.82 0.18 210 / 0.3)' : 'var(--atlas-border)'}`,
            }}
          >
            {tab.label}
            {tab.count !== undefined && (
              <span
                className="rounded px-1"
                style={{ background: tab.color ? `${tab.color}20` : 'var(--atlas-navy)', color: tab.color || 'var(--muted-foreground)', fontSize: '0.6rem' }}
              >
                {tab.count}
              </span>
            )}
          </button>
        ))}
      </div>

      <div className="flex gap-4">
        {/* Queue Table */}
        <div className="flex-1 min-w-0">
          <div className="atlas-card overflow-hidden">
            <div className="p-3" style={{ borderBottom: '1px solid var(--atlas-border)' }}>
              <span className="text-sm font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
                Freigaben-Queue (48)
              </span>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--atlas-border)' }}>
                  {['Priorität', 'Vorschau', 'Titel', 'Plattform', 'Produkt', 'Affiliate', 'Geplant für', 'Erstellt von', 'Status', 'Aktionen'].map(h => (
                    <th key={h} style={{ padding: '8px 10px', textAlign: 'left' }}>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{h}</span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {queue.map((item, i) => (
                  <tr
                    key={i}
                    className="cursor-pointer"
                    onClick={() => setSelectedItem(item)}
                    style={{
                      borderBottom: i < queue.length - 1 ? '1px solid var(--atlas-border)' : 'none',
                      background: selectedItem.title === item.title ? 'oklch(0.82 0.18 210 / 0.05)' : 'transparent',
                    }}
                  >
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: PRIORITY_COLORS[item.priority]?.bg, color: PRIORITY_COLORS[item.priority]?.text, fontSize: '0.6rem', border: `1px solid ${PRIORITY_COLORS[item.priority]?.text}30` }}>
                        {item.priority}
                      </span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <img src={item.image} alt={item.title} className="rounded" style={{ width: '32px', height: '32px', objectFit: 'cover' }} onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                    </td>
                    <td style={{ padding: '8px 10px', maxWidth: '160px' }}>
                      <div className="text-xs truncate" style={{ color: 'var(--foreground)' }}>{item.title}</div>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs">{PLATFORM_ICONS[item.platform]} {item.platform}</span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6875rem' }}>{item.product}</span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6875rem' }}>{item.affiliate}</span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-mono)', fontSize: '0.6rem' }}>{item.scheduled}</span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <div>
                        <div className="text-xs" style={{ color: 'var(--foreground)', fontSize: '0.6875rem' }}>{item.by}</div>
                        <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>{item.byTime}</div>
                      </div>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <span className="text-xs px-1.5 py-0.5 rounded" style={{ background: STATUS_COLORS[item.status]?.bg, color: STATUS_COLORS[item.status]?.text, fontSize: '0.6rem' }}>
                        {item.status}
                      </span>
                    </td>
                    <td style={{ padding: '8px 10px' }}>
                      <button className="p-1" 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–10 von 48 Freigaben</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>10 pro Seite</option>
              </select>
            </div>
          </div>
        </div>

        {/* Right: Preview + Audit */}
        <div className="w-64 flex-shrink-0 space-y-3">
          {/* Schnellvorschau */}
          <div className="atlas-card overflow-hidden">
            <div className="p-3" style={{ borderBottom: '1px solid var(--atlas-border)' }}>
              <span className="text-xs font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Schnellvorschau</span>
            </div>
            <div className="p-3">
              <div className="flex items-center gap-2 mb-2">
                <span style={{ fontSize: '14px' }}>{PLATFORM_ICONS[selectedItem.platform]}</span>
                <span className="text-xs font-medium" style={{ color: 'var(--foreground)' }}>{selectedItem.platform}</span>
                <span className="text-xs ml-auto" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Beitrag</span>
              </div>
              <img
                src={selectedItem.image}
                alt={selectedItem.title}
                className="w-full rounded mb-2"
                style={{ aspectRatio: '4/3', objectFit: 'cover' }}
                onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
              />
              <div className="text-xs font-medium mb-1" style={{ color: 'var(--foreground)' }}>{selectedItem.title}</div>
              <div className="text-xs mb-2" style={{ color: 'var(--muted-foreground)' }}>
                Geplant für: {selectedItem.scheduled}<br />
                Affiliate: {selectedItem.affiliate}
              </div>
              <div className="flex flex-col gap-1.5">
                <button
                  className="w-full text-xs py-1.5 rounded font-semibold"
                  style={{ background: 'var(--atlas-green)', color: 'white' }}
                  onClick={() => handleApprove(selectedItem.title)}
                >
                  ✓ Freigeben
                </button>
                <button className="w-full text-xs py-1.5 rounded" style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
                  ↩ Zurück an Entwurf
                </button>
                <div className="flex gap-1.5">
                  <button className="flex-1 text-xs py-1.5 rounded flex items-center justify-center gap-1" style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
                    <MessageSquare size={11} /> Kommentieren
                  </button>
                  <button className="flex-1 text-xs py-1.5 rounded flex items-center justify-center gap-1" style={{ background: 'var(--atlas-navy)', border: '1px solid var(--atlas-border)', color: 'var(--foreground)' }}>
                    <Edit size={11} /> Bearbeiten
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Audit Log */}
          <div className="atlas-card p-3">
            <div className="text-xs font-semibold mb-2" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>Audit-Verlauf</div>
            <div className="space-y-2">
              {AUDIT_LOG.map((entry, i) => (
                <div key={i} className="flex gap-2">
                  <div className="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 text-xs font-bold" style={{ background: `${entry.color}20`, color: entry.color }}>
                    {entry.user[0]}
                  </div>
                  <div>
                    <div className="text-xs" style={{ color: 'var(--foreground)' }}>
                      <strong>{entry.user}</strong> {entry.action}
                    </div>
                    <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>{entry.time}</div>
                  </div>
                </div>
              ))}
            </div>
            <button className="text-xs mt-2" style={{ color: 'var(--atlas-cyan)' }}>Alle Kommentare anzeigen →</button>
          </div>
        </div>
      </div>
    </div>
  );
}
