"use client";

import { useState } from "react";
import { Save, Crosshair, FileText, Download, X, Loader2 } from "lucide-react";

interface Props {
  count: number;
  brandId: string;
  selectedKeywords: Array<{ keyword: string; searchVolume?: number | null; difficulty?: number | null; intent?: string | null; source?: string }>;
  onSaved: () => void;
  onClear: () => void;
  /** Fires after a successful bulk Track action so the parent can flip the
   *  inline "Tracking ✓" badge on each row without waiting for a refresh. */
  onTracked?: (keywords: string[]) => void;
}

export default function BulkActionBar({ count, brandId, selectedKeywords, onSaved, onClear, onTracked }: Props) {
  const [loading, setLoading] = useState<string | null>(null);

  if (count === 0) return null;

  async function save() {
    setLoading("save");
    try {
      await fetch("/api/keyword-research/save", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, keywords: selectedKeywords.map((k) => ({ keyword: k.keyword, searchVolume: k.searchVolume, difficulty: k.difficulty, intent: k.intent, source: k.source || "ai_estimated" })) }),
      });
      onSaved();
    } catch { /* swallow */ }
    setLoading(null);
  }

  async function track() {
    setLoading("track");
    try {
      const res = await fetch("/api/rank-tracking/keywords", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, keywords: selectedKeywords.map((k) => ({ keyword: k.keyword })) }),
      });
      if (res.ok) onTracked?.(selectedKeywords.map((k) => k.keyword));
      onSaved();
    } catch { /* swallow */ }
    setLoading(null);
  }

  function exportCsv() {
    const header = "Keyword,Volume,Difficulty,Intent\n";
    const rows = selectedKeywords.map((k) => `"${k.keyword}",${k.searchVolume ?? ""},${k.difficulty ?? ""},${k.intent ?? ""}`).join("\n");
    const blob = new Blob([header + rows], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a"); a.href = url; a.download = "keywords.csv";
    document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
  }

  return (
    <div className="fixed bottom-4 left-1/2 -translate-x-1/2 z-40 flex items-center gap-3 bg-slate-900 text-white rounded-xl shadow-2xl px-5 py-3">
      <span className="text-xs font-semibold">{count} selected</span>
      <div className="w-px h-5 bg-slate-700" />
      <button onClick={save} disabled={loading === "save"} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-brand-600 text-xs font-semibold hover:bg-brand-700 disabled:opacity-50">
        {loading === "save" ? <Loader2 className="w-3 h-3 animate-spin" /> : <Save className="w-3 h-3" />} Save
      </button>
      <button onClick={track} disabled={loading === "track"} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-700 text-xs font-semibold hover:bg-slate-600 disabled:opacity-50">
        {loading === "track" ? <Loader2 className="w-3 h-3 animate-spin" /> : <Crosshair className="w-3 h-3" />} Track
      </button>
      <button onClick={exportCsv} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-700 text-xs font-semibold hover:bg-slate-600">
        <Download className="w-3 h-3" /> CSV
      </button>
      <button onClick={onClear} className="ml-1 p-1.5 rounded-lg hover:bg-slate-700"><X className="w-3.5 h-3.5 text-slate-400" /></button>
    </div>
  );
}
