"use client";

import { useState } from "react";
import { ClipboardPlus, CheckCircle2, AlertCircle, Zap } from "lucide-react";
import type { ExtractedAction } from "@/lib/services/analysis-actions";

const PRIORITY_CLS: Record<string, string> = {
  critical: "text-red-700 bg-red-50 border-red-200",
  high: "text-orange-700 bg-orange-50 border-orange-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  low: "text-blue-700 bg-blue-50 border-blue-200",
};

const TYPE_LABELS: Record<string, string> = {
  investigate: "Investigate",
  fix: "Fix",
  monitor: "Monitor",
  configure: "Configure",
  connect_source: "Connect",
  create_content: "Create",
};

export function ActionsPanel({ actions, brandId }: { actions: ExtractedAction[]; brandId: string }) {
  const [feedback, setFeedback] = useState<Record<string, string>>({});

  async function createTask(action: ExtractedAction) {
    if (feedback[action.id]) return;
    setFeedback(prev => ({ ...prev, [action.id]: "Creating..." }));

    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          brandId,
          title: action.title,
          description: action.description,
          category: action.actionType === "connect_source" ? "technical" : "seo",
          priority: action.priority,
          effort: action.effort,
          pageUrl: action.affectedPage || null,
          recommendation: action.evidence,
          source: "ai_strategist",
          sourceId: action.id,
          sourceRunAt: new Date().toISOString(),
        }),
      });

      if (res.ok) {
        const data = await res.json();
        setFeedback(prev => ({ ...prev, [action.id]: data._duplicate ? "Already exists" : "Created!" }));
      } else {
        setFeedback(prev => ({ ...prev, [action.id]: "Failed" }));
        setTimeout(() => setFeedback(prev => { const n = { ...prev }; delete n[action.id]; return n; }), 3000);
      }
    } catch {
      setFeedback(prev => ({ ...prev, [action.id]: "Failed" }));
      setTimeout(() => setFeedback(prev => { const n = { ...prev }; delete n[action.id]; return n; }), 3000);
    }
  }

  if (actions.length === 0) return null;

  return (
    <div className="bg-white rounded-xl border border-brand-200 overflow-hidden">
      <div className="px-4 py-3 border-b border-brand-100 bg-brand-50/60 flex items-center gap-2">
        <Zap className="w-3.5 h-3.5 text-brand-600" />
        <h3 className="text-sm font-bold text-slate-800">Actionable Items</h3>
        <span className="ml-auto text-[10px] text-slate-400">{actions.length} action{actions.length !== 1 ? "s" : ""}</span>
      </div>
      <div className="divide-y divide-slate-100">
        {actions.map(action => {
          const state = feedback[action.id];
          return (
            <div key={action.id} className="px-4 py-3">
              <div className="flex items-start gap-2.5">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <span className={`text-[9px] font-bold uppercase px-1.5 py-0.5 rounded border ${PRIORITY_CLS[action.priority] ?? PRIORITY_CLS.medium}`}>
                      {action.priority}
                    </span>
                    <span className="text-[9px] font-semibold text-slate-400 uppercase">
                      {TYPE_LABELS[action.actionType] ?? action.actionType}
                    </span>
                  </div>
                  <p className="text-xs font-semibold text-slate-800">{action.title}</p>
                  <p className="text-[11px] text-slate-500 mt-0.5 leading-relaxed line-clamp-2">{action.description}</p>
                  {action.affectedMetric && (
                    <p className="text-[10px] text-slate-400 mt-1">Metric: {action.affectedMetric}</p>
                  )}
                </div>
                <div className="shrink-0">
                  {!state ? (
                    <button
                      onClick={() => createTask(action)}
                      className="flex items-center gap-1 px-2.5 py-1.5 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.5 py-1.5 rounded-lg text-[10px] font-semibold ${
                      state === "Created!" ? "bg-green-50 border border-green-200 text-green-700"
                      : state === "Already exists" ? "bg-amber-50 border border-amber-200 text-amber-700"
                      : state === "Creating..." ? "bg-slate-50 border border-slate-200 text-slate-400"
                      : "bg-red-50 border border-red-200 text-red-700"
                    }`}>
                      {state === "Created!" && <CheckCircle2 className="w-3 h-3" />}
                      {state === "Already exists" && <AlertCircle className="w-3 h-3" />}
                      {state}
                    </span>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
