'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Mail, Ban, Save } 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
    assigned_version_id: string | null
    version_name: string | null
    version_status: string | null
  }
  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',
}

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 resend() {
    setBusy(true)
    const res = await fetch(`/api/admin/investors/${id}/resend`, { method: 'POST' })
    setBusy(false)
    if (res.ok) {
      flashToast('Magic link resent')
      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.name || inv.email}</h1>
                  <span className={`text-[10px] px-2 py-0.5 rounded-full border uppercase font-semibold ${STATUS_STYLES[inv.status]}`}>
                    {inv.status}
                  </span>
                </div>
                <div className="text-sm text-white/60">{inv.company || '—'}</div>
                <div className="text-xs text-white/40 mt-1">{inv.email}</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>
              </>
            ) : (
              <>
                <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={resend}
                  disabled={busy || 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 Link
                </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">Last login</div>
            <div className="text-sm text-white/80 mt-1">
              {inv.last_login_at ? new Date(inv.last_login_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">
          <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
              ? `Investor sees version "${inv.version_name || ''}"`
              : 'Investor sees default pitch data'}
          </span>
        </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>
  )
}
