/**
 * Draft Studio — Erstelle, optimiere und bereite Inhalte für alle Kanäle vor
 * Referenz: docs/design-references/screen-draft-studio.png
 */

import { useState } from 'react';
import { useLocation } from 'wouter';
import { ArrowLeft, Save, Send, ExternalLink, MoreHorizontal, Plus, ChevronDown } from 'lucide-react';
import { toast } from 'sonner';

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

const MOCK_PRODUCTS = [
  { id: '1', name: 'Shelly Plug S Gen3', price: '€24,95', category: 'Smart Home / Energie', available: true },
  { id: '2', name: 'Shelly Plus 1', price: '€19,95', category: 'Smart Home', available: true },
  { id: '3', name: 'Airfryer Pro X', price: '€129,00', category: 'Kitchen', available: true },
];

const MOCK_DRAFTS = [
  { id: '1', title: 'Shelly Plug S Gen3 – smarter Energie sparen', status: 'Entwurf', platform: 'TikTok', updated: 'Heute, 10:42' },
  { id: '2', title: 'Airfryer Trends 2025 – Top Picks', status: 'Review', platform: 'Instagram', updated: 'Gestern, 15:20' },
  { id: '3', title: 'KI-News Update – Was du wissen musst', status: 'Entwurf', platform: 'LinkedIn', updated: 'Gestern, 09:15' },
  { id: '4', title: 'Balkonkraftwerk Starter Guide', status: 'Freigegeben', platform: 'YouTube Shorts', updated: '25. Mai, 14:00' },
];

