"use client"

import { useState } from "react"
import { toast } from "sonner"
import {
  Zap, TrendingUp, AlertTriangle, Wrench, FileText,
  DollarSign, RefreshCw, CheckCircle, XCircle, Loader2,
  Lightbulb, ShieldAlert,
} from "lucide-react"

const typeConfig: Record<string, { icon: React.ElementType; color: string; bg: string; border: string }> = {
  rent_increase:    { icon: TrendingUp,  color: "text-emerald-400", bg: "bg-emerald-500/10", border: "border-emerald-500/20" },
  vacancy_alert:    { icon: AlertTriangle, color: "text-amber-400", bg: "bg-amber-500/10",   border: "border-amber-500/20"   },
  maintenance_urgent: { icon: Wrench,    color: "text-red-400",     bg: "bg-red-500/10",     border: "border-red-500/20"     },
  lease_renewal:    { icon: FileText,    color: "text-blue-400",    bg: "bg-blue-500/10",    border: "border-blue-500/20"    },
  expense_alert:    { icon: DollarSign,  color: "text-orange-400",  bg: "bg-orange-500/10",  border: "border-orange-500/20"  },
  cash_flow:        { icon: TrendingUp,  color: "text-indigo-400",  bg: "bg-indigo-500/10",  border: "border-indigo-500/20"  },
  risk_alert:       { icon: ShieldAlert, color: "text-red-400",     bg: "bg-red-500/10",     border: "border-red-500/20"     },
  opportunity:      { icon: Lightbulb,   color: "text-violet-400",  bg: "bg-violet-500/10",  border: "border-violet-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",
}

export function RecommendationsClient({ recommendations: initial }: { recommendations: any[] }) {
  const [recs, setRecs] = useState(initial)
  const [generating, setGenerating] = useState(false)
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const [filter, setFilter] = useState<"pending" | "approved" | "dismissed">("pending")

  const filtered = recs.filter((r) => r.status === filter)
  const pendingCount = recs.filter((r) => r.status === "pending").length

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

  async function updateStatus(id: string, status: "approved" | "dismissed") {
    setActionLoading(id + status)
    try {
      const res = await fetch(`/api/ai/recommendations/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      })
      const data = await res.json()
      if (!res.ok) { toast.error(data.error ?? "Failed to update"); return }
      setRecs((prev) => prev.map((r) => r.id === id ? data : r))
      toast.success(status === "approved" ? "Recommendation approved!" : "Dismissed")
    } catch {
      toast.error("Network error — please try again")
    } finally {
      setActionLoading(null)
    }
  }

  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">
            <Zap className="h-5 w-5 text-violet-400" />
            AI Recommendations
          </h2>
          <p className="text-sm text-white/40 mt-0.5">
            Smart suggestions based on your portfolio data
            {pendingCount > 0 && <span className="ml-2 text-violet-400">{pendingCount} pending</span>}
          </p>
        </div>
        <button
          onClick={generate}
          disabled={generating}
          className="flex items-center gap-2 rounded-xl bg-violet-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-violet-500 disabled:opacity-50 transition"
        >
          {generating ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
          {generating ? "Analyzing…" : "Generate New"}
        </button>
      </div>

      {/* Filter tabs */}
      <div className="flex gap-1 rounded-xl border border-white/[0.06] bg-[#16161f] p-1 w-fit">
        {(["pending", "approved", "dismissed"] as const).map((s) => (
          <button
            key={s}
            onClick={() => setFilter(s)}
            className={`rounded-lg px-4 py-1.5 text-xs font-medium capitalize transition ${
              filter === s ? "bg-white/10 text-white" : "text-white/40 hover:text-white"
            }`}
          >
            {s} ({recs.filter((r) => r.status === s).length})
          </button>
        ))}
      </div>

      {/* List */}
      {filtered.length === 0 ? (
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] py-16 text-center">
          <Zap className="h-8 w-8 text-white/10 mx-auto mb-3" />
          <p className="text-sm text-white/30">
            {filter === "pending" ? "No pending recommendations" : `No ${filter} recommendations`}
          </p>
          {filter === "pending" && (
            <p className="text-xs text-white/20 mt-1">Click "Generate New" to analyze your portfolio</p>
          )}
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map((rec) => {
            const cfg = typeConfig[rec.type] ?? typeConfig.opportunity
            const Icon = cfg.icon
            return (
              <div key={rec.id} className={`rounded-xl border ${cfg.border} bg-[#16161f] p-5`}>
                <div className="flex items-start gap-4">
                  <div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${cfg.bg}`}>
                    <Icon className={`h-5 w-5 ${cfg.color}`} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <p className="text-sm font-semibold text-white">{rec.title}</p>
                      <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ring-1 ring-inset ${priorityBadge[rec.priority] ?? priorityBadge.low}`}>
                        {rec.priority}
                      </span>
                    </div>
                    <p className="text-sm text-white/50 mt-1.5 leading-relaxed">{rec.description}</p>
                    {rec.impact && (
                      <p className={`text-xs font-medium mt-2 ${cfg.color}`}>↗ {rec.impact}</p>
                    )}
                  </div>
                </div>

                {rec.status === "pending" && (
                  <div className="flex items-center gap-2 mt-4 pt-4 border-t border-white/[0.06]">
                    <button
                      onClick={() => updateStatus(rec.id, "approved")}
                      disabled={!!actionLoading}
                      className="flex items-center gap-1.5 rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-500 disabled:opacity-50 transition"
                    >
                      {actionLoading === rec.id + "approved"
                        ? <Loader2 className="h-3 w-3 animate-spin" />
                        : <CheckCircle className="h-3 w-3" />}
                      {rec.action_label ?? "Apply"}
                    </button>
                    <button
                      onClick={() => updateStatus(rec.id, "dismissed")}
                      disabled={!!actionLoading}
                      className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-1.5 text-xs text-white/40 hover:text-white disabled:opacity-50 transition"
                    >
                      {actionLoading === rec.id + "dismissed"
                        ? <Loader2 className="h-3 w-3 animate-spin" />
                        : <XCircle className="h-3 w-3" />}
                      Dismiss
                    </button>
                  </div>
                )}

                {rec.status === "approved" && (
                  <div className="flex items-center gap-1.5 mt-4 pt-4 border-t border-white/[0.06]">
                    <CheckCircle className="h-3.5 w-3.5 text-emerald-400" />
                    <span className="text-xs text-emerald-400">Approved</span>
                  </div>
                )}

                {rec.status === "dismissed" && (
                  <div className="flex items-center gap-1.5 mt-4 pt-4 border-t border-white/[0.06]">
                    <XCircle className="h-3.5 w-3.5 text-white/20" />
                    <span className="text-xs text-white/30">Dismissed</span>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      )}
    </div>
  )
}
