"use client"

import Link from "next/link"
import { formatDistanceToNow } from "date-fns"
import {
  Zap, BarChart3, Sparkles, Activity, Bot,
  TrendingUp, ShieldAlert, Wrench, ArrowRight,
  CheckCircle, AlertTriangle, Brain,
} from "lucide-react"
import { formatCurrency } from "@/lib/utils"

const riskBadge: Record<string, string> = {
  critical: "text-red-400 bg-red-500/10 ring-red-500/20",
  high:     "text-orange-400 bg-orange-500/10 ring-orange-500/20",
  medium:   "text-amber-400 bg-amber-500/10 ring-amber-500/20",
  low:      "text-emerald-400 bg-emerald-500/10 ring-emerald-500/20",
}

const priorityBadge: Record<string, string> = {
  high:   "text-red-400 bg-red-500/10 ring-red-500/20",
  medium: "text-amber-400 bg-amber-500/10 ring-amber-500/20",
  low:    "text-white/40 bg-white/5 ring-white/10",
}

interface Props {
  recentRecs: any[]
  recentPredictions: any[]
  activityLog: any[]
  stats: {
    totalImpact: number
    approvedRecs: number
    pendingRecs: number
    occupancyRate: number
    totalRevenue: number
    overdueAmount: number
    criticalMaintenance: number
    riskAlerts: number
  }
}

