"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { useBrand } from "@/context/brand-context";
import { SourceEmptyState, hasData } from "@/components/source-empty-state";
import {
  Lightbulb, AlertCircle, AlertTriangle, Info, Shield,
  ChevronRight, ExternalLink, Zap, ClipboardPlus, CheckCircle2,
} from "lucide-react";

interface Recommendation {
  id: string;
  source: string;
  severity: string;
  title: string;
  detail: string;
  suggestedFix: string;
  affectedPages: string[];
  affectedCount: number;
  effort: string;
  impact: string;
  category?: string;
  metric?: string;
}

const SOURCE_LABELS: Record<string, string> = {
  technical_audit: "Technical Audit",
  dead_pages: "Dead Pages",
  performance_audit: "Performance",
  ai_visibility: "AI Visibility",
  competitors: "Competitors",
  site_tag: "Site Tag",
};

const SOURCE_HREFS: Record<string, string> = {
  technical_audit: "/technical-audit",
  dead_pages: "/broken-links",
  performance_audit: "/site-performance-audit",
  ai_visibility: "/ai-visibility",
  competitors: "/competitors",
  site_tag: "/site-tag-analytics",
};

const SOURCE_STYLES: Record<string, string> = {
  technical_audit: "bg-slate-50 text-slate-600 border-slate-200",
  dead_pages: "bg-red-50 text-red-600 border-red-200",
  performance_audit: "bg-amber-50 text-amber-600 border-amber-200",
  ai_visibility: "bg-violet-50 text-violet-600 border-violet-200",
  competitors: "bg-blue-50 text-blue-600 border-blue-200",
  site_tag: "bg-emerald-50 text-emerald-600 border-emerald-200",
};

type CategoryFilter = "all" | "errors" | "ux" | "conversion" | "technical" | "performance" | "competitive" | "content";
const CATEGORY_FILTERS: Array<{ key: CategoryFilter; label: string }> = [
  { key: "all", label: "All" },
  { key: "errors", label: "Errors" },
  { key: "ux", label: "UX" },
  { key: "conversion", label: "Conversion" },
  { key: "technical", label: "Technical" },
  { key: "performance", label: "Performance" },
  { key: "competitive", label: "Competitive" },
  { key: "content", label: "Content" },
];

const SEVERITY_CFG: Record<string, { icon: typeof AlertCircle; color: string; bg: string; border: string }> = {
  critical: { icon: AlertCircle,   color: "text-red-700",    bg: "bg-red-50",    border: "border-red-200" },
  high:     { icon: AlertTriangle, color: "text-orange-700", bg: "bg-orange-50", border: "border-orange-200" },
  medium:   { icon: AlertTriangle, color: "text-amber-700",  bg: "bg-amber-50",  border: "border-amber-200" },
  low:      { icon: Info,          color: "text-blue-700",   bg: "bg-blue-50",   border: "border-blue-200" },
};

const IMPACT_CFG: Record<string, string> = {
  high:   "text-green-700 bg-green-50 border-green-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  low:    "text-slate-500 bg-slate-50 border-slate-200",
};

const EFFORT_CFG: Record<string, string> = {
  low:    "text-green-600 bg-green-50 border-green-200",
  medium: "text-amber-600 bg-amber-50 border-amber-200",
  high:   "text-red-600 bg-red-50 border-red-200",
};

