"use client";

import { useState } from "react";
import { ClipboardPlus, CheckCircle2, AlertCircle, Copy, Check, Eye } from "lucide-react";

interface InlineActionProps {
  brandId: string;
  itemId: string;
  title: string;
  description: string;
  priority: string;
  effort?: string;
  evidence?: string;
  affectedPage?: string;
  /** If provided, action buttons are shown. If null, only copy is shown. */
  actionable: boolean;
}

export function InlineActions({ brandId, itemId, title, description, priority, effort, evidence, affectedPage, actionable }: InlineActionProps) {
  const [taskState, setTaskState] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [reviewed, setReviewed] = useState(false);

  async function createTask() {
    if (taskState) return;
    setTaskState("Creating...");
    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId,
          title: `Fix: ${title}`,
          description,
          category: "seo",
          priority,
          effort: effort ?? "medium",
          pageUrl: affectedPage ?? null,
          recommendation: evidence ?? description,
          source: "ai_strategist",
          sourceId: itemId,
        }),
      });
      if (res.ok) {
        const data = await res.json();
        setTaskState(data._duplicate ? "Exists" : "Created");
      } else {
        setTaskState("Failed");
        setTimeout(() => setTaskState(null), 3000);
      }
    } catch {
      setTaskState("Failed");
      setTimeout(() => setTaskState(null), 3000);
    }
  }

  function copyText() {
    navigator.clipboard.writeText(`${title}\n${description}${evidence ? `\nEvidence: ${evidence}` : ""}`);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="flex items-center gap-1 mt-2">
      {/* Create Task */}
      {actionable && !taskState && (
        <button onClick={createTask} className="flex items-center gap-1 px-2 py-1 rounded-md border border-brand-200 bg-brand-50 text-[9px] font-semibold text-brand-700 hover:bg-brand-100 transition-colors">
          <ClipboardPlus className="w-3 h-3" /> Task
        </button>
      )}
      {taskState && (
        <span className={`flex items-center gap-1 px-2 py-1 rounded-md text-[9px] font-semibold ${
          taskState === "Created" ? "bg-green-50 text-green-700 border border-green-200"
          : taskState === "Exists" ? "bg-amber-50 text-amber-700 border border-amber-200"
          : taskState === "Creating..." ? "bg-slate-50 text-slate-400 border border-slate-200"
          : "bg-red-50 text-red-700 border border-red-200"
        }`}>
          {taskState === "Created" && <CheckCircle2 className="w-3 h-3" />}
          {taskState === "Exists" && <AlertCircle className="w-3 h-3" />}
          {taskState}
        </span>
      )}

      {/* Copy */}
      <button onClick={copyText} className="flex items-center gap-1 px-2 py-1 rounded-md text-[9px] font-semibold text-slate-400 hover:bg-slate-100 transition-colors">
        {copied ? <Check className="w-3 h-3 text-green-600" /> : <Copy className="w-3 h-3" />}
        {copied ? "Copied" : "Copy"}
      </button>

      {/* Mark Reviewed */}
      {actionable && (
        <button onClick={() => setReviewed(!reviewed)} className={`flex items-center gap-1 px-2 py-1 rounded-md text-[9px] font-semibold transition-colors ${reviewed ? "bg-green-50 text-green-600" : "text-slate-400 hover:bg-slate-100"}`}>
          <Eye className="w-3 h-3" /> {reviewed ? "Reviewed" : "Review"}
        </button>
      )}
    </div>
  );
}
