"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Lightbulb, AlertTriangle, CheckCircle, X, Play,
  Loader2, ChevronDown, ChevronUp, Filter,
} from "lucide-react";

interface Recommendation {
  id: string;
  type: string;
  priority: string;
  status: string;
  title: string;
  insight: string;
  action: string;
  impact: string | null;
  relatedPages: string[];
  relatedKeywords: string[];
  createdAt: string;
}

interface Counts {
  total: number;
  critical: number;
  pending: number;
}

const TYPE_LABELS: Record<string, string> = {
  format_replication: "Format Replication",
  citation_gap: "Citation Gap",
  competitive_alert: "Competitive Alert",
  conversion_optimization: "Conversion Optimization",
  content_expansion: "Content Expansion",
  schema_fix: "Schema Fix",
  query_expansion: "Query Expansion",
  content_brief_trigger: "Content Brief",
};

const PRIORITY_CONFIG: Record<string, { color: string; bg: string; label: string }> = {
  critical: { color: "text-red-700", bg: "bg-red-50 border-red-200", label: "Critical" },
  high: { color: "text-orange-700", bg: "bg-orange-50 border-orange-200", label: "High" },
  medium: { color: "text-yellow-700", bg: "bg-yellow-50 border-yellow-200", label: "Medium" },
  low: { color: "text-slate-600", bg: "bg-slate-50 border-slate-200", label: "Low" },
};

