"use client";

/**
 * Suggested Keywords inline section
 * ──────────────────────────────────
 * Quick-add card shown on the Rank Tracker page when the brand has fewer
 * than ~5 tracked keywords. Pulls from /api/rank-tracking/suggestions
 * (the same endpoint the AddKeywordsModal uses) but renders a flat
 * checkbox list grouped into two pragmatic buckets:
 *   • Quick Wins      — striking distance + page 1 (positions 1-15)
 *   • High Traffic    — non-branded queries with the most impressions
 *
 * Bulk-add reuses POST /api/rank-tracking/keywords so the user can track
 * 5+ keywords in two clicks instead of typing them in one by one.
 */

import { useEffect, useState } from "react";
import { Loader2, Plus, Sparkles, Flame, Target, Link2 } from "lucide-react";

interface Suggestion {
  keyword: string;
  source: string;
  impressions: number | null;
  currentPosition: number | null;
  priority: string;
  reason: string;
  targetUrl?: string;
  suggestedTags?: string[];
}

interface ApiResponse {
  branded: Suggestion[];
  nonBranded: Suggestion[];
  localVariations: Suggestion[];
  spanishKeywords: Suggestion[];
  strikingDistance: Suggestion[];
  total: number;
}

interface Props {
  brandId: string;
  /** Called after a successful bulk-add so the parent can reload. */
  onAdded: () => void;
  /** Set of keywords already tracked (lowercase) — filtered out of the list. */
  alreadyTracked: Set<string>;
}

export default function SuggestedKeywordsSection({ brandId, onAdded, alreadyTracked }: Props) {
  const [loading, setLoading] = useState(true);
  const [suggestions, setSuggestions] = useState<ApiResponse | null>(null);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [adding, setAdding] = useState(false);
  const [hasGsc, setHasGsc] = useState(true);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    // includeAi=false keeps this card snappy — it's a quick-add helper,
    // not the full suggestion experience. The AddKeywordsModal still
    // offers the AI-enriched list when the user wants more.
    fetch(`/api/rank-tracking/suggestions?brandId=${brandId}&includeAi=false&limit=40`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data: ApiResponse | null) => {
        if (cancelled) return;
        if (!data || data.total === 0) {
          setHasGsc(false);
          setSuggestions(null);
        } else {
          setSuggestions(data);
        }
      })
      .catch(() => { if (!cancelled) setHasGsc(false); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [brandId]);

  // Build the two buckets we surface inline. Striking Distance + the
  // close-to-page-1 entries from nonBranded become "Quick Wins". The
  // rest of nonBranded sorted by impressions becomes "High Traffic".
  const quickWins: Suggestion[] = [];
  const highTraffic: Suggestion[] = [];
  if (suggestions) {
    const seen = new Set<string>();
    const isAvailable = (s: Suggestion) => {
      const key = s.keyword.toLowerCase();
      if (seen.has(key) || alreadyTracked.has(key)) return false;
      seen.add(key);
      return true;
    };
    for (const s of suggestions.strikingDistance) {
      if (quickWins.length >= 5) break;
      if (isAvailable(s)) quickWins.push(s);
    }
    for (const s of suggestions.nonBranded) {
      if (s.currentPosition != null && s.currentPosition <= 15 && quickWins.length < 5) {
        if (isAvailable(s)) quickWins.push(s);
      }
    }
    const byImpressions = [...suggestions.nonBranded]
      .filter((s) => (s.impressions ?? 0) > 0)
      .sort((a, b) => (b.impressions ?? 0) - (a.impressions ?? 0));
    for (const s of byImpressions) {
      if (highTraffic.length >= 5) break;
      if (isAvailable(s)) highTraffic.push(s);
    }
  }

  const totalAvailable = quickWins.length + highTraffic.length;

  function toggle(k: string) {
    setSelected((s) => {
      const next = new Set(s);
      next.has(k) ? next.delete(k) : next.add(k);
      return next;
    });
  }

  async function trackSelected() {
    if (selected.size === 0) return;
    setAdding(true);
    try {
      const all = [...quickWins, ...highTraffic];
      const payload = all
        .filter((s) => selected.has(s.keyword))
        .map((s) => ({
          keyword: s.keyword,
          location: "United States",
          device: "desktop",
          targetUrl: s.targetUrl,
          tags: s.suggestedTags ?? [],
        }));
      const res = await fetch("/api/rank-tracking/keywords", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, keywords: payload }),
      });
      if (res.ok) {
        setSelected(new Set());
        onAdded();
      }
    } finally {
      setAdding(false);
    }
  }

  // ── Empty / disconnected states ──────────────────────────────────
  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-6 flex items-center justify-center text-slate-400 text-sm">
        <Loader2 className="w-4 h-4 animate-spin mr-2" /> Loading suggestions…
      </div>
    );
  }
  if (!hasGsc || !suggestions) {
    return (
      <div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl border border-blue-200 p-6">
        <div className="flex items-start gap-3">
          <Link2 className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <h3 className="font-bold text-slate-900 text-sm">Connect Google Search Console for AI keyword suggestions</h3>
            <p className="text-xs text-slate-600 mt-1">
              Once GSC is connected, this card will surface striking-distance and high-traffic
              keywords your site already ranks for — one click to start tracking them.
            </p>
          </div>
        </div>
      </div>
    );
  }
  if (totalAvailable === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-6 text-center text-sm text-slate-500">
        <Sparkles className="w-5 h-5 text-slate-300 mx-auto mb-2" />
        Every keyword GSC is reporting on is already being tracked. Use the
        <strong className="font-semibold"> Add Keywords </strong>
        button to discover more from AI.
      </div>
    );
  }

  // ── Main render ──────────────────────────────────────────────────
  return (
    <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 justify-between">
        <div className="flex items-center gap-2">
          <Sparkles className="w-4 h-4 text-violet-500" />
          <h2 className="font-bold text-slate-800 text-sm">Suggested Keywords to Track</h2>
        </div>
        <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">
          From your GSC data
        </span>
      </div>

      <div className="grid md:grid-cols-2 gap-px bg-slate-100">
        <SuggestionGroup
          title="Quick Wins"
          subtitle="close to page 1"
          icon={Target}
          accent="text-amber-600"
          items={quickWins}
          selected={selected}
          onToggle={toggle}
        />
        <SuggestionGroup
          title="High Traffic"
          subtitle="most impressions"
          icon={Flame}
          accent="text-orange-600"
          items={highTraffic}
          selected={selected}
          onToggle={toggle}
        />
      </div>

      <div className="px-5 py-3 border-t border-slate-100 flex items-center justify-between bg-slate-50/60">
        <p className="text-xs text-slate-500">
          {selected.size > 0
            ? `${selected.size} keyword${selected.size === 1 ? "" : "s"} selected`
            : "Select keywords to track them in a single click"}
        </p>
        <button
          onClick={trackSelected}
          disabled={selected.size === 0 || adding}
          className="flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {adding ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Plus className="w-3.5 h-3.5" />}
          Track Selected
        </button>
      </div>
    </div>
  );
}

