'use client'

import { useState, useEffect } from 'react'
import type { Prospect, OutreachConfig, GeneratedOutreach } from '@/lib/types'
import { generateOutreach } from '@/lib/outreach/generate'

interface LeadDetailPanelProps {
  prospect: Prospect | null
  outreachConfig: OutreachConfig
  onClose: () => void
}

const CATEGORY_ICONS: Record<string, string> = {
  'Law Firm': 'balance',
  'Accounting Office': 'calculate',
  'Tax Consultant': 'receipt_long',
  'Business Consultant': 'business_center',
  'Company Formation Office': 'domain_add',
  'HR / Recruitment': 'groups',
  'Immigration / Visa Services': 'travel_explore',
  'Professional Services Agency': 'work',
  'Startup Services': 'rocket_launch',
  'Small B2B Agency': 'hub',
}

export default function LeadDetailPanel({ prospect, outreachConfig, onClose }: LeadDetailPanelProps) {
  const [outreach, setOutreach] = useState<GeneratedOutreach | null>(null)
  const [activeTab, setActiveTab] = useState<'subject' | 'plain' | 'html'>('subject')
  const [copiedKey, setCopiedKey] = useState<string | null>(null)

  useEffect(() => {
    if (prospect) {
      const generated = generateOutreach(prospect, outreachConfig)
      setOutreach(generated)
    } else {
      setOutreach(null)
    }
  }, [prospect, outreachConfig])

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

  if (!prospect) {
    return (
      <aside className="w-80 bg-[#171f33] border-l border-[#574143]/10 flex flex-col items-center justify-center p-8 text-center">
        <span className="material-symbols-outlined text-5xl text-slate-700 mb-4">person_search</span>
        <p className="text-sm text-slate-600 font-medium">Click any row to preview lead details and outreach</p>
      </aside>
    )
  }

  const icon = CATEGORY_ICONS[prospect.normalized_category] || 'business'
  const scoreColor = prospect.score >= 80 ? 'text-[#ac8aff]' : prospect.score >= 50 ? 'text-[#ee9800]' : 'text-slate-500'
  const tagStyle = prospect.lead_tag === 'High Potential'
    ? 'text-[#ac8aff] bg-[#ac8aff]/10'
    : prospect.lead_tag === 'Medium Potential'
      ? 'text-[#ee9800] bg-[#ee9800]/10'
      : 'text-slate-400 bg-[#574143]/20'

  return (
    <aside className="w-80 bg-[#171f33] border-l border-[#574143]/10 flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="p-5 border-b border-[#574143]/10">
        <div className="flex items-center justify-between mb-4">
          <span className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Lead Preview</span>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors">
            <span className="material-symbols-outlined text-lg">close</span>
          </button>
        </div>

        <div className="flex items-start gap-3 mb-4">
          <div className="w-14 h-14 rounded-xl bg-[#2d3449] flex items-center justify-center text-[#ffb2b9] border border-[#ffb2b9]/20 flex-shrink-0">
            <span className="material-symbols-outlined text-2xl">{icon}</span>
          </div>
          <div>
            <h3 className="text-base font-extrabold text-[#dae2fd] leading-tight" style={{ fontFamily: 'Manrope, sans-serif' }}>
              {prospect.business_name}
            </h3>
            <p className="text-sm text-[#ffb2b9] font-bold">{prospect.normalized_category}</p>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="bg-[#222a3d] p-3 rounded-xl">
            <p className="text-[9px] font-bold text-slate-500 uppercase mb-1">Score</p>
            <p className={`text-xl font-black ${scoreColor}`}>{prospect.score}<span className="text-xs">/100</span></p>
          </div>
          <div className="bg-[#222a3d] p-3 rounded-xl">
            <p className="text-[9px] font-bold text-slate-500 uppercase mb-1">Tag</p>
            <span className={`text-[10px] font-black px-2 py-0.5 rounded ${tagStyle}`}>
              {prospect.lead_tag === 'High Potential' ? 'High' : prospect.lead_tag === 'Medium Potential' ? 'Medium' : 'Low'}
            </span>
          </div>
        </div>
      </div>

      {/* Scrollable body */}
      <div className="flex-1 overflow-y-auto p-5 space-y-5">
        {/* Business Info */}
        <div>
          <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Business Info</p>
          <div className="space-y-2">
            {[
              { icon: 'location_city', label: 'City', value: prospect.city },
              { icon: 'location_on', label: 'Address', value: prospect.address },
              { icon: 'call', label: 'Phone', value: prospect.phone },
              { icon: 'mail', label: 'Email', value: prospect.email },
              { icon: 'language', label: 'Website', value: prospect.website },
            ].filter(f => f.value).map(f => (
              <div key={f.label} className="flex items-center gap-2">
                <span className="material-symbols-outlined text-slate-500 text-[16px]">{f.icon}</span>
                <span className="text-[11px] text-slate-300 truncate">{f.value}</span>
              </div>
            ))}
            <div className="flex items-center gap-2">
              <span className="material-symbols-outlined text-slate-500 text-[16px]">link</span>
              <a href={prospect.source_url} target="_blank" rel="noreferrer" className="text-[11px] text-[#ffb2b9] hover:underline truncate">
                View source
              </a>
            </div>
          </div>
        </div>

        {/* Qualification */}
        <div>
          <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Qualification</p>
          <div className="grid grid-cols-2 gap-2">
              {[
                { label: 'Website', value: prospect.presence_status },
                { label: 'Reachability', value: prospect.contactability },
                { label: 'Source', value: prospect.source_label },
                { label: 'Mode', value: prospect.acquisition_mode === 'real' ? 'Live Retrieved' : 'Demo Fallback' },
                { label: 'Confidence', value: `${prospect.result_confidence}%` },
                { label: 'Completeness', value: `${prospect.data_completeness}%` },
              ].map(f => (
              <div key={f.label} className="bg-[#131b2e] p-2.5 rounded-xl">
                <p className="text-[9px] text-slate-600 font-bold uppercase mb-1">{f.label}</p>
                <p className="text-[11px] font-bold text-slate-300">{f.value}</p>
              </div>
            ))}
          </div>
          <p className="text-[11px] text-slate-500 mt-2 leading-relaxed">{prospect.source_note}</p>
        </div>

        {prospect.matched_scope === 'team' && (
          <div>
            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Team Context</p>
            <div className="space-y-2">
              <div className="bg-[#131b2e] p-3 rounded-xl">
                <p className="text-[9px] text-slate-600 font-bold uppercase mb-1">Owner</p>
                <p className="text-[12px] font-bold text-slate-200">{prospect.matched_owner_name ?? 'Team lead'}</p>
              </div>
              <div className="bg-[#131b2e] p-3 rounded-xl">
                <p className="text-[9px] text-slate-600 font-bold uppercase mb-1">Assigned</p>
                <p className="text-[12px] font-bold text-slate-200">{prospect.matched_assigned_name ?? 'Unassigned'}</p>
              </div>
              <p className="text-[11px] text-slate-500 leading-relaxed">
                {prospect.matched_visibility_scope === 'private'
                  ? 'This team lead is private to its owner or assignee.'
                  : 'This team lead is shared for visibility across the team.'}
              </p>
            </div>
          </div>
        )}

        {/* Mspacez Match */}
        <div>
          <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Mspacez Match</p>
          <div className="flex items-center gap-2 bg-[#ffb2b9]/5 p-3 rounded-xl border border-[#ffb2b9]/20 mb-2">
            <span className="material-symbols-outlined text-[#ffb2b9] text-sm">apartment</span>
            <span className="text-sm font-bold text-[#dae2fd]">{prospect.suggested_branch}</span>
          </div>
          <div className="flex items-center gap-2 bg-[#222a3d] p-3 rounded-xl">
            <span className="material-symbols-outlined text-slate-400 text-sm">handshake</span>
            <span className="text-sm text-slate-300">Offer: <strong className="text-[#dae2fd]">{prospect.offer_type}</strong></span>
          </div>
        </div>

        {/* Outreach Preview */}
        {outreach && (
          <div>
            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-3">Outreach Preview</p>

            {/* Tabs */}
            <div className="flex bg-[#131b2e] p-1 rounded-xl mb-3">
              {(['subject', 'plain', 'html'] as const).map(tab => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`flex-1 py-1.5 text-[10px] font-bold uppercase tracking-wide rounded-lg transition-all ${
                    activeTab === tab ? 'bg-[#222a3d] text-white' : 'text-slate-500 hover:text-white'
                  }`}
                >
                  {tab === 'subject' ? 'Subjects' : tab === 'plain' ? 'Text' : 'HTML'}
                </button>
              ))}
            </div>

            {activeTab === 'subject' && (
              <div className="space-y-2">
                {Object.entries(outreach.subjects).map(([key, subject]) => (
                  <div
                    key={key}
                    className="group flex items-start justify-between p-3 bg-[#131b2e] rounded-xl border border-[#574143]/5 hover:border-[#ffb2b9]/30 transition-all cursor-pointer"
                    onClick={() => copy(subject, key)}
                  >
                    <p className="text-[11px] text-[#dae2fd] pr-2 leading-relaxed">{subject}</p>
                    <span className="material-symbols-outlined text-[14px] text-slate-600 group-hover:text-[#ffb2b9] flex-shrink-0 mt-0.5">
                      {copiedKey === key ? 'check' : 'content_copy'}
                    </span>
                  </div>
                ))}
              </div>
            )}

            {activeTab === 'plain' && (
              <div className="relative">
                <div className="bg-[#131b2e] rounded-xl p-4 border border-[#574143]/10 max-h-60 overflow-y-auto">
                  <pre className="text-[11px] text-slate-300 whitespace-pre-wrap font-sans leading-relaxed">
                    {outreach.plain_text}
                  </pre>
                </div>
                <button
                  onClick={() => copy(outreach.plain_text, 'plain')}
                  className="mt-2 w-full py-1.5 text-[10px] font-bold text-slate-400 hover:text-white bg-[#131b2e] rounded-xl transition-colors flex items-center justify-center gap-1"
                >
                  <span className="material-symbols-outlined text-[14px]">
                    {copiedKey === 'plain' ? 'check' : 'content_copy'}
                  </span>
                  {copiedKey === 'plain' ? 'Copied!' : 'Copy Plain Text'}
                </button>
              </div>
            )}

            {activeTab === 'html' && (
              <div>
                <div className="bg-white rounded-xl overflow-hidden border border-[#574143]/10 mb-2" style={{ height: '220px' }}>
                  <iframe
                    srcDoc={outreach.html}
                    className="w-full h-full border-0"
                    title="HTML Email Preview"
                    sandbox="allow-same-origin"
                  />
                </div>
                <button
                  onClick={() => copy(outreach.html, 'html')}
                  className="w-full py-1.5 text-[10px] font-bold text-slate-400 hover:text-white bg-[#131b2e] rounded-xl transition-colors flex items-center justify-center gap-1"
                >
                  <span className="material-symbols-outlined text-[14px]">
                    {copiedKey === 'html' ? 'check' : 'content_copy'}
                  </span>
                  {copiedKey === 'html' ? 'Copied!' : 'Copy HTML'}
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Bottom action */}
      <div className="p-5 bg-[#222a3d]/50 border-t border-[#574143]/10">
        <button
          onClick={() => outreach && copy(outreach.plain_text, 'bottom_copy')}
          className="w-full py-3.5 bg-gradient-to-br from-[#ffb2b9] to-[#fb7185] text-[#6f0122] font-black rounded-xl shadow-lg hover:shadow-[#fb7185]/20 active:scale-95 transition-all flex items-center justify-center gap-2 text-sm"
        >
          <span className="material-symbols-outlined">content_copy</span>
          Copy Outreach
        </button>
      </div>
    </aside>
  )
}
