'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Mail, Ban, Save, Link2, RefreshCw } from 'lucide-react'
import AuditLogTable from '@/components/pitch-admin/AuditLogTable'

interface InvestorDetail {
  investor: {
    id: string
    email: string
    name: string | null
    company: string | null
    status: string
    last_login_at: string | null
    login_count: number
    created_at: string
    first_activity_at: string | null
    data_masked_at: string | null
    assigned_version_id: string | null
    version_name: string | null
    version_status: string | null
    is_showcase: boolean
    preferred_lang: 'de' | 'en'
  }
  sessions: Array<{
    id: string
    ip_address: string | null
    user_agent: string | null
    expires_at: string
    revoked: boolean
    created_at: string
  }>
  snapshots: Array<{
    id: string
    scenario_id: string
    label: string | null
    is_latest: boolean
    created_at: string
  }>
  audit: Array<{
    id: number
    action: string
    created_at: string
    details: Record<string, unknown> | null
    ip_address: string | null
    slide_id: string | null
    admin_email: string | null
    admin_name: string | null
  }>
}

const STATUS_STYLES: Record<string, string> = {
  invited: 'bg-amber-500/15 text-amber-300 border-amber-500/30',
  active: 'bg-green-500/15 text-green-300 border-green-500/30',
  revoked: 'bg-rose-500/15 text-rose-300 border-rose-500/30',
  anonymized: 'bg-zinc-500/15 text-zinc-400 border-zinc-500/30',
}