export default function RecommendationsPage() {
  const { brand, getSourceStatus } = useBrand();
  const sourceStatus = getSourceStatus("recommendations");

  const [recs, setRecs] = useState<Recommendation[]>([]);
  const [counts, setCounts] = useState<{ total: number; critical: number; high: number; medium: number; low: number }>({ total: 0, critical: 0, high: 0, medium: 0, low: 0 });
  const [loading, setLoading] = useState(true);
  const [filterSeverity, setFilterSeverity] = useState<string | null>(null);
  const [filterCategory, setFilterCategory] = useState<CategoryFilter>("all");
  const [taskFeedback, setTaskFeedback] = useState<Record<string, string>>({});

  async function createTaskFromRec(rec: Recommendation) {
    if (taskFeedback[rec.id]) return;
    setTaskFeedback(prev => ({ ...prev, [rec.id]: "Creating..." }));
    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId: brand.id,
          title: `Fix: ${rec.title}`,
          description: rec.detail,
          category: rec.source === "performance_audit" ? "technical" : "seo",
          priority: rec.severity,
          effort: rec.effort,
          pageUrl: rec.affectedPages[0] || null,
          recommendation: rec.suggestedFix,
          source: rec.source,
          sourceId: rec.id,
        }),
      });
      if (res.ok) {
        const data = await res.json();
        setTaskFeedback(prev => ({ ...prev, [rec.id]: data._duplicate ? "Already exists" : "Created!" }));
      } else {
        setTaskFeedback(prev => ({ ...prev, [rec.id]: "Failed" }));
        setTimeout(() => setTaskFeedback(prev => { const n = { ...prev }; delete n[rec.id]; return n; }), 2500);
      }
    } catch {
      setTaskFeedback(prev => ({ ...prev, [rec.id]: "Failed" }));
      setTimeout(() => setTaskFeedback(prev => { const n = { ...prev }; delete n[rec.id]; return n; }), 2500);
    }
  }

  const loadRecs = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/audit-recommendations?brandId=${brand.id}`);
    if (!res.ok) { setLoading(false); return; }
    const data = await res.json();
    setRecs(data.recommendations ?? []);
    setCounts({
      total: data.total ?? 0,
      critical: data.bySeverity?.critical ?? 0,
      high: data.bySeverity?.high ?? 0,
      medium: data.bySeverity?.medium ?? 0,
      low: data.bySeverity?.low ?? 0,
    });
    setLoading(false);
  }, [brand.id]);

  useEffect(() => { loadRecs().catch(() => setLoading(false)); }, [loadRecs]);

  if (!hasData(sourceStatus?.status)) {
    return <SourceEmptyState sourceId="recommendations" title="Recommendations" actionLabel="Run Technical Audit" actionHref="/technical-audit" />;
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-4 border-brand-100 border-t-brand-600 rounded-full animate-spin" />
      </div>
    );
  }

  if (counts.total === 0) {
    return (
      <div className="space-y-6 max-w-6xl">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Recommendations</h1>
          <p className="text-slate-500 text-sm mt-1">Evidence-based recommendations for {brand.domain}</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
          <Shield className="w-12 h-12 text-green-300 mx-auto mb-3" />
          <h2 className="text-lg font-bold text-slate-900 mb-1">No Issues Found</h2>
          <p className="text-sm text-slate-500">All audits are passing. No recommendations at this time.</p>
        </div>
      </div>
    );
  }

  const filtered = recs.filter((r) => {
    if (filterSeverity && r.severity !== filterSeverity) return false;
    if (filterCategory !== "all") {
      // Map sources without explicit category to a default
      const cat = r.category ?? (r.source === "technical_audit" ? "technical" : r.source === "dead_pages" ? "errors" : r.source === "performance_audit" ? "performance" : r.source === "ai_visibility" ? "competitive" : r.source === "competitors" ? "competitive" : "technical");
      if (cat !== filterCategory) return false;
    }
    return true;
  });

  return (
    <div className="space-y-5 max-w-6xl">

      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-slate-900">Recommendations</h1>
        <p className="text-slate-500 text-sm mt-1">
          {counts.total} recommendation{counts.total !== 1 ? "s" : ""} from real audit data for <span className="font-medium text-slate-700">{brand.domain}</span>
        </p>
      </div>

      {/* Severity filter cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
        {([
          { key: "critical", label: "Critical", count: counts.critical, color: "text-red-600", border: "border-red-200", bg: "bg-red-50" },
          { key: "high", label: "High", count: counts.high, color: "text-orange-600", border: "border-orange-200", bg: "bg-orange-50" },
          { key: "medium", label: "Medium", count: counts.medium, color: "text-amber-600", border: "border-amber-200", bg: "bg-amber-50" },
          { key: "low", label: "Low", count: counts.low, color: "text-blue-600", border: "border-blue-200", bg: "bg-blue-50" },
        ] as const).map((s) => (
          <button
            key={s.key}
            onClick={() => setFilterSeverity(filterSeverity === s.key ? null : s.key)}
            className={`rounded-xl border ${filterSeverity === s.key ? "border-slate-900 ring-1 ring-slate-900" : s.border} ${s.bg} px-4 py-3 text-left hover:shadow-sm transition-all`}
          >
            <p className={`text-[10px] font-semibold uppercase tracking-wide ${s.color}`}>{s.label}</p>
            <p className={`text-xl font-bold ${s.color} mt-0.5`}>{s.count}</p>
          </button>
        ))}
      </div>

      {/* Category filter */}
      <div className="flex items-center gap-1 overflow-x-auto">
        {CATEGORY_FILTERS.map((f) => {
          const catCount = f.key === "all" ? recs.length : recs.filter((r) => {
            const cat = r.category ?? (r.source === "technical_audit" ? "technical" : r.source === "dead_pages" ? "errors" : r.source === "performance_audit" ? "performance" : r.source === "ai_visibility" ? "competitive" : r.source === "competitors" ? "competitive" : "technical");
            return cat === f.key;
          }).length;
          if (f.key !== "all" && catCount === 0) return null;
          return (
            <button
              key={f.key}
              onClick={() => setFilterCategory(f.key)}
              className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold whitespace-nowrap transition-colors ${filterCategory === f.key ? "bg-slate-900 text-white" : "bg-white border border-slate-200 text-slate-600 hover:bg-slate-50"}`}
            >
              {f.label} <span className={filterCategory === f.key ? "text-slate-400" : "text-slate-400"}>{catCount}</span>
            </button>
          );
        })}
      </div>

      {/* Recommendation list */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
          <Lightbulb className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">
            {filterSeverity ? `${filterSeverity.charAt(0).toUpperCase() + filterSeverity.slice(1)} Priority` : "All Recommendations"}
          </h2>
          <span className="ml-auto text-xs text-slate-400">{filtered.length} item{filtered.length !== 1 ? "s" : ""}</span>
        </div>
        <div className="divide-y divide-slate-100">
          {filtered.map((rec) => {
            const sev = SEVERITY_CFG[rec.severity] ?? SEVERITY_CFG.medium;
            const SevIcon = sev.icon;
            return (
              <div key={rec.id} className="px-5 py-4 hover:bg-slate-50/50 transition-colors">
                <div className="flex items-start gap-3">
                  <div className={`w-8 h-8 rounded-lg ${sev.bg} ${sev.border} border flex items-center justify-center shrink-0 mt-0.5`}>
                    <SevIcon className={`w-4 h-4 ${sev.color}`} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap mb-1">
                      <p className="text-sm font-semibold text-slate-800">{rec.title}</p>
                      <span className={`text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded border ${sev.bg} ${sev.border} ${sev.color}`}>
                        {rec.severity}
                      </span>
                    </div>
                    <p className="text-xs text-slate-500 leading-relaxed">{rec.detail}</p>
                    {rec.suggestedFix && (
                      <p className="text-xs text-slate-600 mt-1.5 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2">
                        <Zap className="w-3 h-3 text-emerald-600 inline mr-1" />
                        {rec.suggestedFix}
                      </p>
                    )}
                    <div className="flex items-center gap-2 mt-2 flex-wrap">
                      <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded border ${IMPACT_CFG[rec.impact] ?? IMPACT_CFG.medium}`}>Impact: {rec.impact}</span>
                      <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded border ${EFFORT_CFG[rec.effort] ?? EFFORT_CFG.medium}`}>Effort: {rec.effort}</span>
                      <Link href={SOURCE_HREFS[rec.source] ?? "/technical-audit"} className={`text-[9px] font-bold px-1.5 py-0.5 rounded border flex items-center gap-0.5 hover:opacity-80 ${SOURCE_STYLES[rec.source] ?? "bg-slate-50 text-slate-600 border-slate-200"}`}>
                        {SOURCE_LABELS[rec.source] ?? rec.source} <ExternalLink className="w-2.5 h-2.5" />
                      </Link>
                      {rec.metric && (
                        <span className="text-[9px] font-semibold text-slate-500 bg-slate-50 border border-slate-200 rounded px-1.5 py-0.5">{rec.metric}</span>
                      )}
                      {rec.affectedCount > 0 && (
                        <span className="text-[9px] text-slate-400">{rec.affectedCount} page{rec.affectedCount !== 1 ? "s" : ""} affected</span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-1.5 shrink-0">
                    {!taskFeedback[rec.id] ? (
                      <button
                        onClick={() => createTaskFromRec(rec)}
                        className="flex items-center gap-1 px-2 py-1 rounded-lg border border-brand-200 bg-brand-50 text-[10px] font-semibold text-brand-700 hover:bg-brand-100 transition-colors"
                      >
                        <ClipboardPlus className="w-3 h-3" /> Task
                      </button>
                    ) : (
                      <span className={`flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-semibold ${
                        taskFeedback[rec.id] === "Created!" ? "bg-green-50 border border-green-200 text-green-700"
                        : taskFeedback[rec.id] === "Already exists" ? "bg-amber-50 border border-amber-200 text-amber-700"
                        : taskFeedback[rec.id] === "Creating..." ? "bg-slate-50 border border-slate-200 text-slate-400"
                        : "bg-red-50 border border-red-200 text-red-700"
                      }`}>
                        {taskFeedback[rec.id] === "Created!" && <CheckCircle2 className="w-3 h-3" />}
                        {taskFeedback[rec.id]}
                      </span>
                    )}
                    <Link href={SOURCE_HREFS[rec.source] ?? "/technical-audit"} className="shrink-0">
                      <ChevronRight className="w-4 h-4 text-slate-300" />
                    </Link>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