export function AiRecommendationsSection({ brandId }: { brandId: string }) {
  const [recs, setRecs] = useState<Recommendation[]>([]);
  const [counts, setCounts] = useState<Counts>({ total: 0, critical: 0, pending: 0 });
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<Set<string>>(new Set());
  const [filter, setFilter] = useState<string>("all");
  const [updating, setUpdating] = useState<string | null>(null);
  // These two were originally declared AFTER the loading-state early
  // return, which violated the Rules of Hooks (hooks must run in the
  // same order every render). When `loading` flipped from true to
  // false, the hook count changed from 4 → 6 and React threw error
  // #310 ("too many re-renders") trying to recover. Declared up-front
  // here so the order is stable across renders.
  const [generating, setGenerating] = useState(false);
  const [genResult, setGenResult] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!brandId) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/ai-recommendations?brandId=${brandId}`);
      if (res.ok) {
        const data = await res.json();
        setRecs(data.recommendations ?? []);
        setCounts(data.counts ?? { total: 0, critical: 0, pending: 0 });
      }
    } catch { /* silent */ }
    setLoading(false);
  }, [brandId]);

  useEffect(() => { load(); }, [load]);

  const updateStatus = async (id: string, status: "in_progress" | "completed" | "dismissed") => {
    setUpdating(id);
    try {
      const res = await fetch("/api/ai-recommendations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "update_status", id, status }),
      });
      if (res.ok) {
        setRecs((prev) => prev.map((r) => r.id === id ? { ...r, status } : r));
        setCounts((prev) => ({
          ...prev,
          total: Math.max(0, prev.total - (status !== "in_progress" ? 1 : 0)),
          pending: Math.max(0, prev.pending - 1),
        }));
      }
    } catch { /* silent */ }
    setUpdating(null);
  };

  const toggle = (id: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-5 h-5 text-brand-500 animate-spin" />
      </div>
    );
  }

  const generateNow = async () => {
    setGenerating(true);
    setGenResult(null);
    try {
      const res = await fetch("/api/ai-recommendations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "generate", brandId }),
      });
      if (res.ok) {
        const data = await res.json();
        setGenResult(`Generated ${data.generated ?? 0} recommendations`);
        load();
      } else {
        setGenResult("Generation failed — try again");
      }
    } catch { setGenResult("Network error"); }
    setGenerating(false);
  };

  if (recs.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-8 text-center space-y-4">
        <Lightbulb className="w-8 h-8 text-amber-200 mx-auto" />
        <div>
          <h3 className="text-sm font-bold text-slate-900 mb-1">No Recommendations Yet</h3>
          <p className="text-xs text-slate-500 max-w-sm mx-auto">
            The AI Strategy Engine analyses your site data to find optimisation opportunities.
            Click below to run the analysis now, or it will run automatically overnight.
          </p>
        </div>
        <button
          onClick={generateNow}
          disabled={generating}
          className="inline-flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-sm font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50"
        >
          {generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
          {generating ? "Analysing…" : "Run Analysis Now"}
        </button>
        {genResult && <p className="text-xs text-emerald-600 font-semibold">{genResult}</p>}
      </div>
    );
  }

  const filtered = filter === "all"
    ? recs.filter((r) => r.status !== "completed" && r.status !== "dismissed")
    : recs.filter((r) => r.type === filter && r.status !== "completed" && r.status !== "dismissed");

  return (
    <div className="space-y-4">
      {/* Header with counts */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Lightbulb className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">AI Recommendations</h3>
          <span className="text-xs font-semibold text-brand-600 bg-brand-50 px-2 py-0.5 rounded-full">
            {counts.total} pending
          </span>
          {counts.critical > 0 && (
            <span className="text-xs font-semibold text-red-600 bg-red-50 px-2 py-0.5 rounded-full">
              {counts.critical} critical
            </span>
          )}
        </div>

        {/* Filter */}
        <div className="flex items-center gap-1">
          <Filter className="w-3 h-3 text-slate-400" />
          <select
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="text-xs border border-slate-200 rounded-lg px-2 py-1 text-slate-600 bg-white"
          >
            <option value="all">All Types</option>
            {Object.entries(TYPE_LABELS).map(([key, label]) => (
              <option key={key} value={key}>{label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Recommendation cards */}
      <div className="space-y-3">
        {filtered.map((rec) => {
          const priority = PRIORITY_CONFIG[rec.priority] ?? PRIORITY_CONFIG.medium;
          const isExpanded = expanded.has(rec.id);
          const isUpdating = updating === rec.id;

          return (
            <div key={rec.id} className={`rounded-xl border ${priority.bg} overflow-hidden`}>
              {/* Header */}
              <button
                onClick={() => toggle(rec.id)}
                className="w-full px-4 py-3 flex items-start gap-3 text-left"
              >
                <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${priority.color} shrink-0 mt-0.5`}>
                  {priority.label}
                </span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-slate-800 leading-snug">{rec.title}</p>
                  <div className="flex items-center gap-2 mt-1">
                    <span className="text-[10px] font-semibold text-slate-400 uppercase tracking-wider">
                      {TYPE_LABELS[rec.type] ?? rec.type}
                    </span>
                    {rec.status === "in_progress" && (
                      <span className="text-[10px] font-bold text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded">In Progress</span>
                    )}
                  </div>
                </div>
                {isExpanded ? <ChevronUp className="w-4 h-4 text-slate-400 shrink-0" /> : <ChevronDown className="w-4 h-4 text-slate-400 shrink-0" />}
              </button>

              {/* Expanded details */}
              {isExpanded && (
                <div className="px-4 pb-4 space-y-3 border-t border-slate-200/50 pt-3">
                  <div>
                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Insight</p>
                    <p className="text-xs text-slate-700 leading-relaxed">{rec.insight}</p>
                  </div>
                  <div>
                    <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Action</p>
                    <p className="text-xs text-slate-700 leading-relaxed">{rec.action}</p>
                  </div>
                  {rec.impact && (
                    <div>
                      <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">Estimated Impact</p>
                      <p className="text-xs text-emerald-700 font-semibold">{rec.impact}</p>
                    </div>
                  )}

                  {/* Related pages / keywords */}
                  {rec.relatedPages && Array.isArray(rec.relatedPages) && rec.relatedPages.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                      {(rec.relatedPages as string[]).slice(0, 3).map((p) => (
                        <span key={p} className="text-[10px] font-mono text-brand-600 bg-brand-50 px-1.5 py-0.5 rounded">{p}</span>
                      ))}
                    </div>
                  )}

                  {/* Actions */}
                  <div className="flex items-center gap-2 pt-1">
                    {rec.status === "pending" && (
                      <button
                        onClick={() => updateStatus(rec.id, "in_progress")}
                        disabled={isUpdating}
                        className="flex items-center gap-1 text-xs font-semibold text-blue-600 bg-blue-50 hover:bg-blue-100 px-3 py-1.5 rounded-lg transition"
                      >
                        {isUpdating ? <Loader2 className="w-3 h-3 animate-spin" /> : <Play className="w-3 h-3" />}
                        Start
                      </button>
                    )}
                    <button
                      onClick={() => updateStatus(rec.id, "completed")}
                      disabled={isUpdating}
                      className="flex items-center gap-1 text-xs font-semibold text-emerald-600 bg-emerald-50 hover:bg-emerald-100 px-3 py-1.5 rounded-lg transition"
                    >
                      {isUpdating ? <Loader2 className="w-3 h-3 animate-spin" /> : <CheckCircle className="w-3 h-3" />}
                      Completed
                    </button>
                    <button
                      onClick={() => updateStatus(rec.id, "dismissed")}
                      disabled={isUpdating}
                      className="flex items-center gap-1 text-xs font-semibold text-slate-500 bg-slate-50 hover:bg-slate-100 px-3 py-1.5 rounded-lg transition"
                    >
                      {isUpdating ? <Loader2 className="w-3 h-3 animate-spin" /> : <X className="w-3 h-3" />}
                      Dismiss
                    </button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export function AiRecommendationsBadge({ brandId }: { brandId: string }) {
  const [counts, setCounts] = useState<Counts | null>(null);

  useEffect(() => {
    if (!brandId) return;
    fetch(`/api/ai-recommendations?brandId=${brandId}&counts=true`)
      .then((res) => res.ok ? res.json() : null)
      .then((data) => { if (data) setCounts(data); })
      .catch(() => null);
  }, [brandId]);

  if (!counts || counts.total === 0) return null;

  return (
    <span className="inline-flex items-center gap-1 text-xs font-semibold">
      <Lightbulb className="w-3 h-3 text-amber-500" />
      <span className="text-slate-600">{counts.total} recommendations</span>
      {counts.critical > 0 && (
        <span className="text-red-600 font-bold">&middot; {counts.critical} critical</span>
      )}
    </span>
  );
}