export function AiDashboardClient({ recentRecs, recentPredictions, activityLog, stats }: Props) {
  const hasAlerts = stats.riskAlerts > 0 || stats.criticalMaintenance > 0 || stats.overdueAmount > 0

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-violet-500/10">
          <Brain className="h-5 w-5 text-violet-400" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-white">AI Dashboard</h2>
          <p className="text-sm text-white/40">Your portfolio intelligence at a glance</p>
        </div>
      </div>

      {/* Alert banner */}
      {hasAlerts && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/5 p-4 flex items-start gap-3">
          <AlertTriangle className="h-4 w-4 text-red-400 shrink-0 mt-0.5" />
          <div className="flex-1 space-y-1">
            {stats.riskAlerts > 0 && <p className="text-sm text-red-300">{stats.riskAlerts} active risk alert{stats.riskAlerts > 1 ? "s" : ""} in your portfolio</p>}
            {stats.criticalMaintenance > 0 && <p className="text-sm text-orange-300">{stats.criticalMaintenance} high-priority maintenance request{stats.criticalMaintenance > 1 ? "s" : ""} open</p>}
            {stats.overdueAmount > 0 && <p className="text-sm text-amber-300">{formatCurrency(stats.overdueAmount)} in overdue rent</p>}
          </div>
          <Link href="/predictions" className="shrink-0 text-xs text-red-400 hover:text-red-300 transition flex items-center gap-1">
            View <ArrowRight className="h-3 w-3" />
          </Link>
        </div>
      )}

      {/* Impact stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "AI Impact",       value: formatCurrency(stats.totalImpact), sub: "est. monthly value", color: "text-violet-400", icon: Sparkles },
          { label: "Approved",        value: stats.approvedRecs,                sub: "recommendations",   color: "text-emerald-400", icon: CheckCircle },
          { label: "Pending Review",  value: stats.pendingRecs,                 sub: "recommendations",   color: "text-amber-400",   icon: Zap },
          { label: "Risk Alerts",     value: stats.riskAlerts,                  sub: "active",            color: "text-red-400",     icon: ShieldAlert },
        ].map((s) => {
          const Icon = s.icon
          return (
            <div key={s.label} className="rounded-xl border border-white/[0.06] bg-[#16161f] p-4">
              <div className="flex items-center gap-2 mb-2">
                <Icon className={`h-4 w-4 ${s.color}`} />
                <span className="text-xs text-white/40">{s.label}</span>
              </div>
              <p className={`text-2xl font-bold ${s.color}`}>{s.value}</p>
              <p className="text-xs text-white/25 mt-1">{s.sub}</p>
            </div>
          )
        })}
      </div>

      {/* Quick links */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "AI Assistant",    href: "/ai",              icon: Bot,       color: "text-blue-400",   bg: "bg-blue-500/10",   border: "border-blue-500/20"   },
          { label: "AI Insights",     href: "/recommendations", icon: Zap,       color: "text-violet-400", bg: "bg-violet-500/10", border: "border-violet-500/20" },
          { label: "Predictions",     href: "/predictions",     icon: BarChart3, color: "text-indigo-400", bg: "bg-indigo-500/10", border: "border-indigo-500/20" },
          { label: "Impact Tracking", href: "/impact",          icon: TrendingUp,color: "text-emerald-400",bg: "bg-emerald-500/10",border: "border-emerald-500/20"},
        ].map((item) => {
          const Icon = item.icon
          return (
            <Link
              key={item.href}
              href={item.href}
              className={`rounded-xl border ${item.border} ${item.bg} p-4 flex items-center justify-between group hover:brightness-125 transition`}
            >
              <div className="flex items-center gap-2">
                <Icon className={`h-4 w-4 ${item.color}`} />
                <span className="text-sm font-medium text-white">{item.label}</span>
              </div>
              <ArrowRight className="h-3.5 w-3.5 text-white/20 group-hover:text-white/50 transition" />
            </Link>
          )
        })}
      </div>

      <div className="grid sm:grid-cols-2 gap-4">
        {/* Recent recommendations */}
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="px-5 py-3.5 border-b border-white/[0.06] flex items-center justify-between">
            <p className="text-sm font-semibold text-white">Recent Recommendations</p>
            <Link href="/recommendations" className="text-xs text-indigo-400 hover:text-indigo-300 transition flex items-center gap-1">
              View all <ArrowRight className="h-3 w-3" />
            </Link>
          </div>
          {recentRecs.length === 0 ? (
            <div className="py-10 text-center">
              <p className="text-xs text-white/25">No recommendations yet</p>
              <Link href="/recommendations" className="text-xs text-indigo-400 hover:underline mt-1 block">Generate now</Link>
            </div>
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {recentRecs.map((r) => (
                <div key={r.id} className="px-5 py-3.5 flex items-start gap-3">
                  <Zap className="h-4 w-4 text-violet-400 shrink-0 mt-0.5" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-white truncate">{r.title}</p>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ring-1 ring-inset ${priorityBadge[r.priority] ?? priorityBadge.low}`}>
                        {r.priority}
                      </span>
                      <span className={`text-[10px] font-medium capitalize ${r.status === "approved" ? "text-emerald-400" : r.status === "dismissed" ? "text-white/25" : "text-amber-400"}`}>
                        {r.status}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Recent predictions */}
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="px-5 py-3.5 border-b border-white/[0.06] flex items-center justify-between">
            <p className="text-sm font-semibold text-white">Recent Predictions</p>
            <Link href="/predictions" className="text-xs text-indigo-400 hover:text-indigo-300 transition flex items-center gap-1">
              View all <ArrowRight className="h-3 w-3" />
            </Link>
          </div>
          {recentPredictions.length === 0 ? (
            <div className="py-10 text-center">
              <p className="text-xs text-white/25">No predictions yet</p>
              <Link href="/predictions" className="text-xs text-indigo-400 hover:underline mt-1 block">Run analysis</Link>
            </div>
          ) : (
            <div className="divide-y divide-white/[0.04]">
              {recentPredictions.map((p) => (
                <div key={p.id} className="px-5 py-3.5 flex items-start gap-3">
                  <BarChart3 className="h-4 w-4 text-blue-400 shrink-0 mt-0.5" />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-white truncate">{p.title}</p>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ring-1 ring-inset ${riskBadge[p.risk_level] ?? riskBadge.low}`}>
                        {p.risk_level}
                      </span>
                      <span className="text-xs text-white/30">{p.timeframe}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* AI Activity log */}
      {activityLog.length > 0 && (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] overflow-hidden">
          <div className="px-5 py-3.5 border-b border-white/[0.06] flex items-center justify-between">
            <p className="text-sm font-semibold text-white flex items-center gap-2">
              <Activity className="h-4 w-4 text-violet-400" />
              Recent AI Actions
            </p>
            <Link href="/activity" className="text-xs text-indigo-400 hover:text-indigo-300 transition flex items-center gap-1">
              View all <ArrowRight className="h-3 w-3" />
            </Link>
          </div>
          <div className="divide-y divide-white/[0.04]">
            {activityLog.map((a) => (
              <div key={a.id} className="px-5 py-3 flex items-center gap-3">
                <Zap className="h-3.5 w-3.5 text-violet-400 shrink-0" />
                <p className="flex-1 text-sm text-white/60">{a.title}</p>
                <span className="text-xs text-white/20 shrink-0">
                  {formatDistanceToNow(new Date(a.created_at), { addSuffix: true })}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
