"use client";

/**
 * Analysis Review Panel
 * ──────────────────────
 * Review, approve, reject, and edit extracted actions before
 * sending them to Execution Hub as tasks.
 */

import { useState } from "react";
import type { ExtractedAction } from "@/lib/services/analysis-actions";
import {
  CheckCircle2, X, Pencil, ClipboardPlus, AlertCircle,
  ChevronDown, ChevronUp, Zap, Shield, Check,
  AlertTriangle, Lightbulb, TrendingUp,
} from "lucide-react";

type ReviewState = "pending" | "approved" | "rejected" | "edited" | "created" | "exists";

interface ReviewedAction extends ExtractedAction {
  reviewState: ReviewState;
  editedTitle?: string;
  editedDescription?: string;
  editedPriority?: string;
}

const PRIORITY_OPTIONS = ["critical", "high", "medium", "low"] as const;

function deriveCategory(action: ExtractedAction): "issue" | "opportunity" | "win" {
  if (action.sourceSection === "prediction") return "win";
  if (["fix", "configure", "connect_source"].includes(action.actionType)) return "issue";
  return "opportunity";
}

function deriveRevenueImpact(priority: string): "high" | "medium" | "low" {
  if (priority === "critical") return "high";
  if (priority === "high") return "medium";
  return "low";
}

const CATEGORY_CFG = {
  issue:       { label: "Issue",       icon: AlertTriangle, cls: "text-red-700 bg-red-50 border-red-200" },
  opportunity: { label: "Opportunity", icon: Lightbulb,    cls: "text-indigo-700 bg-indigo-50 border-indigo-200" },
  win:         { label: "Win",         icon: TrendingUp,   cls: "text-emerald-700 bg-emerald-50 border-emerald-200" },
} as const;

const REVENUE_CLS: Record<string, string> = {
  high:   "text-rose-700 bg-rose-50 border-rose-200",
  medium: "text-amber-700 bg-amber-50 border-amber-200",
  low:    "text-slate-500 bg-slate-50 border-slate-200",
};

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 STATE_CFG: Record<ReviewState, { label: string; cls: string }> = {
  pending: { label: "Pending", cls: "bg-slate-100 text-slate-500 border-slate-200" },
  approved: { label: "Approved", cls: "bg-green-50 text-green-700 border-green-200" },
  rejected: { label: "Rejected", cls: "bg-red-50 text-red-500 border-red-200" },
  edited: { label: "Edited", cls: "bg-blue-50 text-blue-700 border-blue-200" },
  created: { label: "Task Created", cls: "bg-green-50 text-green-700 border-green-200" },
  exists: { label: "Already Exists", cls: "bg-amber-50 text-amber-700 border-amber-200" },
};

