'use client'

import { useState, useMemo, useEffect, useRef } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Eye, Send, Link2, Copy, Check, Mail, MailX, Layers } from 'lucide-react'
import {
  DEFAULT_MESSAGE, DEFAULT_CLOSING,
  DEFAULT_MESSAGE_EN, DEFAULT_CLOSING_EN,
  getDefaultGreeting,
} from '@/lib/email-templates'

type Lang = 'de' | 'en'

interface Version {
  id: string
  name: string
  status: string
  created_at: string
}

export default function NewInvestorPage() {
  const router = useRouter()
  const [email, setEmail] = useState('')
  const [name, setName] = useState('')
  const [company, setCompany] = useState('')
  const [lang, setLang] = useState<Lang>('de')
  const [sendEmail, setSendEmail] = useState(true)
  const [versionId, setVersionId] = useState('')
  const [versions, setVersions] = useState<Version[]>([])
  const [greeting, setGreeting] = useState('')
  const [message, setMessage] = useState(DEFAULT_MESSAGE)
  const [closing, setClosing] = useState(DEFAULT_CLOSING)
  const [messageEdited, setMessageEdited] = useState(false)
  const [closingEdited, setClosingEdited] = useState(false)
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [createdLink, setCreatedLink] = useState<{ short: string; full: string } | null>(null)
  const [copied, setCopied] = useState(false)
  const prevLang = useRef<Lang>('de')

  const ttl = process.env.NEXT_PUBLIC_MAGIC_LINK_TTL_HOURS || '72'
  const effectiveGreeting = greeting || getDefaultGreeting(name || null, lang)

  useEffect(() => {
    fetch('/api/admin/versions')
      .then(r => r.json())
      .then(d => setVersions((d.versions ?? []).filter((v: Version) => v.status === 'committed')))
      .catch(() => {})
  }, [])

  // When language changes, swap defaults unless the user has manually edited
  useEffect(() => {
    if (lang === prevLang.current) return
    prevLang.current = lang
    const defaults = lang === 'en'
      ? { message: DEFAULT_MESSAGE_EN, closing: DEFAULT_CLOSING_EN }
      : { message: DEFAULT_MESSAGE, closing: DEFAULT_CLOSING }
    if (!messageEdited) setMessage(defaults.message)
    if (!closingEdited) setClosing(defaults.closing)
  }, [lang, messageEdited, closingEdited])

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')
    setSubmitting(true)
    try {
      const res = await fetch('/api/admin/invite', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          name,
          company,
          lang,
          send_email: sendEmail,
          version_id: versionId || null,
          ...(sendEmail && {
            greeting: effectiveGreeting,
            message,
            closing,
          }),
        }),
      })
      if (res.ok) {
        const data = await res.json()
        if (!sendEmail) {
          setCreatedLink({ short: data.short_url, full: data.magic_link_url })
        } else {
          router.push('/pitch-admin/investors')
          router.refresh()
        }
      } else {
        const data = await res.json().catch(() => ({}))
        setError(data.error || 'Invite failed')
      }
    } catch {
      setError('Network error')
    } finally {
      setSubmitting(false)
    }
  }

  async function copyLink() {
    if (!createdLink) return
    await navigator.clipboard.writeText(createdLink.short)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const closingHtml = useMemo(() => closing.replace(/\n/g, '<br>'), [closing])

  // Success state: link was generated without email
  if (createdLink) {
    return (
      <div className="max-w-2xl">
        <Link
          href="/pitch-admin/investors"
          className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white/80 mb-6"
        >
          <ArrowLeft className="w-4 h-4" /> Back to investors
        </Link>

        <div className="bg-white/[0.04] border border-white/[0.08] rounded-2xl p-8 text-center space-y-6">
          <div className="w-14 h-14 rounded-full bg-green-500/15 border border-green-500/30 flex items-center justify-center mx-auto">
            <Link2 className="w-7 h-7 text-green-400" />
          </div>
          <div>
            <h2 className="text-xl font-semibold text-white mb-1">Investor created</h2>
            <p className="text-sm text-white/50">No email was sent. Copy the magic link below to use in your outreach.</p>
          </div>

          <div className="bg-black/40 border border-white/10 rounded-xl p-4 text-left space-y-3">
            <div>
              <p className="text-[10px] font-semibold text-white/40 uppercase tracking-wider mb-1">Short Link <span className="text-green-400/70 normal-case font-normal">(use this in emails)</span></p>
              <p className="text-sm text-indigo-300 font-mono">{createdLink?.short}</p>
            </div>
            <div>
              <p className="text-[10px] font-semibold text-white/25 uppercase tracking-wider mb-1">Full Link</p>
              <p className="text-[10px] text-white/30 break-all leading-relaxed font-mono">{createdLink?.full}</p>
            </div>
          </div>

          <div className="flex items-center justify-center gap-3">
            <button
              onClick={copyLink}
              className="inline-flex items-center gap-2 bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white text-sm font-medium px-5 py-2.5 rounded-lg shadow-lg shadow-indigo-500/20"
            >
              {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
              {copied ? 'Copied!' : 'Copy link'}
            </button>
            <Link
              href="/pitch-admin/investors"
              className="text-sm text-white/60 hover:text-white px-4 py-2"
            >
              Back to investors
            </Link>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="max-w-5xl">
      <Link
        href="/pitch-admin/investors"
        className="inline-flex items-center gap-2 text-sm text-white/50 hover:text-white/80 mb-6"
      >
        <ArrowLeft className="w-4 h-4" /> Back to investors
      </Link>

      <h1 className="text-2xl font-semibold text-white mb-2">Investor einladen</h1>
      <p className="text-sm text-white/50 mb-6">
        {sendEmail
          ? `Der Investor erhält eine Email mit einem persönlichen Magic Link (einmalig, verfällt nach ${ttl}h).`
          : `Erstellt den Investor-Datensatz und generiert einen Magic Link — keine Email wird gesendet.`}
      </p>

      <div className="grid lg:grid-cols-2 gap-6">
        {/* Left: Form */}
        <form
          onSubmit={handleSubmit}
          className="bg-white/[0.04] border border-white/[0.08] rounded-2xl p-6 space-y-4 self-start"
        >
          {/* Email */}
          <div>
            <label htmlFor="email" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
              Email <span className="text-rose-400">*</span>
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
              placeholder="investor@example.com"
            />
          </div>

          {/* Name */}
          <div>
            <label htmlFor="name" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
              Name <span className="text-rose-400">*</span>
            </label>
            <input
              id="name"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
              className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
              placeholder="Dr. Max Mustermann"
            />
          </div>

          {/* Company (optional) */}
          <div>
            <label htmlFor="company" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
              Unternehmen <span className="text-white/30 text-[10px] normal-case">(optional)</span>
            </label>
            <input
              id="company"
              type="text"
              value={company}
              onChange={(e) => setCompany(e.target.value)}
              className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
              placeholder="Muster Ventures GmbH"
            />
          </div>

          {/* Pitch Version */}
          <div>
            <label htmlFor="version" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
              <span className="inline-flex items-center gap-1.5"><Layers className="w-3.5 h-3.5" /> Pitch-Version <span className="text-white/30 text-[10px] normal-case">(optional)</span></span>
            </label>
            <select
              id="version"
              value={versionId}
              onChange={(e) => setVersionId(e.target.value)}
              className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40 appearance-none"
            >
              <option value="">— Standard (keine spezifische Version) —</option>
              {versions.map(v => (
                <option key={v.id} value={v.id}>{v.name}</option>
              ))}
            </select>
            {versions.length === 0 && (
              <p className="text-[10px] text-white/25 mt-1">Keine committed Versionen vorhanden</p>
            )}
          </div>

          <hr className="border-white/[0.06]" />

          {/* Language toggle + Send email toggle */}
          <div className="flex items-center gap-3">
            {/* Pitch language */}
            <div className="flex-1">
              <p className="text-xs font-medium text-white/60 uppercase tracking-wider mb-2">Pitch-Sprache</p>
              <div className="flex rounded-lg border border-white/10 overflow-hidden">
                <button
                  type="button"
                  onClick={() => setLang('de')}
                  className={`flex-1 py-2 text-sm font-medium transition-colors ${lang === 'de' ? 'bg-indigo-600 text-white' : 'bg-black/20 text-white/50 hover:text-white/80'}`}
                >
                  🇩🇪 DE
                </button>
                <button
                  type="button"
                  onClick={() => setLang('en')}
                  className={`flex-1 py-2 text-sm font-medium transition-colors ${lang === 'en' ? 'bg-indigo-600 text-white' : 'bg-black/20 text-white/50 hover:text-white/80'}`}
                >
                  🇬🇧 EN
                </button>
              </div>
              <p className="text-[10px] text-white/25 mt-1">Standardsprache beim Öffnen des Decks</p>
            </div>

            {/* Send email toggle */}
            <div className="flex-1">
              <p className="text-xs font-medium text-white/60 uppercase tracking-wider mb-2">Email senden</p>
              <div className="flex rounded-lg border border-white/10 overflow-hidden">
                <button
                  type="button"
                  onClick={() => setSendEmail(true)}
                  className={`flex-1 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${sendEmail ? 'bg-indigo-600 text-white' : 'bg-black/20 text-white/50 hover:text-white/80'}`}
                >
                  <Mail className="w-3.5 h-3.5" /> Ja
                </button>
                <button
                  type="button"
                  onClick={() => setSendEmail(false)}
                  className={`flex-1 py-2 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${!sendEmail ? 'bg-amber-600 text-white' : 'bg-black/20 text-white/50 hover:text-white/80'}`}
                >
                  <MailX className="w-3.5 h-3.5" /> Nein
                </button>
              </div>
              <p className="text-[10px] text-white/25 mt-1">Nein = nur Link generieren</p>
            </div>
          </div>

          {/* Email customization — only shown when sendEmail=true */}
          {sendEmail && (
            <>
              <hr className="border-white/[0.06]" />

              {/* Greeting */}
              <div>
                <label htmlFor="greeting" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
                  Anrede / Greeting
                </label>
                <input
                  id="greeting"
                  type="text"
                  value={greeting}
                  onChange={(e) => setGreeting(e.target.value)}
                  className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
                  placeholder={getDefaultGreeting(name || null, lang)}
                />
                <p className="text-[10px] text-white/25 mt-1">
                  {lang === 'de' ? 'Leer lassen für automatische Anrede basierend auf dem Namen' : 'Leave empty for automatic greeting based on name'}
                </p>
              </div>

              {/* Message */}
              <div>
                <label htmlFor="message" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
                  Nachricht / Message
                </label>
                <textarea
                  id="message"
                  value={message}
                  onChange={(e) => { setMessage(e.target.value); setMessageEdited(true) }}
                  rows={4}
                  className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/40 resize-y"
                />
              </div>

              {/* Closing */}
              <div>
                <label htmlFor="closing" className="block text-xs font-medium text-white/60 uppercase tracking-wider mb-2">
                  Grussformel / Closing
                </label>
                <textarea
                  id="closing"
                  value={closing}
                  onChange={(e) => { setClosing(e.target.value); setClosingEdited(true) }}
                  rows={3}
                  className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2.5 text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/40 resize-y"
                />
              </div>
            </>
          )}

          {!sendEmail && (
            <div className="flex items-start gap-3 bg-amber-500/[0.08] border border-amber-500/20 rounded-xl p-4">
              <MailX className="w-4 h-4 text-amber-400 mt-0.5 shrink-0" />
              <p className="text-xs text-amber-300/80 leading-relaxed">
                Kein Email wird gesendet. Nach dem Erstellen erhältst du den Magic Link zum manuellen Einfügen in deine Outreach-Email.
              </p>
            </div>
          )}

          {error && (
            <div className="text-sm text-rose-300 bg-rose-500/10 border border-rose-500/20 rounded-lg px-3 py-2">
              {error}
            </div>
          )}

          <div className="flex items-center justify-end gap-3 pt-2">
            <Link
              href="/pitch-admin/investors"
              className="text-sm text-white/60 hover:text-white px-4 py-2"
            >
              Abbrechen
            </Link>
            <button
              type="submit"
              disabled={submitting}
              className="inline-flex items-center gap-2 bg-gradient-to-r from-indigo-500 to-purple-600 hover:from-indigo-600 hover:to-purple-700 text-white text-sm font-medium px-5 py-2.5 rounded-lg disabled:opacity-50 shadow-lg shadow-indigo-500/20"
            >
              {sendEmail ? <Send className="w-4 h-4" /> : <Link2 className="w-4 h-4" />}
              {submitting
                ? (sendEmail ? 'Wird gesendet...' : 'Wird erstellt...')
                : (sendEmail ? 'Einladung senden' : 'Erstellen & Link generieren')}
            </button>
          </div>
        </form>

        {/* Right: Email Preview (only when sendEmail=true) */}
        {sendEmail ? (
          <div className="self-start">
            <div className="flex items-center gap-2 mb-3">
              <Eye className="w-4 h-4 text-white/40" />
              <h3 className="text-sm font-semibold text-white/60 uppercase tracking-wider">Email-Vorschau</h3>
            </div>
            <div className="bg-[#0a0a1a] border border-white/[0.08] rounded-2xl p-4 overflow-y-auto max-h-[80vh]">
              <div className="bg-[#111127] border border-indigo-500/20 rounded-xl overflow-hidden">

                <div className="px-6 pt-6 pb-3">
                  <p className="text-lg font-semibold text-[#e0e0ff]">BreakPilot ComplAI</p>
                  <p className="text-xs text-white/40 mt-1">Investor Pitch Deck</p>
                </div>

                <div className="px-6 py-3">
                  <p className="text-sm text-white/80 mb-3">{effectiveGreeting},</p>
                  <p className="text-sm text-white/70 leading-relaxed mb-4" dangerouslySetInnerHTML={{ __html: message }} />

                  <div className="bg-indigo-500/[0.08] border border-indigo-500/[0.15] rounded-lg p-3 mb-4">
                    <p className="text-[10px] font-semibold text-indigo-400/80 uppercase tracking-wider mb-1">
                      {lang === 'en' ? 'Your Personal Access Link' : 'Ihr persönlicher Zugangslink'}
                    </p>
                    <p className="text-xs text-white/50 leading-relaxed">
                      {lang === 'en'
                        ? `The link below is single-use and expires after ${ttl} hours. It grants you exclusive access to our interactive pitch deck — including an AI assistant for your questions.`
                        : `Der untenstehende Link ist einmalig und verfällt nach ${ttl} Stunden. Er gewährt Ihnen exklusiven Zugang zu unserem interaktiven Pitch Deck — inklusive KI-Assistent für Ihre Fragen.`}
                    </p>
                  </div>

                  <div className="text-center mb-3">
                    <span className="inline-block bg-gradient-to-r from-indigo-500 to-purple-600 text-white text-sm font-semibold px-8 py-2.5 rounded-lg">
                      {lang === 'en' ? 'Open Pitch Deck' : 'Pitch Deck öffnen'}
                    </span>
                  </div>

                  <p className="text-[10px] text-white/25 mb-4 break-all">
                    {lang === 'en' ? "If the button doesn't work: " : 'Falls der Button nicht funktioniert: '}
                    https://pitch.breakpilot.ai/auth/verify?token=...
                  </p>

                  <p className="text-sm text-white/70 leading-relaxed" dangerouslySetInnerHTML={{ __html: closingHtml }} />
                </div>

                <div className="px-6 py-4 border-t border-white/[0.05]">
                  <p className="text-[9px] font-semibold text-white/30 uppercase tracking-wider mb-1">
                    Vertraulichkeit &amp; Haftungsausschluss
                  </p>
                  <p className="text-[9px] text-white/[0.18] leading-relaxed mb-2">
                    Dieses Pitch Deck ist vertraulich und wurde ausschließlich für den namentlich eingeladenen Empfänger erstellt. Keine Weitergabe. 3-Jahres-Pflicht. Kein Angebot. Planzahlen ohne Garantie. Totalverlustrisiko. Deutsches Recht, Konstanz.
                  </p>
                  <p className="text-[9px] font-semibold text-white/20 uppercase tracking-wider mb-1">
                    Confidentiality &amp; Disclaimer
                  </p>
                  <p className="text-[9px] text-white/[0.13] leading-relaxed">
                    Confidential. Purpose-limited. 3-year obligation. Not an offer. Projections only. Risk of total loss. German law, Konstanz jurisdiction.
                  </p>
                </div>

              </div>
            </div>
          </div>
        ) : (
          <div className="self-start">
            <div className="flex items-center gap-2 mb-3">
              <Link2 className="w-4 h-4 text-white/40" />
              <h3 className="text-sm font-semibold text-white/60 uppercase tracking-wider">Link-Modus</h3>
            </div>
            <div className="bg-white/[0.03] border border-white/[0.06] rounded-2xl p-6 space-y-4">
              <p className="text-sm text-white/60 leading-relaxed">
                Im Link-Modus wird kein Email gesendet. Stattdessen:
              </p>
              <ol className="space-y-3 text-sm text-white/50">
                <li className="flex items-start gap-3">
                  <span className="w-5 h-5 rounded-full bg-indigo-500/20 text-indigo-400 text-xs flex items-center justify-center shrink-0 mt-0.5">1</span>
                  Investor-Datensatz wird erstellt (Email, Name, Unternehmen)
                </li>
                <li className="flex items-start gap-3">
                  <span className="w-5 h-5 rounded-full bg-indigo-500/20 text-indigo-400 text-xs flex items-center justify-center shrink-0 mt-0.5">2</span>
                  Persönlicher Magic Link wird generiert (einmalig, {ttl}h gültig)
                </li>
                <li className="flex items-start gap-3">
                  <span className="w-5 h-5 rounded-full bg-indigo-500/20 text-indigo-400 text-xs flex items-center justify-center shrink-0 mt-0.5">3</span>
                  Link erscheint hier zum Kopieren — füge ihn in deine Cold-Email ein
                </li>
              </ol>
              <div className="mt-4 bg-amber-500/[0.06] border border-amber-500/15 rounded-lg p-3">
                <p className="text-xs text-amber-300/70">
                  Pitch-Sprache: <strong>{lang === 'en' ? 'Englisch' : 'Deutsch'}</strong> — das Deck öffnet sich beim ersten Klick in dieser Sprache.
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
