'use client';

import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';

// ==========================================
// SVG Icons
// ==========================================
function IconBold({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"/></svg>;
}
function IconItalic({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="19" x2="10" y1="4" y2="4"/><line x1="14" x2="5" y1="20" y2="20"/><line x1="15" x2="9" y1="4" y2="20"/></svg>;
}
function IconLink({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>;
}
function IconHeading({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 12h12"/><path d="M6 20V4"/><path d="M18 20V4"/></svg>;
}
function IconSend({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="22" x2="11" y1="2" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>;
}
function IconEye({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></svg>;
}
function IconMail({ size = 18, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>;
}
function IconClock({ size = 12, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>;
}
function IconUsers({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
}

// ==========================================
// Types
// ==========================================

interface SentNewsletter {
  id: string;
  subject: string;
  sentAt: string;
  recipientCount: number;
  openRate: number;
}

// ==========================================
// Safe Preview Renderer
// ==========================================
function PreviewContent({ content }: { content: string }) {
  if (!content) {
    return <p className="italic" style={{ color: 'var(--text-muted)' }}>Le contenu apparaîtra ici...</p>;
  }

  // Parse markdown-like syntax into React elements
  const lines = content.split('\n');
  return (
    <div className="space-y-2">
      {lines.map((line, i) => {
        // Headings
        if (line.startsWith('### ')) {
          return <h3 key={i} className="font-impact text-base mt-3 mb-1" style={{ color: 'var(--color-gold)' }}>{processInline(line.slice(4))}</h3>;
        }
        if (line.startsWith('## ')) {
          return <h2 key={i} className="font-impact text-lg mt-3 mb-1" style={{ color: 'var(--color-gold)' }}>{processInline(line.slice(3))}</h2>;
        }
        if (line.startsWith('# ')) {
          return <h1 key={i} className="font-gothic text-xl mt-3 mb-1 text-gold-gradient">{processInline(line.slice(2))}</h1>;
        }
        // Empty line
        if (line.trim() === '') {
          return <br key={i} />;
        }
        // Normal paragraph
        return <p key={i} className="text-sm leading-relaxed" style={{ color: 'var(--text-secondary)' }}>{processInline(line)}</p>;
      })}
    </div>
  );
}

function processInline(text: string): React.ReactNode {
  // Simple bold/italic processing — returns plain text with styled spans
  const parts: React.ReactNode[] = [];
  let remaining = text;
  let key = 0;

  while (remaining.length > 0) {
    // Bold
    const boldMatch = remaining.match(/\*\*(.*?)\*\*/);
    // Italic
    const italicMatch = remaining.match(/\*(.*?)\*/);
    // Link
    const linkMatch = remaining.match(/\[([^\]]+)\]\(([^)]+)\)/);

    const matches = [
      boldMatch ? { type: 'bold', index: boldMatch.index!, match: boldMatch } : null,
      italicMatch && (!boldMatch || (italicMatch.index! < boldMatch.index!)) ? { type: 'italic', index: italicMatch.index!, match: italicMatch } : null,
      linkMatch ? { type: 'link', index: linkMatch.index!, match: linkMatch } : null,
    ].filter(Boolean).sort((a, b) => a!.index - b!.index);

    if (matches.length === 0) {
      parts.push(remaining);
      break;
    }

    const first = matches[0]!;
    if (first.index > 0) {
      parts.push(remaining.slice(0, first.index));
    }

    if (first.type === 'bold') {
      parts.push(<strong key={key++} style={{ color: 'var(--text-primary)' }}>{first.match[1]}</strong>);
      remaining = remaining.slice(first.index + first.match[0].length);
    } else if (first.type === 'italic') {
      parts.push(<em key={key++}>{first.match[1]}</em>);
      remaining = remaining.slice(first.index + first.match[0].length);
    } else if (first.type === 'link') {
      parts.push(<span key={key++} style={{ color: 'var(--color-gold)', textDecoration: 'underline' }}>{first.match[1]}</span>);
      remaining = remaining.slice(first.index + first.match[0].length);
    } else {
      parts.push(remaining);
      break;
    }
  }

  return <>{parts}</>;
}

// ==========================================
// Component
// ==========================================
export default function AdminNewsletter() {
  const [subject, setSubject] = useState('');
  const [content, setContent] = useState('');
  const [showPreview, setShowPreview] = useState(false);
  const [showSendConfirm, setShowSendConfirm] = useState(false);
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  // API data states
  const [history, setHistory] = useState<SentNewsletter[]>([]);
  const [subscriberCount, setSubscriberCount] = useState<number | null>(null);
  const [loadingHistory, setLoadingHistory] = useState(true);
  const [loadingCount, setLoadingCount] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [sendError, setSendError] = useState<string | null>(null);

  const fetchHistory = useCallback(async () => {
    try {
      setLoadingHistory(true);
      const data = await api.admin.newsletter.getHistory();
      setHistory(data as SentNewsletter[]);
    } catch (err) {
      setError('Impossible de charger l\u2019historique des newsletters.');
      console.error(err);
    } finally {
      setLoadingHistory(false);
    }
  }, []);

  const fetchSubscriberCount = useCallback(async () => {
    try {
      setLoadingCount(true);
      const data = await api.admin.newsletter.getSubscriberCount();
      setSubscriberCount(data.count);
    } catch (err) {
      setError('Impossible de charger le nombre d\u2019abonn\u00e9s.');
      console.error(err);
    } finally {
      setLoadingCount(false);
    }
  }, []);

  useEffect(() => {
    fetchHistory();
    fetchSubscriberCount();
  }, [fetchHistory, fetchSubscriberCount]);

  const insertFormatting = (prefix: string, suffix: string) => {
    const textarea = document.getElementById('newsletter-content') as HTMLTextAreaElement;
    if (!textarea) return;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = content.substring(start, end);
    const newContent = content.substring(0, start) + prefix + selected + suffix + content.substring(end);
    setContent(newContent);
  };

  const handleSend = async () => {
    setSending(true);
    setSendError(null);
    try {
      await api.admin.newsletter.send({ subject, content });
      setSending(false);
      setSent(true);
      setShowSendConfirm(false);
      setSubject('');
      setContent('');
      // Rafraîchir l'historique après envoi réussi
      fetchHistory();
      fetchSubscriberCount();
      setTimeout(() => setSent(false), 3000);
    } catch (err) {
      setSending(false);
      const message = err instanceof Error ? err.message : 'Une erreur est survenue lors de l\u2019envoi.';
      setSendError(message);
    }
  };

  const displayCount = subscriberCount !== null ? subscriberCount.toLocaleString() : '\u2014';

  return (
    <div className="space-y-6">
      {/* Subscriber count banner */}
      <div
        className="flex items-center justify-between p-4 rounded-xl"
        style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
      >
        <div className="flex items-center gap-3">
          <div
            className="w-10 h-10 rounded-lg flex items-center justify-center"
            style={{ background: 'rgba(20,184,166,0.15)', color: '#14b8a6' }}
          >
            <IconUsers size={20} />
          </div>
          <div>
            <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>Abonnés Newsletter</p>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Destinataires de la prochaine newsletter</p>
          </div>
        </div>
        <div className="text-2xl font-bold font-mono" style={{ color: '#14b8a6' }}>
          {loadingCount ? (
            <span className="text-base" style={{ color: 'var(--text-muted)' }}>Chargement...</span>
          ) : (
            displayCount
          )}
        </div>
      </div>

      {/* Global error */}
      {error && (
        <div
          className="p-3 rounded-lg text-sm text-center font-bold"
          style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#ef4444' }}
        >
          {error}
        </div>
      )}

      {sent && (
        <div
          className="p-3 rounded-lg text-sm text-center font-bold"
          style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)', color: '#22c55e' }}
        >
          Newsletter envoyée avec succès !
        </div>
      )}

      {/* Editor Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        {/* Editor */}
        <div className="space-y-4">
          <div>
            <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
              Objet
            </label>
            <input
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Objet de la newsletter..."
              className="w-full p-2.5 rounded-lg text-sm"
              style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
            />
          </div>

          <div>
            <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
              Contenu
            </label>
            {/* Formatting Toolbar */}
            <div
              className="flex items-center gap-1 p-2 rounded-t-lg"
              style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--border-dark)', borderBottom: 'none' }}
            >
              <button
                onClick={() => insertFormatting('**', '**')}
                className="p-1.5 rounded hover:bg-white/5 transition-colors"
                title="Gras"
              >
                <IconBold color="var(--text-muted)" />
              </button>
              <button
                onClick={() => insertFormatting('*', '*')}
                className="p-1.5 rounded hover:bg-white/5 transition-colors"
                title="Italique"
              >
                <IconItalic color="var(--text-muted)" />
              </button>
              <button
                onClick={() => insertFormatting('[', '](url)')}
                className="p-1.5 rounded hover:bg-white/5 transition-colors"
                title="Lien"
              >
                <IconLink color="var(--text-muted)" />
              </button>
              <div className="w-px h-5 mx-1" style={{ background: 'var(--border-dark)' }} />
              <button
                onClick={() => insertFormatting('# ', '')}
                className="p-1.5 rounded hover:bg-white/5 transition-colors"
                title="Titre"
              >
                <IconHeading color="var(--text-muted)" />
              </button>
              <div className="flex-1" />
              <span className="text-[10px] font-mono" style={{ color: 'var(--text-muted)' }}>
                Markdown
              </span>
            </div>
            <textarea
              id="newsletter-content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="Rédigez votre newsletter... (supporte le Markdown basique : **gras**, *italique*, [lien](url), # titre)"
              rows={16}
              className="w-full p-3 rounded-b-lg text-sm resize-none font-mono"
              style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', borderTop: 'none', color: 'var(--text-primary)' }}
            />
          </div>

          {/* Action buttons */}
          <div className="flex items-center gap-3">
            <button
              onClick={() => setShowPreview(!showPreview)}
              className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm transition-colors"
              style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-secondary)' }}
            >
              <IconEye size={14} />
              {showPreview ? 'Masquer' : 'Aperçu'}
            </button>
            <button
              onClick={() => setShowSendConfirm(true)}
              disabled={!subject.trim() || !content.trim() || subscriberCount === null}
              className="flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105"
              style={{
                background: subject.trim() && content.trim() && subscriberCount !== null
                  ? 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))'
                  : 'rgba(255,255,255,0.05)',
                color: subject.trim() && content.trim() && subscriberCount !== null ? 'white' : 'var(--text-muted)',
                boxShadow: subject.trim() && content.trim() && subscriberCount !== null ? '0 0 20px rgba(196,30,30,0.3)' : 'none',
                cursor: subject.trim() && content.trim() && subscriberCount !== null ? 'pointer' : 'not-allowed',
              }}
            >
              <IconSend size={14} />
              Envoyer à {displayCount} abonnés
            </button>
          </div>
        </div>

        {/* Preview */}
        <div
          className="rounded-xl overflow-hidden"
          style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
        >
          <div
            className="px-4 py-3 flex items-center gap-2"
            style={{ background: 'rgba(255,255,255,0.03)', borderBottom: '1px solid var(--border-dark)' }}
          >
            <IconEye size={14} color="var(--color-gold)" />
            <span className="font-impact text-xs" style={{ color: 'var(--color-gold)' }}>Aperçu</span>
          </div>
          <div className="p-5">
            {/* Email header preview */}
            <div className="mb-4 pb-4" style={{ borderBottom: '1px solid var(--border-dark)' }}>
              <p className="text-[10px] mb-1" style={{ color: 'var(--text-muted)' }}>De: Ombres & Lumières &lt;noreply@mafiaz.world&gt;</p>
              <p className="text-[10px] mb-2" style={{ color: 'var(--text-muted)' }}>Objet: {subject || '(pas d\'objet)'}</p>
              <div className="section-divider-red" />
            </div>
            {/* Email body preview — rendered safely via React components */}
            <PreviewContent content={content} />
          </div>
        </div>
      </div>

      {/* Newsletter History */}
      <div>
        <h3 className="font-impact text-sm mb-3" style={{ color: 'var(--color-gold)' }}>
          Historique des envois
        </h3>
        <div
          className="rounded-xl overflow-hidden"
          style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}
        >
          <div
            className="grid grid-cols-[1fr_140px_100px_80px] gap-3 px-4 py-3 text-[10px] uppercase tracking-wider font-bold"
            style={{ background: 'rgba(255,255,255,0.03)', color: 'var(--text-muted)', borderBottom: '1px solid var(--border-dark)' }}
          >
            <span>Objet</span>
            <span>Date d&apos;envoi</span>
            <span>Destinataires</span>
            <span>Taux d&apos;ouverture</span>
          </div>
          {loadingHistory ? (
            <div className="px-4 py-8 text-center">
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Chargement de l&apos;historique...</p>
            </div>
          ) : history.length === 0 ? (
            <div className="px-4 py-8 text-center">
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Aucune newsletter envoyée pour le moment.</p>
            </div>
          ) : (
            history.map((nl) => (
              <div
                key={nl.id}
                className="grid grid-cols-[1fr_140px_100px_80px] gap-3 px-4 py-3 items-center transition-colors hover:bg-white/[0.02]"
                style={{ borderBottom: '1px solid var(--border-dark)' }}
              >
                <div className="flex items-center gap-2 min-w-0">
                  <IconMail size={14} color="var(--text-muted)" />
                  <p className="text-sm truncate" style={{ color: 'var(--text-primary)' }}>{nl.subject}</p>
                </div>
                <span className="text-xs flex items-center gap-1" style={{ color: 'var(--text-muted)' }}>
                  <IconClock />{nl.sentAt}
                </span>
                <span className="text-xs font-mono" style={{ color: 'var(--text-secondary)' }}>
                  {nl.recipientCount.toLocaleString()}
                </span>
                <span
                  className="text-xs font-bold"
                  style={{ color: nl.openRate >= 60 ? '#22c55e' : nl.openRate >= 40 ? '#f59e0b' : 'var(--color-red-light)' }}
                >
                  {nl.openRate}%
                </span>
              </div>
            ))
          )}
        </div>
      </div>

      {/* Send Confirmation Dialog */}
      {showSendConfirm && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          style={{ background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(4px)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowSendConfirm(false); }}
        >
          <div
            className="w-full max-w-sm rounded-xl overflow-hidden"
            style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border-dark)' }}
          >
            <div className="p-6 text-center">
              <div
                className="w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-4"
                style={{ background: 'rgba(196,30,30,0.1)', border: '1px solid rgba(196,30,30,0.3)' }}
              >
                <IconSend size={24} color="var(--color-red-light)" />
              </div>
              <h3 className="font-impact text-lg mb-2" style={{ color: 'var(--color-gold)' }}>
                Confirmer l&apos;envoi
              </h3>
              <p className="text-sm mb-1" style={{ color: 'var(--text-secondary)' }}>
                Vous êtes sur le point d&apos;envoyer cette newsletter à :
              </p>
              <p className="text-2xl font-bold font-mono mb-4" style={{ color: 'var(--color-red-light)' }}>
                {displayCount} abonnés
              </p>
              <p className="text-xs mb-4" style={{ color: 'var(--text-muted)' }}>
                Objet : &quot;{subject}&quot;
              </p>

              {/* Send error feedback */}
              {sendError && (
                <div
                  className="p-2.5 rounded-lg text-xs mb-4 text-left"
                  style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#ef4444' }}
                >
                  {sendError}
                </div>
              )}

              <div className="flex gap-3 justify-center">
                <button
                  onClick={() => { setShowSendConfirm(false); setSendError(null); }}
                  className="px-5 py-2 rounded-lg text-sm"
                  style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-secondary)' }}
                >
                  Annuler
                </button>
                <button
                  onClick={handleSend}
                  disabled={sending}
                  className="px-5 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105"
                  style={{
                    background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
                    color: 'white',
                    boxShadow: '0 0 15px rgba(196,30,30,0.3)',
                    opacity: sending ? 0.7 : 1,
                  }}
                >
                  {sending ? 'Envoi en cours...' : 'Confirmer l\'envoi'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
