"use client"

import { useState } from "react"
import { toast } from "sonner"
import {
  TrendingUp, TrendingDown, AlertTriangle, ShieldAlert,
  Wrench, Home, Zap, RefreshCw, Loader2, BarChart3,
  ArrowUpRight, ArrowDownRight,
} from "lucide-react"
import { formatCurrency } from "@/lib/utils"

const typeConfig: Record<string, { icon: React.ElementType; color: string; bg: string; border: string }> = {
  revenue_forecast:    { icon: TrendingUp,    color: "text-emerald-400", bg: "bg-emerald-500/10", border: "border-emerald-500/20" },
  occupancy_forecast:  { icon: Home,          color: "text-blue-400",    bg: "bg-blue-500/10",    border: "border-blue-500/20"    },
  cash_flow_risk:      { icon: TrendingDown,  color: "text-red-400",     bg: "bg-red-500/10",     border: "border-red-500/20"     },
  tenant_risk:         { icon: AlertTriangle, color: "text-amber-400",   bg: "bg-amber-500/10",   border: "border-amber-500/20"   },
  maintenance_risk:    { icon: Wrench,        color: "text-orange-400",  bg: "bg-orange-500/10",  border: "border-orange-500/20"  },
  vacancy_risk:        { icon: ShieldAlert,   color: "text-red-400",     bg: "bg-red-500/10",     border: "border-red-500/20"     },
  growth_opportunity:  { icon: Zap,           color: "text-violet-400",  bg: "bg-violet-500/10",  border: "border-violet-500/20"  },
}

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 confidenceBadge: Record<string, string> = {
  high:   "text-emerald-400",
  medium: "text-amber-400",
  low:    "text-white/30",
}