export default function Drafts() {
  const [, navigate] = useLocation();
  const [selectedDraft, setSelectedDraft] = useState<string | null>('1');
  const [activePlatform, setActivePlatform] = useState('TikTok');
  const [title, setTitle] = useState('Shelly Plug S Gen3 – smarter Energie sparen');
  const [hook, setHook] = useState('Stromkosten senken war noch nie so einfach! 💡');
  const [caption, setCaption] = useState('Der Shelly Plug S Gen3 macht dein Zuhause smarter und spart Energie – automatisch und zuverlässig.\n\nKlein, smart, effizient: Jetzt entdecken!');
  const [cta, setCta] = useState('Jetzt entdecken & sparen →');
  const [hashtags, setHashtags] = useState('#Shelly #ShellyPlugS #SmartHome #EnergieSparen #Automation #IoT');
  const [selectedProduct, setSelectedProduct] = useState(MOCK_PRODUCTS[0]);

  const handleSave = () => toast.success('Entwurf gespeichert');
  const handleSendReview = () => toast.success('Zur Freigabe gesendet');
  const handleOpenPostiz = () => window.open('https://postiz.atlas-os.ai', '_blank');

  const captionLength = caption.length;
  const maxCaption = 1500;

  const affiliateUrl = `https://shelly.shop/plug-s-gen3?utm_source=atlassocial&utm_medium=social&utm_campaign=shelly-plug-s-gen3-launch`;

  if (!selectedDraft) {
    // Draft list view
    return (
      <div className="p-5 animate-fade-in-up">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h1 className="text-xl font-bold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
              Draft Studio
            </h1>
            <p className="text-sm mt-0.5" style={{ color: 'var(--muted-foreground)' }}>
              Erstelle, optimiere und bereite deine Inhalte für alle Kanäle vor.
            </p>
          </div>
          <button className="atlas-btn-primary" onClick={() => setSelectedDraft('new')}>
            <Plus size={14} /> Neuer Entwurf
          </button>
        </div>
        <div className="space-y-2">
          {MOCK_DRAFTS.map(draft => (
            <div
              key={draft.id}
              className="atlas-card atlas-card-hover p-3 cursor-pointer flex items-center gap-3"
              onClick={() => setSelectedDraft(draft.id)}
            >
              <div className="flex-1">
                <div className="text-sm font-medium" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-display)' }}>
                  {draft.title}
                </div>
                <div className="flex items-center gap-2 mt-1">
                  <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{PLATFORM_ICONS[draft.platform]} {draft.platform}</span>
                  <span style={{ color: 'var(--atlas-border)' }}>·</span>
                  <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Letzte Änderung: {draft.updated}</span>
                </div>
              </div>
              <span
                className="text-xs px-2 py-0.5 rounded"
                style={{
                  background: draft.status === 'Freigegeben' ? 'oklch(0.65 0.15 165 / 0.15)' : draft.status === 'Review' ? 'oklch(0.75 0.15 75 / 0.15)' : 'oklch(0.82 0.18 210 / 0.1)',
                  color: draft.status === 'Freigegeben' ? 'var(--atlas-green)' : draft.status === 'Review' ? 'var(--atlas-amber)' : 'var(--atlas-cyan)',
                  border: `1px solid ${draft.status === 'Freigegeben' ? 'oklch(0.65 0.15 165 / 0.25)' : draft.status === 'Review' ? 'oklch(0.75 0.15 75 / 0.25)' : 'oklch(0.82 0.18 210 / 0.2)'}`,
                }}
              >
                {draft.status}
              </span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-full animate-fade-in-up">
      {/* Left: Editor */}
      <div className="flex-1 overflow-y-auto atlas-scrollbar p-5 space-y-4">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <button className="atlas-btn-ghost p-1.5" onClick={() => setSelectedDraft(null)}>
              <ArrowLeft size={14} />
            </button>
            <div>
              <div className="flex items-center gap-2">
                <span className="atlas-badge-cyan" style={{ fontSize: '0.6rem' }}>Entwurf</span>
                <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Letzte Änderung: Heute, 10:42</span>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button className="atlas-btn-ghost text-xs gap-1.5" onClick={handleSave}>
              <Save size={13} /> Als Draft speichern
            </button>
            <button className="atlas-btn-ghost text-xs gap-1.5" onClick={handleSendReview}>
              <Send size={13} /> Zur Freigabe senden
            </button>
            <button className="atlas-btn-primary text-xs gap-1.5" onClick={handleOpenPostiz}>
              <ExternalLink size={13} /> In Postiz öffnen
            </button>
            <button className="atlas-btn-ghost p-1.5">
              <MoreHorizontal size={14} />
            </button>
          </div>
        </div>

        {/* Title */}
        <div>
          <label className="text-xs mb-1 block" style={{ color: 'var(--muted-foreground)' }}>Titel des Entwurfs</label>
          <div className="relative">
            <input
              className="atlas-input pr-16"
              value={title}
              onChange={e => setTitle(e.target.value)}
              maxLength={100}
            />
            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>
              {title.length}/100
            </span>
          </div>
        </div>

        {/* Product */}
        <div>
          <label className="text-xs mb-1 block" style={{ color: 'var(--muted-foreground)' }}>Produkt</label>
          <div className="atlas-card p-3 flex items-center gap-3">
            <img
              src="https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=60&h=60&fit=crop"
              alt={selectedProduct.name}
              className="rounded"
              style={{ width: '48px', height: '48px', objectFit: 'cover' }}
            />
            <div className="flex-1">
              <div className="text-sm font-medium" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-display)' }}>
                {selectedProduct.name}
              </div>
              <div className="text-xs" style={{ color: 'var(--muted-foreground)' }}>
                {selectedProduct.price} · {selectedProduct.category}
              </div>
            </div>
            <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>
            <button className="atlas-btn-ghost text-xs">Produkt ändern</button>
          </div>
        </div>

        {/* Affiliate Link */}
        <div>
          <div className="flex items-center justify-between mb-1">
            <label className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Affiliate-Link & UTM</label>
            <div className="flex items-center gap-1.5">
              <span className="atlas-badge-green" style={{ fontSize: '0.6rem' }}>Affiliate-Link aktiv</span>
              <div className="w-8 h-4 rounded-full" style={{ background: 'var(--atlas-green)', position: 'relative' }}>
                <div className="absolute right-0.5 top-0.5 w-3 h-3 rounded-full bg-white" />
              </div>
            </div>
          </div>
          <div className="atlas-card p-3 space-y-2">
            <div className="grid grid-cols-3 gap-2">
              <div>
                <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Campaign</div>
                <input className="atlas-input text-xs" value="shelly-plug-s-gen3-launch" readOnly />
              </div>
              <div>
                <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Source</div>
                <input className="atlas-input text-xs" value="atlassocial" readOnly />
              </div>
              <div>
                <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Medium</div>
                <input className="atlas-input text-xs" value="social" readOnly />
              </div>
            </div>
            <div className="flex items-center gap-2">
              <input className="atlas-input text-xs flex-1" value={affiliateUrl} readOnly />
              <button className="atlas-btn-ghost text-xs px-2 py-1.5" onClick={() => { navigator.clipboard.writeText(affiliateUrl); toast.success('Link kopiert'); }}>
                Kopieren
              </button>
            </div>
          </div>
        </div>

        {/* Content Blocks */}
        <div className="space-y-3">
          <div className="text-xs font-semibold" style={{ color: 'var(--foreground)', fontFamily: 'var(--font-display)' }}>Content Blöcke</div>

          <div>
            <div className="flex items-center gap-1.5 mb-1">
              <span style={{ fontSize: '12px' }}>🪝</span>
              <label className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Hook</label>
            </div>
            <input className="atlas-input" value={hook} onChange={e => setHook(e.target.value)} />
          </div>

          <div>
            <div className="flex items-center gap-1.5 mb-1">
              <span style={{ fontSize: '12px' }}>💬</span>
              <label className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Caption</label>
              <span className="ml-auto text-xs" style={{ color: captionLength > maxCaption * 0.9 ? 'var(--atlas-amber)' : 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>
                {captionLength}/{maxCaption}
              </span>
            </div>
            <textarea
              className="atlas-input resize-none"
              rows={4}
              value={caption}
              onChange={e => setCaption(e.target.value)}
            />
          </div>

          <div>
            <div className="flex items-center gap-1.5 mb-1">
              <span style={{ fontSize: '12px' }}>📣</span>
              <label className="text-xs" style={{ color: 'var(--muted-foreground)' }}>CTA</label>
            </div>
            <input className="atlas-input" value={cta} onChange={e => setCta(e.target.value)} />
          </div>

          <div>
            <div className="flex items-center gap-1.5 mb-1">
              <span style={{ fontSize: '12px' }}>#️⃣</span>
              <label className="text-xs" style={{ color: 'var(--muted-foreground)' }}>Hashtags</label>
              <span className="ml-auto text-xs" style={{ color: 'var(--muted-foreground)', fontFamily: 'var(--font-mono)' }}>
                {hashtags.split('#').filter(Boolean).length}/30
              </span>
            </div>
            <input className="atlas-input" value={hashtags} onChange={e => setHashtags(e.target.value)} />
          </div>
        </div>

        {/* Freigabe Status */}
        <div className="atlas-card p-3">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Status</div>
              <span className="atlas-badge-cyan">Entwurf</span>
            </div>
            <div>
              <div className="text-xs mb-1" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Erstellt von</div>
              <span className="text-xs" style={{ color: 'var(--foreground)' }}>Atlas Team</span>
            </div>
          </div>
        </div>
      </div>

      {/* Right: Preview */}
      <div className="w-96 flex-shrink-0 border-l overflow-y-auto atlas-scrollbar" style={{ borderColor: 'var(--atlas-border)', background: 'var(--atlas-navy)' }}>
        <div className="p-4">
          <div className="text-sm font-semibold mb-3" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>
            Vorschau
          </div>

          {/* Platform Tabs */}
          <div className="flex gap-1 mb-4 overflow-x-auto">
            {PLATFORMS.map(p => (
              <button
                key={p}
                onClick={() => setActivePlatform(p)}
                className="flex items-center gap-1 px-2 py-1.5 rounded text-xs whitespace-nowrap transition-all"
                style={{
                  background: activePlatform === p ? 'oklch(0.82 0.18 210 / 0.12)' : 'transparent',
                  color: activePlatform === p ? 'var(--atlas-cyan)' : 'var(--muted-foreground)',
                  border: `1px solid ${activePlatform === p ? 'oklch(0.82 0.18 210 / 0.3)' : 'var(--atlas-border)'}`,
                }}
              >
                {PLATFORM_ICONS[p]} {p}
              </button>
            ))}
          </div>

          {/* Preview Card */}
          <div className="atlas-card overflow-hidden">
            {activePlatform === 'TikTok' && (
              <div className="relative" style={{ background: '#000', borderRadius: '8px', overflow: 'hidden', aspectRatio: '9/16', maxHeight: '320px' }}>
                <img
                  src="https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=700&fit=crop"
                  alt="Preview"
                  style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.7 }}
                />
                <div className="absolute inset-0 flex flex-col justify-end p-3" style={{ background: 'linear-gradient(to top, rgba(0,0,0,0.8) 0%, transparent 60%)' }}>
                  <div className="text-xs font-bold text-white mb-1">@atlassocial</div>
                  <div className="text-xs text-white mb-1">{hook}</div>
                  <div className="text-xs text-white opacity-80 line-clamp-2">{caption.split('\n')[0]}</div>
                  <div className="text-xs mt-1" style={{ color: 'var(--atlas-cyan)' }}>{cta}</div>
                </div>
                <div className="absolute right-2 bottom-16 flex flex-col items-center gap-3">
                  <div className="text-white text-center">
                    <div style={{ fontSize: '18px' }}>❤️</div>
                    <div className="text-xs">128</div>
                  </div>
                  <div className="text-white text-center">
                    <div style={{ fontSize: '18px' }}>💬</div>
                    <div className="text-xs">12</div>
                  </div>
                  <div className="text-white text-center">
                    <div style={{ fontSize: '18px' }}>🔖</div>
                    <div className="text-xs">16</div>
                  </div>
                </div>
              </div>
            )}
            {activePlatform === 'Instagram' && (
              <div>
                <div className="flex items-center gap-2 p-3" style={{ borderBottom: '1px solid var(--atlas-border)' }}>
                  <div className="w-7 h-7 rounded-full" style={{ background: 'var(--atlas-cyan)' }} />
                  <div>
                    <div className="text-xs font-medium" style={{ color: 'var(--foreground)' }}>atlassocial</div>
                    <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>Gesponsert</div>
                  </div>
                </div>
                <img
                  src="https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=400&h=400&fit=crop"
                  alt="Preview"
                  style={{ width: '100%', aspectRatio: '1/1', objectFit: 'cover' }}
                />
                <div className="p-3">
                  <div className="text-xs font-medium mb-1" style={{ color: 'var(--atlas-cyan)' }}>{cta}</div>
                  <div className="text-xs" style={{ color: 'var(--foreground)' }}>
                    <strong>atlassocial</strong> {caption.split('\n')[0]}
                  </div>
                  <div className="text-xs mt-1" style={{ color: 'var(--atlas-cyan)' }}>
                    {hashtags.split(' ').slice(0, 3).join(' ')}
                  </div>
                </div>
              </div>
            )}
            {(activePlatform === 'LinkedIn' || activePlatform === 'X (Twitter)') && (
              <div className="p-3">
                <div className="flex items-center gap-2 mb-2">
                  <div className="w-8 h-8 rounded-full" style={{ background: 'var(--atlas-cyan)' }} />
                  <div>
                    <div className="text-xs font-medium" style={{ color: 'var(--foreground)' }}>ATLAS Social</div>
                    <div className="text-xs" style={{ color: 'var(--muted-foreground)', fontSize: '0.6rem' }}>@atlassocial · Gesponsert</div>
                  </div>
                </div>
                <div className="text-xs mb-2" style={{ color: 'var(--foreground)', lineHeight: '1.6' }}>
                  {hook}<br /><br />{caption.split('\n')[0]}
                </div>
                <div className="text-xs mb-2" style={{ color: 'var(--atlas-cyan)' }}>{cta}</div>
                <div className="text-xs" style={{ color: 'var(--atlas-cyan)', opacity: 0.7 }}>
                  {hashtags.split(' ').slice(0, 4).join(' ')}
                </div>
              </div>
            )}
          </div>

          {/* AI Insights */}
          <div className="atlas-card p-3 mt-3">
            <div className="flex items-center gap-1.5 mb-2">
              <span style={{ fontSize: '12px' }}>🤖</span>
              <span className="text-xs font-semibold" style={{ fontFamily: 'var(--font-display)', color: 'var(--foreground)' }}>AI-Insights</span>
              <span className="atlas-badge-cyan" style={{ fontSize: '0.55rem' }}>BETA</span>
            </div>
            <div className="space-y-1.5">
              {[
                { icon: '✅', text: 'Starker Hook – hohe Aufmerksamkeit erwartet' },
                { icon: '✅', text: 'CTA ist klar und handlungsorientiert' },
                { icon: '✅', text: 'Hashtag-Mix ist ausgewogen' },
                { icon: '✅', text: 'Bildmaterial unterstützt die Botschaft sehr gut' },
              ].map((insight, i) => (
                <div key={i} className="flex items-center gap-2">
                  <span style={{ fontSize: '11px' }}>{insight.icon}</span>
                  <span className="text-xs" style={{ color: 'var(--muted-foreground)' }}>{insight.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
