'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Users, UserCheck, Mail, Eye, ArrowRight } from 'lucide-react'
import StatCard from '@/components/pitch-admin/StatCard'
import AuditLogTable from '@/components/pitch-admin/AuditLogTable'

interface DashboardData {
  totals: {
    total_investors: number
    pending_invites: number
    active_7d: number
    slides_viewed_total: number
    active_sessions: number
    active_admins: number
  }
  recent_logins: Array<{
    investor_id: string
    email: string
    name: string | null
    company: string | null
    created_at: string
    ip_address: string | null
  }>
  recent_activity: Array<{
    id: number
    action: string
    created_at: string
    details: Record<string, unknown> | null
    investor_email: string | null
    investor_name: string | null
    target_investor_email: string | null
    admin_email: string | null
    admin_name: string | null
  }>
}

export default function DashboardPage() {
  const [data, setData] = useState<DashboardData | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/admin/dashboard')
      .then((r) => r.json())
      .then(setData)
      .finally(() => setLoading(false))
  }, [])

  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">Failed to load dashboard</div>

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-white">Dashboard</h1>
          <p className="text-sm text-white/50 mt-1">Investor activity overview</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 transition-all"
        >
          + Invite Investor
        </Link>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard label="Total Investors" value={data.totals.total_investors} icon={Users} accent="indigo" />
        <StatCard
          label="Active (7d)"
          value={data.totals.active_7d}
          icon={UserCheck}
          accent="green"
          hint={`${data.totals.active_sessions} live sessions`}
        />
        <StatCard
          label="Pending Invites"
          value={data.totals.pending_invites}
          icon={Mail}
          accent="amber"
        />
        <StatCard
          label="Slides Viewed"
          value={data.totals.slides_viewed_total}
          icon={Eye}
          accent="indigo"
          hint="all-time"
        />
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <section className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-white">Recent Logins</h2>
            <Link href="/pitch-admin/investors" className="text-xs text-indigo-400 hover:text-indigo-300 flex items-center gap-1">
              All investors <ArrowRight className="w-3 h-3" />
            </Link>
          </div>
          {data.recent_logins.length === 0 ? (
            <div className="text-white/40 text-sm py-8 text-center">No logins yet</div>
          ) : (
            <ul className="space-y-2">
              {data.recent_logins.map((row, i) => (
                <li key={i} className="flex items-center justify-between text-sm py-2 border-b border-white/[0.04] last:border-0">
                  <div className="min-w-0">
                    <Link href={`/pitch-admin/investors/${row.investor_id}`} className="text-white/90 hover:text-indigo-300 truncate block">
                      {row.name || row.email}
                    </Link>
                    <div className="text-xs text-white/40 truncate">{row.company || row.email}</div>
                  </div>
                  <div className="text-xs text-white/40 whitespace-nowrap ml-3">
                    {new Date(row.created_at).toLocaleString()}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </section>

        <section className="bg-white/[0.04] border border-white/[0.06] rounded-2xl p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-white">Recent Activity</h2>
            <Link href="/pitch-admin/audit" className="text-xs text-indigo-400 hover:text-indigo-300 flex items-center gap-1">
              Full log <ArrowRight className="w-3 h-3" />
            </Link>
          </div>
          <div className="-mx-5">
            <AuditLogTable rows={data.recent_activity.slice(0, 8)} />
          </div>
        </section>
      </div>
    </div>
  )
}