// ─── Group ─────────────────────────────────────────────────────────────────────

function SuggestionGroup({
  title, subtitle, icon: Icon, accent, items, selected, onToggle,
}: {
  title: string;
  subtitle: string;
  icon: typeof Target;
  accent: string;
  items: Suggestion[];
  selected: Set<string>;
  onToggle: (keyword: string) => void;
}) {
  return (
    <div className="bg-white p-4">
      <div className="flex items-center gap-2 mb-2">
        <Icon className={`w-3.5 h-3.5 ${accent}`} />
        <h3 className="text-xs font-bold text-slate-800">{title}</h3>
        <span className="text-[10px] text-slate-400">{subtitle}</span>
      </div>
      {items.length === 0 ? (
        <p className="text-[11px] text-slate-400 italic py-2">No matching opportunities right now.</p>
      ) : (
        <ul className="space-y-1">
          {items.map((s) => {
            const isChecked = selected.has(s.keyword);
            return (
              <li key={s.keyword}>
                <label className={`flex items-center gap-2 px-2 py-1.5 rounded-lg cursor-pointer text-xs ${isChecked ? "bg-brand-50" : "hover:bg-slate-50"}`}>
                  <input
                    type="checkbox"
                    checked={isChecked}
                    onChange={() => onToggle(s.keyword)}
                    className="rounded shrink-0"
                  />
                  <span className="flex-1 truncate font-medium text-slate-800">{s.keyword}</span>
                  {s.currentPosition != null && (
                    <span className="text-[10px] text-slate-500 tabular-nums">
                      Pos {Math.round(s.currentPosition * 10) / 10}
                    </span>
                  )}
                  {s.impressions != null && (
                    <span className="text-[10px] text-slate-500 tabular-nums">
                      {s.impressions.toLocaleString()} imps
                    </span>
                  )}
                </label>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}
