'use client'

import { useEffect, useMemo, useState } from 'react'
import { createLeadEvent } from '@/lib/leads/api'
import { generateOutreach } from '@/lib/outreach/generate'
import {
  buildEmailHandoffUrls,
  getDefaultSubjectVariant,
  selectSubject,
  SUBJECT_VARIANT_LABELS,
} from '@/lib/outreach/handoff'
import { hasGlobalLeadScope } from '@/lib/auth/roles'
import type {
  AppUser,
  GeneratedOutreach,
  LeadRecord,
  OutreachConfig,
  OutreachSubjectVariant,
  Prospect,
} from '@/lib/types'

interface OutreachComposerProps {
  prospects: Prospect[]
  config: OutreachConfig
  currentUser: AppUser
  onConfigChange: (config: OutreachConfig) => void
  onLeadTracked: (lead: LeadRecord) => void
}

export default function OutreachComposer({
  prospects,
  config,
  currentUser,
  onConfigChange,
  onLeadTracked,
}: OutreachComposerProps) {
  const [selectedProspect, setSelectedProspect] = useState<Prospect | null>(prospects[0] ?? null)
  const [activePreviewTab, setActivePreviewTab] = useState<'html' | 'plain'>('html')
  const [copiedKey, setCopiedKey] = useState<string | null>(null)
  const [selectedSubjectVariant, setSelectedSubjectVariant] = useState<OutreachSubjectVariant>(getDefaultSubjectVariant(config.email_tone))
  const [error, setError] = useState('')
  const [actionState, setActionState] = useState<'idle' | 'sending'>('idle')

  useEffect(() => {
    setSelectedProspect(current => {
      if (!prospects.length) {
        return null
      }

      if (current && prospects.some(prospect => prospect.id === current.id)) {
        return current
      }

      return prospects[0]
    })
  }, [prospects])

  useEffect(() => {
    setSelectedSubjectVariant(getDefaultSubjectVariant(config.email_tone))
  }, [config.email_tone, selectedProspect?.id])

  const update = (key: keyof OutreachConfig, value: string | number) => {
    onConfigChange({ ...config, [key]: value })
  }

  const outreach: GeneratedOutreach | null = selectedProspect
    ? generateOutreach(selectedProspect, config)
    : null

  const selectedSubject = useMemo(() => {
    if (!outreach) return ''
    return selectSubject(outreach, selectedSubjectVariant)
  }, [outreach, selectedSubjectVariant])

  const canTrackEmail = Boolean(
    selectedProspect?.matched_lead_id &&
    selectedProspect.email &&
    (
      hasGlobalLeadScope(currentUser) ||
      selectedProspect.matched_scope !== 'team' ||
      selectedProspect.matched_assigned_to === currentUser.id
    )
  )

  const trackabilityMessage = !selectedProspect
    ? 'Select a lead to prepare outreach.'
    : !selectedProspect.email
      ? 'This lead does not have an email address yet.'
      : !selectedProspect.matched_lead_id
        ? 'Save this lead to the shared library first so outreach can be tracked.'
        : !hasGlobalLeadScope(currentUser) && selectedProspect.matched_scope === 'team' && selectedProspect.matched_assigned_to !== currentUser.id
          ? 'This team lead is assigned to another teammate. Reassign it in CRM first or ask an admin to handle the outreach.'
          : 'Tracked Gmail handoff is ready for this lead.'

  const copy = (text: string, key: string) => {
    navigator.clipboard.writeText(text)
    setCopiedKey(key)
    setTimeout(() => setCopiedKey(null), 1500)
  }

  const handleSendEmail = async () => {
    if (!selectedProspect || !outreach || !selectedProspect.matched_lead_id || !selectedProspect.email) {
      setError('This lead does not have an email address yet.')
      return
    }

    const { gmail, fallback } = buildEmailHandoffUrls({
      to: selectedProspect.email,
      subject: selectedSubject,
      body: outreach.plain_text,
    })
    const composeWindow = window.open('', '_blank', 'noopener,noreferrer')
    if (composeWindow) {
      composeWindow.document.write('<title>Opening email…</title><p style="font-family:sans-serif;padding:24px">Opening your email compose window…</p>')
    }

    setActionState('sending')
    setError('')

    const openComposeUrl = (url: string) => {
      if (composeWindow && !composeWindow.closed) {
        composeWindow.location.replace(url)
        return
      }

      const popup = window.open(url, '_blank', 'noopener,noreferrer')
      if (!popup) {
        window.location.href = url
      }
    }

    try {
      const updated = await createLeadEvent(selectedProspect.matched_lead_id, {
        event_type: 'email_sent',
        note: `Gmail compose handoff opened using the ${SUBJECT_VARIANT_LABELS[selectedSubjectVariant].toLowerCase()} subject.`,
        metadata: {
          outreach_type: 'gmail_handoff',
          subject: selectedSubject,
          recipient: selectedProspect.email,
          language: config.language,
          tone: config.email_tone,
          style: config.email_style,
          subject_variant: selectedSubjectVariant,
          body_preview: outreach.plain_text.slice(0, 500),
        },
      })

      onLeadTracked(updated.lead)
    } catch (err) {
      setError(err instanceof Error ? `${err.message}. Gmail compose will still open.` : 'Tracking failed, but Gmail compose will still open.')
    } finally {
      openComposeUrl(gmail || fallback)
      setActionState('idle')
    }
  }

  return (
    <div className="flex h-full overflow-hidden">
      <section className="w-72 bg-[#0b1326] border-r border-[#574143]/10 p-6 overflow-y-auto flex-shrink-0">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-lg font-bold text-white" style={{ fontFamily: 'Manrope, sans-serif' }}>Composer</h3>
          <span className="bg-[#fb7185]/10 text-[#fb7185] text-[10px] font-bold px-2 py-0.5 rounded-full border border-[#fb7185]/20">
            {prospects.length} LEADS
          </span>
        </div>

        <div className="space-y-5">
          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Sender Profile</label>
            <input
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              type="text"
              placeholder="Your name"
              value={config.sender_name}
              onChange={e => update('sender_name', e.target.value)}
            />
            <input
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              type="text"
              placeholder="Your role"
              value={config.sender_role}
              onChange={e => update('sender_role', e.target.value)}
            />
            <input
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              type="text"
              placeholder="Company name"
              value={config.sender_company}
              onChange={e => update('sender_company', e.target.value)}
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Offer Details</label>
            <div className="grid grid-cols-2 gap-2">
              <div className="relative">
                <input
                  className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 pr-14 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
                  type="number"
                  min={0}
                  max={100}
                  value={config.commission_percent}
                  onChange={e => update('commission_percent', Number(e.target.value))}
                />
                <span className="absolute right-3 top-2.5 text-[10px] text-slate-400 font-bold">% COMM</span>
              </div>
              <div className="relative">
                <input
                  className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 pr-14 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
                  type="number"
                  min={0}
                  max={100}
                  value={config.client_discount_percent}
                  onChange={e => update('client_discount_percent', Number(e.target.value))}
                />
                <span className="absolute right-3 top-2.5 text-[10px] text-slate-400 font-bold">% DISC</span>
              </div>
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Exclusivity Note</label>
            <textarea
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none resize-none"
              rows={3}
              placeholder="e.g. Regional exclusivity for first 90 days…"
              value={config.exclusivity_text}
              onChange={e => update('exclusivity_text', e.target.value)}
            />
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Email Tone</label>
            <select
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              value={config.email_tone}
              onChange={e => update('email_tone', e.target.value)}
            >
              <option>Executive Professional</option>
              <option>Direct</option>
              <option>Partnership-Focused</option>
            </select>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Language</label>
            <div className="grid grid-cols-2 gap-2">
              {(['English', 'Arabic'] as const).map(language => (
                <button
                  key={language}
                  type="button"
                  onClick={() => update('language', language)}
                  className={`py-2.5 rounded-xl text-xs font-bold transition-all ${
                    config.language === language
                      ? 'bg-[#ffb2b9]/20 text-[#ffb2b9] border border-[#ffb2b9]/30'
                      : 'bg-[#222a3d] text-slate-400 border border-[#574143]/10 hover:text-white'
                  }`}
                >
                  {language}
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Email Version</label>
            <div className="grid grid-cols-2 gap-2">
              {[
                { key: 'short', label: 'Short Outreach' },
                { key: 'full', label: 'Full Credibility' },
              ].map(style => (
                <button
                  key={style.key}
                  type="button"
                  onClick={() => update('email_style', style.key)}
                  className={`py-2.5 rounded-xl text-xs font-bold transition-all ${
                    config.email_style === style.key
                      ? 'bg-[#ffb2b9]/20 text-[#ffb2b9] border border-[#ffb2b9]/30'
                      : 'bg-[#222a3d] text-slate-400 border border-[#574143]/10 hover:text-white'
                  }`}
                >
                  {style.label}
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">CTA</label>
            <input
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              type="text"
              placeholder="CTA text"
              value={config.cta_text}
              onChange={e => update('cta_text', e.target.value)}
            />
            <input
              className="w-full bg-[#222a3d] border-none rounded-xl text-sm text-[#fb7185]/80 px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
              type="text"
              placeholder="Calendly link / contact"
              value={config.cta_contact}
              onChange={e => update('cta_contact', e.target.value)}
            />
          </div>

          <div className="p-4 bg-[#060e20] rounded-xl border border-[#574143]/10">
            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-tighter mb-3">Tracked Gmail Status</p>
            <p className={`text-xs leading-relaxed ${canTrackEmail ? 'text-[#9fe8c4]' : 'text-slate-400'}`}>
              {trackabilityMessage}
            </p>
          </div>
        </div>
      </section>

      <section className="flex-1 bg-[#060e20] p-8 overflow-y-auto">
        <div className="max-w-2xl mx-auto space-y-6">
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-extrabold text-white tracking-tight" style={{ fontFamily: 'Manrope, sans-serif' }}>
              Outreach Preview
            </h2>
            <div className="flex bg-[#2d3449] p-1 rounded-xl">
              <button
                onClick={() => setActivePreviewTab('html')}
                className={`px-4 py-1.5 text-xs font-bold rounded-lg transition-all ${activePreviewTab === 'html' ? 'bg-[#222a3d] text-white shadow-sm' : 'text-slate-400 hover:text-white'}`}
              >
                HTML Preview
              </button>
              <button
                onClick={() => setActivePreviewTab('plain')}
                className={`px-4 py-1.5 text-xs font-bold rounded-lg transition-all ${activePreviewTab === 'plain' ? 'bg-[#222a3d] text-white shadow-sm' : 'text-slate-400 hover:text-white'}`}
              >
                Plain Text
              </button>
            </div>
          </div>

          {prospects.length > 0 && (
            <div className="flex flex-col gap-1.5">
              <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Preview For Lead</label>
              <select
                className="bg-[#222a3d] border-none rounded-xl text-sm text-[#dae2fd] px-3 py-2.5 focus:ring-1 focus:ring-[#fb7185]/50 focus:outline-none"
                value={selectedProspect?.id || ''}
                onChange={e => {
                  const prospect = prospects.find(item => item.id === e.target.value)
                  if (prospect) setSelectedProspect(prospect)
                }}
              >
                {prospects.map(prospect => (
                  <option key={prospect.id} value={prospect.id}>
                    {prospect.business_name} — {prospect.city}
                  </option>
                ))}
              </select>
            </div>
          )}

          {error && (
            <div className="p-3 rounded-xl border border-red-500/20 bg-red-500/10 text-sm text-red-300">
              {error}
            </div>
          )}

          {outreach && (
            <>
              <div className="flex flex-wrap items-center gap-2">
                <span className="px-2.5 py-1 rounded-full bg-[#131b2e] text-[10px] font-black uppercase tracking-widest text-[#ffb2b9] border border-[#ffb2b9]/20">
                  {outreach.language}
                </span>
                <span className="px-2.5 py-1 rounded-full bg-[#131b2e] text-[10px] font-black uppercase tracking-widest text-slate-300 border border-[#574143]/10">
                  {outreach.style === 'short' ? 'Short Outreach' : 'Full Credibility'}
                </span>
                <span className="px-2.5 py-1 rounded-full bg-[#131b2e] text-[10px] font-black uppercase tracking-widest text-[#9fe8c4] border border-[#9fe8c4]/20">
                  {config.email_tone}
                </span>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Subject Line Options</p>
                  <p className="text-[11px] text-slate-500">Selected for Gmail: {SUBJECT_VARIANT_LABELS[selectedSubjectVariant]}</p>
                </div>
                <div className="space-y-2">
                  {(Object.entries(outreach.subjects) as [OutreachSubjectVariant, string][]).map(([key, subject]) => {
                    const selected = key === selectedSubjectVariant
                    return (
                      <div
                        key={key}
                        onClick={() => setSelectedSubjectVariant(key)}
                        className={`group flex items-center justify-between p-4 border rounded-xl transition-all cursor-pointer ${
                          selected
                            ? 'bg-[#ffb2b9]/10 border-[#ffb2b9]/30'
                            : 'bg-[#131b2e] border-[#574143]/5 hover:border-[#fb7185]/30'
                        }`}
                      >
                        <div className="flex items-center gap-3">
                          <span className={`w-1.5 h-1.5 rounded-full ${key === 'professional' ? 'bg-[#ffb95f]' : key === 'direct' ? 'bg-[#fb7185]' : 'bg-[#d0bcff]'}`} />
                          <div>
                            <p className="text-sm text-[#dae2fd]">{subject}</p>
                            <p className="text-[10px] text-slate-500 uppercase tracking-widest mt-1">{SUBJECT_VARIANT_LABELS[key]}</p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={event => {
                            event.stopPropagation()
                            copy(subject, key)
                          }}
                          className={`flex items-center gap-1 text-[10px] font-bold ${copiedKey === key ? 'text-[#fb7185]' : 'text-slate-500 group-hover:text-white'}`}
                        >
                          <span className="material-symbols-outlined text-sm">{copiedKey === key ? 'check' : 'content_copy'}</span>
                          {selected ? 'Selected' : 'Copy'}
                        </button>
                      </div>
                    )
                  })}
                </div>
              </div>

              {activePreviewTab === 'html' ? (
                <div className="bg-white rounded-xl overflow-hidden border border-white/5 shadow-2xl">
                  <div className="bg-[#060e20] p-4 flex items-center justify-between">
                    <div className="flex gap-1.5">
                      <div className="w-3 h-3 rounded-full bg-[#ffb4ab]/20" />
                      <div className="w-3 h-3 rounded-full bg-[#ffb95f]/20" />
                      <div className="w-3 h-3 rounded-full bg-[#d0bcff]/20" />
                    </div>
                    <p className="text-[10px] font-bold text-slate-400 uppercase">HTML Email Preview</p>
                    <button
                      onClick={() => copy(outreach.html, 'html_body')}
                      className="text-[10px] text-slate-400 hover:text-white flex items-center gap-1"
                    >
                      <span className="material-symbols-outlined text-sm">{copiedKey === 'html_body' ? 'check' : 'content_copy'}</span>
                      {copiedKey === 'html_body' ? 'Copied' : 'Copy HTML'}
                    </button>
                  </div>
                  <div style={{ height: '500px', overflow: 'auto' }}>
                    <iframe srcDoc={outreach.html} className="w-full border-0" style={{ height: '600px' }} title="Email HTML" sandbox="allow-same-origin" />
                  </div>
                </div>
              ) : (
                <div className="bg-[#131b2e] rounded-xl p-6 border border-[#574143]/10">
                  <pre className="text-sm text-slate-300 whitespace-pre-wrap font-sans leading-relaxed">
                    {outreach.plain_text}
                  </pre>
                  <button
                    onClick={() => copy(outreach.plain_text, 'plain_body')}
                    className="mt-4 px-4 py-2 text-xs font-bold text-slate-400 hover:text-white bg-[#222a3d] rounded-xl transition-colors flex items-center gap-2"
                  >
                    <span className="material-symbols-outlined text-sm">{copiedKey === 'plain_body' ? 'check' : 'content_copy'}</span>
                    {copiedKey === 'plain_body' ? 'Copied!' : 'Copy Plain Text'}
                  </button>
                </div>
              )}

              <div className="flex flex-wrap items-center gap-3">
                <button
                  onClick={handleSendEmail}
                  disabled={!canTrackEmail || actionState === 'sending'}
                  className="px-5 py-3 rounded-xl text-[#6f0122] font-black text-sm bg-gradient-to-br from-[#ffb2b9] to-[#fb7185] transition-transform active:scale-95 hover:opacity-90 disabled:opacity-40"
                >
                  {actionState === 'sending' ? 'Opening Gmail…' : 'Send Email via Gmail'}
                </button>
                <button
                  onClick={() => copy(outreach.plain_text, 'bottom_copy')}
                  className="px-5 py-3 rounded-xl text-slate-100 font-bold text-sm bg-[#222a3d] border border-[#574143]/10 transition-transform active:scale-95 hover:text-white"
                >
                  {copiedKey === 'bottom_copy' ? 'Copied Outreach' : 'Copy Outreach'}
                </button>
                <p className="text-xs text-slate-500">
                  Gmail uses the selected subject and the plain-text body for the most reliable handoff.
                </p>
              </div>
            </>
          )}

          {prospects.length === 0 && (
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <span className="material-symbols-outlined text-6xl text-slate-700 mb-4">mail</span>
              <p className="text-slate-500">Run a search or use your saved Lead Library to generate outreach previews.</p>
            </div>
          )}
        </div>
      </section>
    </div>
  )
}