export default function InvestorDetailPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const [data, setData] = useState<InvestorDetail | null>(null)
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState(false)
  const [name, setName] = useState('')
  const [company, setCompany] = useState('')
  const [busy, setBusy] = useState(false)
  const [toast, setToast] = useState<string | null>(null)
  const [versions, setVersions] = useState<Array<{ id: string; name: string; status: string }>>([])

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

  function flashToast(msg: string) {
    setToast(msg)
    setTimeout(() => setToast(null), 3000)
  }

  async function load() {
    setLoading(true)
    const res = await fetch(`/api/admin/investors/${id}`)
    if (res.ok) {
      const d = await res.json()
      setData(d)
      setName(d.investor.name || '')
      setCompany(d.investor.company || '')
    }
    setLoading(false)
  }

  useEffect(() => { if (id) load() }, [id])

  async function save() {
    setBusy(true)
    const res = await fetch(`/api/admin/investors/${id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, company }),
    })
    setBusy(false)
    if (res.ok) {
      setEditing(false)
      flashToast('Saved')
      load()
    } else {
      flashToast('Save failed')
    }
  }

  async function generateLink() {
    setBusy(true)
    const res = await fetch(`/api/admin/investors/${id}/generate-link`, { method: 'POST' })
    setBusy(false)
    if (res.ok) {
      const d = await res.json()
      const link = d.short_url || d.url
      try {
        await navigator.clipboard.writeText(link)
        flashToast('Short link copied to clipboard')
      } catch {
        flashToast(`Link (copy manually): ${link}`)
      }
    } else {
      const err = await res.json().catch(() => ({}))
      flashToast(err.error || 'Failed to generate link')
    }
  }

  async function resend() {
    setBusy(true)
    const res = await fetch(`/api/admin/investors/${id}/resend`, { method: 'POST' })
    setBusy(false)
    if (res.ok) {
      flashToast('Magic link resent via email')
      load()
    } else {
      const err = await res.json().catch(() => ({}))
      flashToast(err.error || 'Resend failed')
    }
  }

  async function revoke() {
    if (!confirm('Revoke this investor\'s access? This signs them out and prevents future logins.')) return
    setBusy(true)
    const res = await fetch('/api/admin/revoke', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ investor_id: id }),
    })
    setBusy(false)
    if (res.ok) {
      flashToast('Revoked')
      load()
    } else {
      flashToast('Revoke failed')
    }
  }

  if (loading) return <div className="flex items-center justify-center h-64"><div className="w-8 h-8 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin" /></div>
  if (!data) return <div className="text-rose-400">Investor not found</div>

  const inv = data.investor

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

      {/* Header */}
      <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-6">
        <div className="flex items-start justify-between gap-4 flex-wrap">
          <div className="min-w-0 flex-1">
            {editing ? (
              <div className="space-y-3">
                <input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Name"
                  className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-white text-lg font-semibold focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
                />
                <input
                  value={company}
                  onChange={(e) => setCompany(e.target.value)}
                  placeholder="Company"
                  className="w-full bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
                />
              </div>
            ) : (
              <>
                <div className="flex items-center gap-3 mb-1 flex-wrap">
                  <h1 className="text-2xl font-semibold text-white">
                    {inv.data_masked_at ? <span className="text-zinc-500 italic">[data protected]</span> : (inv.name || inv.email)}
                  </h1>
                  <span className={`text-[10px] px-2 py-0.5 rounded-full border uppercase font-semibold ${inv.data_masked_at ? STATUS_STYLES.anonymized : STATUS_STYLES[inv.status]}`}>
                    {inv.data_masked_at ? 'anonymized' : inv.status}
                  </span>
                </div>
                {inv.data_masked_at ? (
                  <div className="text-xs text-zinc-500 mt-1">
                    Data anonymized on {new Date(inv.data_masked_at).toLocaleString()} · 30-day inactivity window elapsed
                  </div>
                ) : (
                  <>
                    <div className="text-sm text-white/60">{inv.company || '—'}</div>
                    <div className="text-xs text-white/40 mt-1">{inv.email}</div>
                    {inv.last_login_at && (
                      <div className="text-xs text-amber-400/70 mt-1">
                        ⏱ Data window: 30 days after last login · auto-anonymizes {new Date(new Date(inv.last_login_at).getTime() + 30 * 24 * 60 * 60 * 1000).toLocaleString()}
                      </div>
                    )}
                  </>
                )}
              </>
            )}
          </div>
          <div className="flex items-center gap-2">
            {editing ? (
              <>
                <button
                  onClick={() => { setEditing(false); setName(inv.name || ''); setCompany(inv.company || '') }}
                  className="text-sm text-white/60 hover:text-white px-3 py-2"
                >
                  Cancel
                </button>
                <button
                  onClick={save}
                  disabled={busy}
                  className="bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-50"
                >
                  <Save className="w-4 h-4" /> Save
                </button>
              </>
            ) : (
              <>
                {!inv.data_masked_at && (
                  <button
                    onClick={() => setEditing(true)}
                    className="bg-white/[0.06] hover:bg-white/[0.1] text-white text-sm px-4 py-2 rounded-lg"
                  >
                    Edit
                  </button>
                )}
                <button
                  onClick={generateLink}
                  disabled={busy || !!inv.data_masked_at || inv.status === 'revoked'}
                  className="bg-emerald-500/15 hover:bg-emerald-500/25 text-emerald-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-30"
                  title="Generate link without sending email — copies to clipboard"
                >
                  {busy ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Link2 className="w-4 h-4" />} Copy Link
                </button>
                <button
                  onClick={resend}
                  disabled={busy || !!inv.data_masked_at || inv.status === 'revoked'}
                  className="bg-indigo-500/15 hover:bg-indigo-500/25 text-indigo-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-30"
                >
                  <Mail className="w-4 h-4" /> Resend Email
                </button>
                <button
                  onClick={revoke}
                  disabled={busy || inv.status === 'revoked'}
                  className="bg-rose-500/15 hover:bg-rose-500/25 text-rose-300 text-sm px-4 py-2 rounded-lg flex items-center gap-2 disabled:opacity-30"
                >
                  <Ban className="w-4 h-4" /> Revoke
                </button>
              </>
            )}
          </div>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-white/[0.06]">
          <div>
            <div className="text-xs text-white/40 uppercase tracking-wider">Logins</div>
            <div className="text-xl text-white font-semibold mt-1">{inv.login_count}</div>
          </div>
          <div>
            <div className="text-xs text-white/40 uppercase tracking-wider">First activity</div>
            <div className="text-sm text-white/80 mt-1">
              {inv.first_activity_at ? new Date(inv.first_activity_at).toLocaleString() : '—'}
            </div>
          </div>
          <div>
            <div className="text-xs text-white/40 uppercase tracking-wider">Sessions</div>
            <div className="text-xl text-white font-semibold mt-1">{data.sessions.length}</div>
          </div>
          <div>
            <div className="text-xs text-white/40 uppercase tracking-wider">Snapshots</div>
            <div className="text-xl text-white font-semibold mt-1">{data.snapshots.length}</div>
          </div>
        </div>
      </div>

      {/* Version assignment */}
      <section className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
        <h2 className="text-sm font-semibold text-white mb-3">Pitch Version</h2>
        <div className="flex items-center gap-3 flex-wrap">
          <select
            value={inv.assigned_version_id || ''}
            onChange={async (e) => {
              const versionId = e.target.value || null
              setBusy(true)
              const res = await fetch(`/api/admin/investors/${id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ assigned_version_id: versionId }),
              })
              setBusy(false)
              if (res.ok) { flashToast('Version updated'); load() }
              else { flashToast('Update failed') }
            }}
            disabled={busy}
            className="bg-black/30 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
          >
            <option value="">Default (base tables)</option>
            {versions.map(v => (
              <option key={v.id} value={v.id}>{v.name}</option>
            ))}
          </select>
          <span className="text-xs text-white/40">
            {inv.assigned_version_id
              ? `Sees version "${inv.version_name || ''}"`
              : 'Sees default pitch data'}
          </span>
        </div>

        {/* Default language */}
        <div className="mt-4 pt-4 border-t border-white/[0.06]">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm text-white font-medium">Default pitch language</div>
              <div className="text-xs text-white/40 mt-0.5">Language the deck opens in when the investor clicks the link</div>
            </div>
            <div className="flex rounded-lg border border-white/10 overflow-hidden">
              {(['de', 'en'] as const).map(l => (
                <button
                  key={l}
                  disabled={busy}
                  onClick={async () => {
                    if (inv.preferred_lang === l) return
                    setBusy(true)
                    const res = await fetch(`/api/admin/investors/${id}`, {
                      method: 'PATCH',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({ preferred_lang: l }),
                    })
                    setBusy(false)
                    if (res.ok) { flashToast(`Language set to ${l.toUpperCase()}`); load() }
                    else { flashToast('Update failed') }
                  }}
                  className={`px-4 py-1.5 text-sm font-medium transition-colors disabled:opacity-50 ${inv.preferred_lang === l ? 'bg-indigo-600 text-white' : 'bg-black/20 text-white/50 hover:text-white/80'}`}
                >
                  {l === 'de' ? '🇩🇪 DE' : '🇬🇧 EN'}
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Showcase toggle */}
        <div className="flex items-center justify-between mt-4 pt-4 border-t border-white/[0.06]">
          <div>
            <div className="text-sm text-white font-medium">Showcase mode</div>
            <div className="text-xs text-white/40 mt-0.5">Hides financials, The Ask, and investor-only slides — for customer demos</div>
          </div>
          <button
            onClick={async () => {
              setBusy(true)
              const res = await fetch(`/api/admin/investors/${id}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ is_showcase: !inv.is_showcase }),
              })
              setBusy(false)
              if (res.ok) { flashToast(inv.is_showcase ? 'Switched to investor mode' : 'Switched to showcase mode'); load() }
              else { flashToast('Update failed') }
            }}
            disabled={busy}
            className={`relative w-11 h-6 rounded-full transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black focus:ring-indigo-500 ${inv.is_showcase ? 'bg-indigo-500' : 'bg-white/10'}`}
          >
            <span className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform duration-200 ${inv.is_showcase ? 'translate-x-5' : 'translate-x-0'}`} />
          </button>
        </div>
      </section>

      {/* Audit log for this investor */}
      <section className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
        <h2 className="text-sm font-semibold text-white mb-4">Activity</h2>
        <AuditLogTable rows={data.audit} showActor />
      </section>

      {toast && (
        <div className="fixed bottom-6 right-6 bg-indigo-500/20 border border-indigo-500/40 text-indigo-200 text-sm px-4 py-2 rounded-lg backdrop-blur-sm">
          {toast}
        </div>
      )}
    </div>
  )
}
