"use client";

import { useMemo, useState } from "react";
import {
  ArrowRight,
  Brain,
  ChevronDown,
  ChevronUp,
  Plug,
  ShieldCheck,
  Sparkles,
  Zap,
} from "lucide-react";
import { getTaskAutomationFlow } from "@/lib/role-automation/automation-flow";
import type { Business, TaskAutomationFlow } from "@/lib/types";
import { Badge } from "@/components/ui/badge";

interface AutomationFlowPanelProps {
  taskId: string;
  roleName: string;
  integrationTarget: string;
  business: Business;
  compact?: boolean;
}

const stepIcons = [Brain, Sparkles, Plug, ShieldCheck];

export function AutomationFlowPanel({
  taskId,
  roleName,
  integrationTarget,
  business,
  compact = false,
}: AutomationFlowPanelProps) {
  const [expanded, setExpanded] = useState(!compact);
  const flow = useMemo(
    () => getTaskAutomationFlow(taskId, business, roleName, integrationTarget),
    [taskId, business, roleName, integrationTarget],
  );

  return (
    <div className="mt-2 rounded-lg border border-slate-800/80 bg-slate-950/60 p-2.5">
      <button
        type="button"
        className="flex w-full items-center justify-between gap-2 text-left"
        onClick={() => setExpanded((v) => !v)}
      >
        <span className="flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-violet-300">
          <Zap className="h-3 w-3" />
          How this automates
        </span>
        {expanded ? <ChevronUp className="h-3.5 w-3.5 text-slate-500" /> : <ChevronDown className="h-3.5 w-3.5 text-slate-500" />}
      </button>

      {expanded ? (
        <AutomationFlowSteps flow={flow} size="sm" />
      ) : (
        <p className="mt-1 text-[10px] text-slate-500 line-clamp-1">
          {flow.steps.map((s) => s.label.replace(/^\d+\.\s*/, "")).join(" → ")}
        </p>
      )}
    </div>
  );
}

export function AutomationFlowSteps({
  flow,
  size = "md",
}: {
  flow: TaskAutomationFlow;
  size?: "sm" | "md";
}) {
  const textSize = size === "sm" ? "text-[10px]" : "text-xs";

  return (
    <div className={`mt-2 space-y-2 ${textSize}`}>
      <p className="text-slate-400">
        <span className="text-slate-500">Trigger:</span> {flow.trigger}
      </p>

      <div className="space-y-1.5">
        {flow.steps.map((step, i) => {
          const Icon = stepIcons[i] ?? Zap;
          return (
            <div key={step.id} className="flex gap-2">
              <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-violet-500/20 bg-violet-500/10">
                <Icon className="h-3 w-3 text-violet-300" />
              </div>
              <div className="min-w-0 flex-1">
                <p className="font-medium text-slate-300">{step.label}</p>
                <p className="text-slate-500">{step.detail}</p>
              </div>
            </div>
          );
        })}
      </div>

      <div className="flex flex-wrap items-center gap-1.5 border-t border-slate-800 pt-2">
        <Badge className="border-violet-500/30 bg-violet-500/10 text-violet-200">
          {flow.integrationName}
        </Badge>
        <Badge className="border-amber-500/30 bg-amber-500/10 text-amber-200">
          {flow.mode === "demo" ? "Demo — simulates push" : "Live connected"}
        </Badge>
        {flow.requiresApproval ? (
          <Badge className="border-sky-500/30 bg-sky-500/10 text-sky-200">
            Approval required
          </Badge>
        ) : null}
      </div>

      <p className="text-slate-500">
        <span className="text-slate-400">Output:</span> {flow.outputLabel} — {flow.outputDetail}
      </p>
      <p className="text-slate-600">{flow.approvalNote}</p>
    </div>
  );
}

export function AutomationPlatformOverview() {
  const stages = [
    { icon: Brain, label: "Business Brain", color: "text-sky-400" },
    { icon: Sparkles, label: "Role Agent", color: "text-violet-400" },
    { icon: Zap, label: "AI Execute", color: "text-amber-400" },
    { icon: Plug, label: "Integration", color: "text-emerald-400" },
    { icon: ShieldCheck, label: "Receipt", color: "text-rose-400" },
  ];

  return (
    <div className="rounded-xl border border-violet-500/20 bg-violet-500/5 p-4">
      <p className="mb-3 text-sm font-medium text-violet-100">Automation pipeline</p>
      <div className="flex flex-wrap items-center gap-1 text-xs text-slate-400">
        {stages.map((stage, i) => (
          <span key={stage.label} className="flex items-center gap-1">
            <stage.icon className={`h-3.5 w-3.5 ${stage.color}`} />
            <span>{stage.label}</span>
            {i < stages.length - 1 ? <ArrowRight className="mx-0.5 h-3 w-3 text-slate-600" /> : null}
          </span>
        ))}
      </div>
      <p className="mt-3 text-xs text-slate-500">
        Each task box below shows exactly what runs when you click <strong className="text-slate-300">Run task</strong> — context loaded, AI output, integration target, and receipt. Demo mode generates real deliverables; connect integrations in Settings to push live.
      </p>
    </div>
  );
}