export function ReviewPanel({ actions, brandId, onClose }: {
  actions: ExtractedAction[];
  brandId: string;
  onClose?: () => void;
}) {
  const [items, setItems] = useState<ReviewedAction[]>(
    actions.map(a => ({ ...a, reviewState: "pending" }))
  );
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [creating, setCreating] = useState(false);

  function updateItem(id: string, updates: Partial<ReviewedAction>) {
    setItems(prev => prev.map(i => i.id === id ? { ...i, ...updates } : i));
  }

  function approveAll() {
    setItems(prev => prev.map(i => i.reviewState === "pending" ? { ...i, reviewState: "approved" } : i));
  }

  function rejectAll() {
    setItems(prev => prev.map(i => i.reviewState === "pending" ? { ...i, reviewState: "rejected" } : i));
  }

  async function createApprovedTasks() {
    const approved = items.filter(i => i.reviewState === "approved" || i.reviewState === "edited");
    if (approved.length === 0) return;

    setCreating(true);
    for (const action of approved) {
      try {
        const res = await fetch("/api/tasks", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "create",
            brandId,
            title: action.editedTitle ?? action.title,
            description: action.editedDescription ?? action.description,
            category: action.actionType === "connect_source" ? "technical" : "seo",
            priority: action.editedPriority ?? 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();
          updateItem(action.id, { reviewState: data._duplicate ? "exists" : "created" });
        }
      } catch {
        // Skip failed — keep as approved for retry
      }
    }
    setCreating(false);
  }

  const pending = items.filter(i => i.reviewState === "pending").length;
  const approved = items.filter(i => i.reviewState === "approved" || i.reviewState === "edited").length;
  const created = items.filter(i => i.reviewState === "created").length;

  return (
    <div className="h-full bg-slate-50 flex flex-col">
      {/* Header */}
      <div className="shrink-0 bg-white border-b border-slate-200 px-5 py-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-[10px] font-bold uppercase tracking-widest text-brand-600">Review Actions</p>
            <h2 className="text-base font-bold text-slate-900 mt-0.5">{items.length} extracted action{items.length !== 1 ? "s" : ""}</h2>
          </div>
          {onClose && (
            <button onClick={onClose} className="text-slate-400 hover:text-slate-600 p-1">
              <X className="w-4 h-4" />
            </button>
          )}
        </div>

        {/* Summary bar */}
        <div className="flex items-center gap-2 mt-3">
          <span className="text-[10px] text-slate-400">{pending} pending</span>
          <span className="text-[10px] text-green-600">{approved} approved</span>
          <span className="text-[10px] text-green-600">{created} created</span>
          <span className="flex-1" />
          <button onClick={approveAll} disabled={pending === 0} className="text-[10px] font-semibold text-green-600 hover:text-green-700 disabled:text-slate-300">
            Approve all
          </button>
          <button onClick={rejectAll} disabled={pending === 0} className="text-[10px] font-semibold text-red-500 hover:text-red-600 disabled:text-slate-300">
            Reject all
          </button>
        </div>
      </div>

      {/* Action list */}
      <div className="flex-1 overflow-y-auto min-h-0 p-4 space-y-2">
        {items.map(item => {
          const isExpanded = expandedId === item.id;
          const state = STATE_CFG[item.reviewState];
          const isFinalized = item.reviewState === "created" || item.reviewState === "exists";
          const category = deriveCategory(item);
          const catCfg = CATEGORY_CFG[category];
          const CatIcon = catCfg.icon;
          const revImpact = deriveRevenueImpact(item.editedPriority ?? item.priority);

          return (
            <div key={item.id} className={`bg-white rounded-xl border ${isFinalized ? "border-green-200" : "border-slate-200"} overflow-hidden`}>
              {/* Summary row */}
              <div className="px-4 py-3 flex items-start gap-2.5">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    {/* Category badge (mirrors Signals Center taxonomy) */}
                    <span className={`flex items-center gap-0.5 text-[9px] font-bold uppercase px-1.5 py-0.5 rounded border ${catCfg.cls}`}>
                      <CatIcon className="w-2.5 h-2.5" />
                      {catCfg.label}
                    </span>
                    {/* Priority */}
                    <span className={`text-[9px] font-bold uppercase px-1.5 py-0.5 rounded border ${PRIORITY_CLS[item.editedPriority ?? item.priority] ?? PRIORITY_CLS.medium}`}>
                      {item.editedPriority ?? item.priority}
                    </span>
                    {/* Revenue impact */}
                    <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded border ${REVENUE_CLS[revImpact]}`}>
                      {revImpact} impact
                    </span>
                    {/* Always "New" — actions derive from the most recent analysis run */}
                    <span className="text-[9px] font-bold uppercase px-1.5 py-0.5 rounded border bg-blue-50 text-blue-700 border-blue-200">
                      New
                    </span>
                    {/* Review state */}
                    <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded border ${state.cls}`}>
                      {state.label}
                    </span>
                  </div>
                  <p className="text-xs font-semibold text-slate-800 mt-1">{item.editedTitle ?? item.title}</p>
                  <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-1">{item.editedDescription ?? item.description}</p>
                </div>

                {/* Quick actions */}
                <div className="flex items-center gap-1 shrink-0">
                  {!isFinalized && item.reviewState !== "rejected" && (
                    <>
                      <button onClick={() => updateItem(item.id, { reviewState: "approved" })}
                        className={`p-1.5 rounded-lg transition-colors ${item.reviewState === "approved" ? "bg-green-100 text-green-600" : "text-slate-300 hover:text-green-600 hover:bg-green-50"}`}
                        title="Approve">
                        <Check className="w-3.5 h-3.5" />
                      </button>
                      <button onClick={() => updateItem(item.id, { reviewState: "rejected" })}
                        className="p-1.5 rounded-lg text-slate-300 hover:text-red-500 hover:bg-red-50 transition-colors" title="Reject">
                        <X className="w-3.5 h-3.5" />
                      </button>
                    </>
                  )}
                  {item.reviewState === "rejected" && (
                    <button onClick={() => updateItem(item.id, { reviewState: "pending" })}
                      className="text-[10px] font-semibold text-slate-400 hover:text-slate-600">Undo</button>
                  )}
                  <button onClick={() => setExpandedId(isExpanded ? null : item.id)}
                    className="p-1.5 rounded-lg text-slate-300 hover:text-slate-500 transition-colors">
                    {isExpanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
                  </button>
                </div>
              </div>

              {/* Expanded edit form */}
              {isExpanded && !isFinalized && (
                <div className="px-4 pb-4 border-t border-slate-100 pt-3 space-y-2">
                  <div>
                    <label className="text-[10px] font-semibold text-slate-400 uppercase">Title</label>
                    <input
                      type="text"
                      value={item.editedTitle ?? item.title}
                      onChange={e => updateItem(item.id, { editedTitle: e.target.value, reviewState: "edited" })}
                      className="w-full mt-0.5 px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-brand-500"
                    />
                  </div>
                  <div>
                    <label className="text-[10px] font-semibold text-slate-400 uppercase">Description</label>
                    <textarea
                      value={item.editedDescription ?? item.description}
                      onChange={e => updateItem(item.id, { editedDescription: e.target.value, reviewState: "edited" })}
                      rows={3}
                      className="w-full mt-0.5 px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-brand-500 resize-none"
                    />
                  </div>
                  <div>
                    <label className="text-[10px] font-semibold text-slate-400 uppercase">Priority</label>
                    <select
                      value={item.editedPriority ?? item.priority}
                      onChange={e => updateItem(item.id, { editedPriority: e.target.value, reviewState: "edited" })}
                      className="w-full mt-0.5 px-2.5 py-1.5 text-xs border border-slate-200 rounded-lg bg-white"
                    >
                      {PRIORITY_OPTIONS.map(p => <option key={p} value={p}>{p.charAt(0).toUpperCase() + p.slice(1)}</option>)}
                    </select>
                  </div>
                  <p className="text-[10px] text-slate-400 font-mono bg-slate-50 rounded px-2 py-1">{item.evidence}</p>
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Footer: Create tasks */}
      <div className="shrink-0 bg-white border-t border-slate-200 px-5 py-3">
        <button
          onClick={createApprovedTasks}
          disabled={approved === 0 || creating}
          className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700 disabled:opacity-50 transition-colors"
        >
          <ClipboardPlus className="w-4 h-4" />
          {creating ? "Creating tasks..." : `Create ${approved} task${approved !== 1 ? "s" : ""} in Execution Hub`}
        </button>
      </div>
    </div>
  );
}