export function PredictionsClient({ predictions: initial }: { predictions: any[] }) {
  const [predictions, setPredictions] = useState(initial)
  const [generating, setGenerating] = useState(false)
  const [filter, setFilter] = useState("")

  const riskItems = predictions.filter((p) => ["critical", "high"].includes(p.risk_level))
  const filtered = filter ? predictions.filter((p) => p.type === filter) : predictions

  async function generate() {
    setGenerating(true)
    try {
      const res = await fetch("/api/ai/predictions", { method: "POST" })
      const data = await res.json()
      if (!res.ok) { toast.error(data.error ?? "Failed to generate"); return }
      setPredictions(data)
      toast.success(`${data.length} predictions generated`)
      setFilter("")
    } catch {
      toast.error("Network error — please try again")
    } finally {
      setGenerating(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-end justify-between">
        <div>
          <h2 className="text-lg font-semibold text-white flex items-center gap-2">
            <BarChart3 className="h-5 w-5 text-blue-400" />
            Predictive Analytics
          </h2>
          <p className="text-sm text-white/40 mt-0.5">
            AI-powered forecasts and risk alerts based on your portfolio trends
            {riskItems.length > 0 && (
              <span className="ml-2 text-red-400">{riskItems.length} risk alert{riskItems.length > 1 ? "s" : ""}</span>
            )}
          </p>
        </div>
        <button
          onClick={generate}
          disabled={generating}
          className="flex items-center gap-2 rounded-xl bg-blue-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-blue-500 disabled:opacity-50 transition"
        >
          {generating ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
          {generating ? "Analyzing…" : "Run Analysis"}
        </button>
      </div>

      {/* Risk alerts banner */}
      {riskItems.length > 0 && (
        <div className="rounded-xl border border-red-500/20 bg-red-500/5 p-4">
          <div className="flex items-center gap-2 mb-3">
            <ShieldAlert className="h-4 w-4 text-red-400" />
            <p className="text-sm font-semibold text-red-400">{riskItems.length} Active Risk Alert{riskItems.length > 1 ? "s" : ""}</p>
          </div>
          <div className="space-y-1.5">
            {riskItems.map((r) => (
              <div key={r.id} className="flex items-center gap-2">
                <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ring-1 ring-inset ${riskBadge[r.risk_level]}`}>
                  {r.risk_level}
                </span>
                <span className="text-sm text-white/70">{r.title}</span>
                <span className="text-xs text-white/30">{r.timeframe}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Filter */}
      {predictions.length > 0 && (
        <div className="flex gap-2 flex-wrap">
          <button
            onClick={() => setFilter("")}
            className={`rounded-full px-3 py-1 text-xs font-medium transition ${!filter ? "bg-indigo-600 text-white" : "border border-white/10 text-white/50 hover:text-white"}`}
          >
            All ({predictions.length})
          </button>
          {["revenue_forecast", "occupancy_forecast", "cash_flow_risk", "vacancy_risk", "growth_opportunity"].map((t) => {
            const count = predictions.filter((p) => p.type === t).length
            if (!count) return null
            return (
              <button
                key={t}
                onClick={() => setFilter(t)}
                className={`rounded-full px-3 py-1 text-xs font-medium capitalize transition ${filter === t ? "bg-indigo-600 text-white" : "border border-white/10 text-white/50 hover:text-white"}`}
              >
                {t.replace(/_/g, " ")} ({count})
              </button>
            )
          })}
        </div>
      )}

      {/* Cards */}
      {filtered.length === 0 ? (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] py-16 text-center">
          <BarChart3 className="h-8 w-8 text-white/10 mx-auto mb-3" />
          <p className="text-sm text-white/30">No predictions yet</p>
          <p className="text-xs text-white/20 mt-1">Click "Run Analysis" to generate AI-powered forecasts</p>
        </div>
      ) : (
        <div className="grid sm:grid-cols-2 gap-3">
          {filtered.map((pred) => {
            const cfg = typeConfig[pred.type] ?? typeConfig.growth_opportunity
            const Icon = cfg.icon
            const changePercent = pred.data?.change_percent ?? 0
            const isPositive = changePercent >= 0
            const isRisk = ["cash_flow_risk", "tenant_risk", "maintenance_risk", "vacancy_risk"].includes(pred.type)

            return (
              <div key={pred.id} className={`rounded-xl border ${cfg.border} bg-[#16161f] p-5`}>
                <div className="flex items-start justify-between gap-3 mb-3">
                  <div className="flex items-center gap-3">
                    <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${cfg.bg}`}>
                      <Icon className={`h-4 w-4 ${cfg.color}`} />
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-white">{pred.title}</p>
                      <p className="text-xs text-white/30">{pred.timeframe}</p>
                    </div>
                  </div>
                  <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ring-1 ring-inset shrink-0 ${riskBadge[pred.risk_level] ?? riskBadge.low}`}>
                    {pred.risk_level}
                  </span>
                </div>

                <p className="text-sm text-white/50 leading-relaxed mb-3">{pred.prediction}</p>

                {pred.data?.metric && (
                  <div className="rounded-lg bg-white/[0.03] border border-white/[0.06] p-3 flex items-center justify-between">
                    <div>
                      <p className="text-xs text-white/30">{pred.data.metric}</p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-sm text-white/50">
                          {typeof pred.data.current_value === "number" && pred.data.metric?.toLowerCase().includes("revenue")
                            ? formatCurrency(pred.data.current_value)
                            : `${pred.data.current_value}${pred.data.metric?.includes("%") || pred.data.metric?.toLowerCase().includes("rate") ? "%" : ""}`}
                        </span>
                        <span className="text-white/20">→</span>
                        <span className="text-sm font-semibold text-white">
                          {typeof pred.data.predicted_value === "number" && pred.data.metric?.toLowerCase().includes("revenue")
                            ? formatCurrency(pred.data.predicted_value)
                            : `${pred.data.predicted_value}${pred.data.metric?.includes("%") || pred.data.metric?.toLowerCase().includes("rate") ? "%" : ""}`}
                        </span>
                      </div>
                    </div>
                    {changePercent !== 0 && (
                      <div className={`flex items-center gap-1 text-sm font-semibold ${
                        isRisk
                          ? (isPositive ? "text-red-400" : "text-emerald-400")
                          : (isPositive ? "text-emerald-400" : "text-red-400")
                      }`}>
                        {isPositive
                          ? <ArrowUpRight className="h-4 w-4" />
                          : <ArrowDownRight className="h-4 w-4" />}
                        {Math.abs(changePercent)}%
                      </div>
                    )}
                  </div>
                )}

                <div className="flex items-center gap-1 mt-3">
                  <span className="text-xs text-white/25">Confidence:</span>
                  <span className={`text-xs font-medium capitalize ${confidenceBadge[pred.confidence] ?? confidenceBadge.medium}`}>
                    {pred.confidence}
                  </span>
                </div>
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
