'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Search, Mail, Ban, Eye, RefreshCw, Link2 } from 'lucide-react'

interface Investor {
  id: string
  email: string
  name: string | null
  company: string | null
  status: string
  last_login_at: string | null
  login_count: number
  created_at: string
  slides_viewed: number
  last_activity: string | null
  assigned_version_id: string | null
  version_name: string | null
  first_activity_at: string | null
  data_masked_at: 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 InvestorsPage() {
  const [investors, setInvestors] = useState<Investor[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [busy, setBusy] = useState<string | null>(null)
  const [toast, setToast] = useState<string | null>(null)

  async function load() {
    setLoading(true)
    const res = await fetch('/api/admin/investors')
    if (res.ok) {
      const data = await res.json()
      setInvestors(data.investors)
    }
    setLoading(false)
  }

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

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

  async function generateLink(id: string) {
    setBusy(id)
    const res = await fetch(`/api/admin/investors/${id}/generate-link`, { method: 'POST' })
    setBusy(null)
    if (res.ok) {
      const data = await res.json()
      const link = data.short_url || data.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(id: string) {
    setBusy(id)
    const res = await fetch(`/api/admin/investors/${id}/resend`, { method: 'POST' })
    setBusy(null)
    if (res.ok) flashToast('Magic link resent')
    else {
      const err = await res.json().catch(() => ({}))
      flashToast(err.error || 'Resend failed')
    }
  }

  async function revoke(id: string, email: string) {
    if (!confirm(`Revoke access for ${email}? This signs them out and prevents future logins.`)) return
    setBusy(id)
    const res = await fetch('/api/admin/revoke', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ investor_id: id }),
    })
    setBusy(null)
    if (res.ok) {
      flashToast('Access revoked')
      load()
    } else {
      flashToast('Revoke failed')
    }
  }

  const filtered = investors.filter((i) => {
    if (statusFilter !== 'all' && i.status !== statusFilter) return false
    if (search) {
      const q = search.toLowerCase()
      return (
        i.email.toLowerCase().includes(q) ||
        (i.name || '').toLowerCase().includes(q) ||
        (i.company || '').toLowerCase().includes(q)
      )
    }
    return true
  })

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-white">Investors</h1>
          <p className="text-sm text-white/50 mt-1">{investors.length} total · {filtered.length} shown</p>
        </div>
        <Link
          href="/pitch-admin/investors/new"
          className="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-4 py-2 rounded-lg shadow-lg shadow-indigo-500/20"
        >
          + Invite Investor
        </Link>
      </div>

      <div className="flex items-center gap-3 flex-wrap">
        <div className="relative flex-1 min-w-[240px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search name, email, or company"
            className="w-full bg-white/[0.04] border border-white/[0.08] rounded-lg pl-10 pr-3 py-2 text-sm text-white placeholder:text-white/30 focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="bg-white/[0.04] border border-white/[0.08] rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
        >
          <option value="all">All statuses</option>
          <option value="invited">Invited</option>
          <option value="active">Active</option>
          <option value="revoked">Revoked</option>
        </select>
      </div>

      {loading ? (
        <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>
      ) : (
        <div className="bg-white/[0.04] border border-white/[0.06] rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-white/40 border-b border-white/[0.06]">
                <th className="py-3 px-4 font-medium">Investor</th>
                <th className="py-3 px-4 font-medium">Status</th>
                <th className="py-3 px-4 font-medium text-right">Logins</th>
                <th className="py-3 px-4 font-medium text-right">Slides</th>
                <th className="py-3 px-4 font-medium">Version</th>
                <th className="py-3 px-4 font-medium">Last login</th>
                <th className="py-3 px-4 font-medium text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-white/40">No investors</td>
                </tr>
              )}
              {filtered.map((inv) => (
                <tr key={inv.id} className="border-b border-white/[0.04] hover:bg-white/[0.02]">
                  <td className="py-3 px-4">
                    <Link href={`/pitch-admin/investors/${inv.id}`} className="block min-w-0 hover:text-indigo-300">
                      <div className="text-white/90 font-medium truncate">
                        {inv.data_masked_at ? <span className="text-zinc-500 italic">[data protected]</span> : (inv.name || inv.email)}
                      </div>
                      <div className="text-xs text-white/40 truncate">
                        {inv.data_masked_at
                          ? `Anonymized ${new Date(inv.data_masked_at).toLocaleDateString()}`
                          : `${inv.company ? `${inv.company} · ` : ''}${inv.email}`}
                      </div>
                    </Link>
                  </td>
                  <td className="py-3 px-4">
                    <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>
                  </td>
                  <td className="py-3 px-4 text-right text-white/70 font-mono">{inv.login_count}</td>
                  <td className="py-3 px-4 text-right text-white/70 font-mono">{inv.slides_viewed}</td>
                  <td className="py-3 px-4">
                    {inv.version_name ? (
                      <span className="text-[10px] px-2 py-0.5 rounded bg-purple-500/15 text-purple-300 border border-purple-500/30">{inv.version_name}</span>
                    ) : (
                      <span className="text-xs text-white/30">Default</span>
                    )}
                  </td>
                  <td className="py-3 px-4 text-white/50 text-xs whitespace-nowrap">
                    {inv.last_login_at ? new Date(inv.last_login_at).toLocaleDateString() : '—'}
                  </td>
                  <td className="py-3 px-4">
                    <div className="flex items-center justify-end gap-1">
                      <Link
                        href={`/pitch-admin/investors/${inv.id}`}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-white/[0.06] hover:text-white"
                        title="View"
                      >
                        <Eye className="w-4 h-4" />
                      </Link>
                      <button
                        onClick={() => generateLink(inv.id)}
                        disabled={busy === inv.id || inv.status === 'revoked' || !!inv.data_masked_at}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-emerald-500/15 hover:text-emerald-300 disabled:opacity-30 disabled:cursor-not-allowed"
                        title="Generate & copy magic link (no email)"
                      >
                        {busy === inv.id ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Link2 className="w-4 h-4" />}
                      </button>
                      <button
                        onClick={() => resend(inv.id)}
                        disabled={busy === inv.id || inv.status === 'revoked' || !!inv.data_masked_at}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-indigo-500/15 hover:text-indigo-300 disabled:opacity-30 disabled:cursor-not-allowed"
                        title="Resend magic link via email"
                      >
                        <Mail className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => revoke(inv.id, inv.email)}
                        disabled={busy === inv.id || inv.status === 'revoked'}
                        className="w-8 h-8 rounded-lg flex items-center justify-center text-white/50 hover:bg-rose-500/15 hover:text-rose-300 disabled:opacity-30 disabled:cursor-not-allowed"
                        title="Revoke"
                      >
                        <Ban className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {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>
  )
}
