"use client";

import {
  BookOpen,
  CheckCircle2,
  ChevronDown,
  Droplets,
  Gauge,
  Lightbulb,
  Loader2,
  Pause,
  Play,
  Power,
  RotateCcw,
  SlidersHorizontal,
  AlertTriangle,
  Wrench,
  XCircle,
} from "lucide-react";
import type React from "react";
import { useState } from "react";
import type {
  ArtifactAction,
  ArtifactComponentProps,
  DeviceActionProps,
  GuidedProcedureProps,
  InteractionArtifact,
  KnowledgeBlock,
  KnowledgeLessonProps,
  ParameterChangeProps,
} from "@/lib/artifacts/types";
import { KnowledgeArtifact } from "./KnowledgeArtifact";
import { DieMaterialAdjust } from "./DieMaterialAdjust";
import { DieStatusOverview } from "./DieStatusOverview";

function cx(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

function actionClass(kind: ArtifactAction["kind"]) {
  if (kind === "primary") {
    return "bg-zinc-950 text-white hover:bg-zinc-800";
  }
  if (kind === "danger") {
    return "bg-red-600 text-white hover:bg-red-500";
  }
  return "border border-zinc-200 bg-white text-zinc-700 hover:bg-zinc-50";
}

function ArtifactFrame({
  artifact,
  eyebrow,
  icon: Icon,
  children,
}: {
  artifact: InteractionArtifact;
  eyebrow: string;
  icon: typeof SlidersHorizontal;
  children: React.ReactNode;
}) {
  const statusLabel: Record<InteractionArtifact["status"], string> = {
    draft: "草稿",
    waiting_confirmation: "等待确认",
    running: "执行中",
    success: "已完成",
    failed: "失败",
    paused: "已暂停",
  };

  return (
    <section className="w-full max-w-5xl">
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-lg bg-zinc-950 text-white">
            <Icon className="h-5 w-5" />
          </div>
          <div>
            <p className="text-xs font-semibold uppercase tracking-[0.18em] text-zinc-500">{eyebrow}</p>
            <h2 className="text-2xl font-semibold text-zinc-950">{artifact.title}</h2>
          </div>
        </div>
        <span
          className={cx(
            "rounded-full px-3 py-1 text-sm font-medium",
            artifact.status === "success" && "bg-emerald-50 text-emerald-700",
            artifact.status === "running" && "bg-blue-50 text-blue-700",
            artifact.status === "waiting_confirmation" && "bg-amber-50 text-amber-700",
            artifact.status === "failed" && "bg-red-50 text-red-700",
            artifact.status === "paused" && "bg-zinc-100 text-zinc-600",
          )}
        >
          {statusLabel[artifact.status]}
        </span>
      </div>
      <div className="rounded-lg border border-zinc-200 bg-white shadow-sm">{children}</div>
    </section>
  );
}

function ArtifactActions({
  artifact,
  onAction,
}: {
  artifact: InteractionArtifact;
  onAction: (action: ArtifactAction, value?: unknown) => void;
}) {
  if (artifact.actions.length === 0) return null;

  const voiceHints = artifact.actions.flatMap((action) => action.voiceAliases ?? []).slice(0, 3);

  return (
    <div className="border-t border-zinc-100 px-6 py-4">
      {voiceHints.length > 0 && artifact.status === "waiting_confirmation" && (
        <div className="mb-3 rounded-md bg-blue-50 px-3 py-2 text-xs font-medium text-blue-700">
          可说：{voiceHints.join(" / ")}
        </div>
      )}
      <div className="flex flex-wrap gap-3">
        {artifact.actions.map((action) => (
          <button
            key={action.actionId}
            type="button"
            disabled={action.disabled}
            onClick={() => onAction(action)}
            className={cx(
              "inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-50",
              actionClass(action.kind),
            )}
          >
            {action.kind === "primary" ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}
            {action.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function ParameterChangeCard({
  artifact,
  onAction,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "parameter_change" }>>) {
  const props = artifact.props as ParameterChangeProps;

  return (
    <ArtifactFrame artifact={artifact} eyebrow="Parameter Change" icon={SlidersHorizontal}>
      <div className="grid gap-0 md:grid-cols-[1fr_1.2fr]">
        <div className="border-b border-zinc-100 p-6 md:border-b-0 md:border-r">
          <p className="text-sm text-zinc-500">{props.deviceName}</p>
          <h3 className="mt-2 text-3xl font-semibold text-zinc-950">{props.parameterName}</h3>
          <p className="mt-4 text-sm leading-6 text-zinc-600">{props.impact}</p>
          <p className="mt-4 rounded-md bg-zinc-50 p-3 text-sm text-zinc-600">{props.executionNote}</p>
        </div>

        <div className="p-6">
          <div className="grid grid-cols-[1fr_auto_1fr] items-center gap-4">
            <ValuePanel label="当前值" value={props.currentValue} unit={props.unit} muted />
            <div className="h-px w-8 bg-zinc-200 md:w-12" />
            <ValuePanel label="目标值" value={props.targetValue} unit={props.unit} />
          </div>

          <div className="mt-6 flex items-center gap-3 rounded-lg bg-amber-50 p-4 text-amber-800">
            {artifact.status === "running" ? (
              <Loader2 className="h-5 w-5 animate-spin" />
            ) : artifact.status === "success" ? (
              <CheckCircle2 className="h-5 w-5" />
            ) : artifact.status === "failed" ? (
              <XCircle className="h-5 w-5" />
            ) : (
              <AlertTriangle className="h-5 w-5" />
            )}
            <span className="text-sm font-medium">
              {artifact.status === "success"
                ? "参数已写入，画布保留本次修改快照。"
                : artifact.status === "running"
                  ? "正在模拟写入参数..."
                  : artifact.status === "failed"
                    ? "参数写入失败，可以修改后重试。"
                    : "请确认前后值无误后再执行。"}
            </span>
          </div>
        </div>
      </div>
      <ArtifactActions artifact={artifact} onAction={onAction} />
    </ArtifactFrame>
  );
}

function ValuePanel({
  label,
  value,
  unit,
  muted,
}: {
  label: string;
  value: string | number;
  unit?: string;
  muted?: boolean;
}) {
  return (
    <div className={cx("rounded-lg border p-5", muted ? "border-zinc-200 bg-zinc-50" : "border-zinc-950 bg-zinc-950 text-white")}>
      <p className={cx("text-sm font-medium", muted ? "text-zinc-500" : "text-zinc-300")}>{label}</p>
      <div className="mt-3 flex items-end gap-2">
        <span className="text-4xl font-semibold tracking-normal">{value}</span>
        {unit && <span className={cx("pb-1 text-sm", muted ? "text-zinc-500" : "text-zinc-300")}>{unit}</span>}
      </div>
    </div>
  );
}

function DeviceActionCard({
  artifact,
  onAction,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "device_action" }>>) {
  const props = artifact.props as DeviceActionProps;
  const isActive = artifact.status === "running" || artifact.status === "success";
  const DeviceIcon = props.deviceKind === "pump" ? Droplets : props.deviceKind === "light" ? Lightbulb : Power;

  return (
    <ArtifactFrame artifact={artifact} eyebrow="Device Action" icon={DeviceIcon}>
      <div className="grid gap-0 md:grid-cols-[1.1fr_0.9fr]">
        <div className="relative min-h-[360px] overflow-hidden bg-zinc-950 p-8 text-white">
          <div className="relative z-10">
            <p className="text-sm text-zinc-400">{props.deviceKind.toUpperCase()}</p>
            <h3 className="mt-2 text-4xl font-semibold">{props.deviceName}</h3>
            <p className="mt-3 text-zinc-300">{props.executionNote}</p>
          </div>

          <div className="absolute inset-x-0 bottom-0 h-44 bg-gradient-to-t from-zinc-800 to-transparent" />
          <DeviceMotionScene deviceKind={props.deviceKind} icon={DeviceIcon} active={isActive} running={artifact.status === "running"} />
        </div>

        <div className="p-6">
          <div className="space-y-4">
            <StatusRow label="当前状态" value={props.currentState} />
            <StatusRow label="目标状态" value={props.targetState} emphasis />
            <StatusRow label="执行动作" value={actionLabel(props.action)} />
          </div>
          <div className="mt-8 rounded-lg border border-zinc-200 p-4">
            <div className="mb-3 flex items-center justify-between text-sm">
              <span className="font-medium text-zinc-700">{props.progressLabel ?? "执行进度"}</span>
              <span className="text-zinc-500">{artifact.status === "success" ? "100%" : artifact.status === "running" ? "64%" : "0%"}</span>
            </div>
            <div className="h-2 rounded-full bg-zinc-100">
              <div
                className={cx(
                  "h-2 rounded-full transition-all duration-700",
                  artifact.status === "success" ? "w-full bg-emerald-500" : artifact.status === "running" ? "w-2/3 bg-cyan-500" : "w-0",
                )}
              />
            </div>
          </div>
        </div>
      </div>
      <ArtifactActions artifact={artifact} onAction={onAction} />
    </ArtifactFrame>
  );
}

function DeviceMotionScene({
  deviceKind,
  icon: DeviceIcon,
  active,
  running,
}: {
  deviceKind: DeviceActionProps["deviceKind"];
  icon: typeof Droplets;
  active: boolean;
  running: boolean;
}) {
  const isPump = deviceKind === "pump";
  const isLight = deviceKind === "light";

  return (
    <div className="absolute left-1/2 top-1/2 z-10 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center">
      <div
        className={cx(
          "absolute h-56 w-56 rounded-full transition duration-700",
          active && isPump && "scale-100 bg-sky-400/20 blur-xl",
          active && isLight && "scale-100 bg-cyan-400/20 blur-xl",
          active && !isPump && !isLight && "scale-100 bg-emerald-400/20 blur-xl",
          !active && "scale-75 bg-zinc-600/20 blur-lg",
        )}
      />

      {isPump && (
        <div className="absolute h-48 w-64 overflow-hidden rounded-full">
          <span className={cx("pump-flow absolute left-1/2 top-1/2 h-3 w-52 rounded-full bg-sky-300/60 animate-pulse", !active && "opacity-0")} />
          <span
            className={cx("pump-flow absolute left-1/2 top-[58%] h-2 w-44 rounded-full bg-emerald-300/50 animate-pulse", !active && "opacity-0")}
            style={{ animationDelay: "300ms" }}
          />
          <span className={cx("pump-drop absolute left-[30%] top-[22%] h-3 w-3 rounded-full bg-sky-200 animate-bounce", !running && "opacity-0")} />
          <span
            className={cx("pump-drop absolute left-[64%] top-[20%] h-2.5 w-2.5 rounded-full bg-cyan-100 animate-bounce", !running && "opacity-0")}
            style={{ animationDelay: "180ms" }}
          />
          <span
            className={cx("pump-drop absolute left-[52%] top-[66%] h-2 w-2 rounded-full bg-emerald-200 animate-bounce", !running && "opacity-0")}
            style={{ animationDelay: "360ms" }}
          />
        </div>
      )}

      {isLight && active && (
        <>
          <span className="absolute h-44 w-44 animate-ping rounded-full border border-cyan-200/40" />
          <span className="absolute h-64 w-64 rounded-full bg-cyan-300/10 blur-2xl" />
        </>
      )}

      <div
        className={cx(
          "relative flex h-36 w-36 items-center justify-center rounded-full border transition duration-700",
          active && isPump && "border-sky-300 bg-sky-300/15 text-sky-100",
          active && isLight && "border-cyan-300 bg-cyan-300/15 text-cyan-100",
          active && !isPump && !isLight && "border-emerald-300 bg-emerald-300/15 text-emerald-100",
          !active && "border-zinc-700 bg-zinc-900 text-zinc-500",
        )}
      >
        <DeviceIcon className={cx("h-16 w-16", running && (isPump ? "animate-bounce" : "animate-pulse"))} />
      </div>
    </div>
  );
}

function actionLabel(action: DeviceActionProps["action"]) {
  return {
    open: "打开",
    close: "关闭",
    start: "启动",
    stop: "停止",
  }[action];
}

function StatusRow({ label, value, emphasis }: { label: string; value: string; emphasis?: boolean }) {
  return (
    <div className="flex items-center justify-between rounded-lg bg-zinc-50 px-4 py-3">
      <span className="text-sm text-zinc-500">{label}</span>
      <span className={cx("text-sm font-semibold", emphasis ? "text-zinc-950" : "text-zinc-700")}>{value}</span>
    </div>
  );
}

function KnowledgeLessonArtifact({
  artifact,
  onAction,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "knowledge_lesson" }>>) {
  const props = artifact.props as KnowledgeLessonProps;

  return (
    <ArtifactFrame artifact={artifact} eyebrow="Knowledge Lesson" icon={BookOpen}>
      <div className="p-6">
        <div className="rounded-lg bg-emerald-50 p-5">
          <p className="text-sm font-semibold text-emerald-700">先看结论</p>
          <h3 className="mt-2 text-2xl font-semibold text-emerald-950">{props.conclusion}</h3>
        </div>
        <div className="mt-6 grid gap-4">
          {props.blocks.map((block, index) => (
            <KnowledgeBlockView block={block} key={`${block.type}_${index}`} />
          ))}
        </div>
      </div>
      <ArtifactActions artifact={artifact} onAction={onAction} />
    </ArtifactFrame>
  );
}

function KnowledgeBlockView({ block }: { block: KnowledgeBlock }) {
  const [open, setOpen] = useState(block.type !== "details" || Boolean(block.defaultOpen));

  if (block.type === "summary") {
    return <p className="rounded-lg border border-zinc-200 p-4 text-sm leading-6 text-zinc-700">{block.text}</p>;
  }

  if (block.type === "key_points") {
    return (
      <div className="rounded-lg border border-zinc-200 p-4">
        <p className="mb-3 text-sm font-semibold text-zinc-950">关键点</p>
        <div className="grid gap-2 md:grid-cols-3">
          {block.items.map((item) => (
            <div className="rounded-md bg-zinc-50 p-3 text-sm text-zinc-700" key={item}>
              {item}
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (block.type === "steps") {
    return (
      <div className="rounded-lg border border-zinc-200 p-4">
        <p className="mb-4 text-sm font-semibold text-zinc-950">处理步骤</p>
        <div className="space-y-3">
          {block.steps.map((step, index) => (
            <div className="grid grid-cols-[32px_1fr] gap-3" key={step.title}>
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-zinc-950 text-sm font-semibold text-white">{index + 1}</div>
              <div>
                <p className="font-medium text-zinc-950">{step.title}</p>
                <p className="mt-1 text-sm leading-6 text-zinc-600">{step.body}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (block.type === "details") {
    return (
      <div className="rounded-lg border border-zinc-200">
        <button className="flex w-full items-center justify-between p-4 text-left" type="button" onClick={() => setOpen((value) => !value)}>
          <span className="font-semibold text-zinc-950">{block.title}</span>
          <ChevronDown className={cx("h-4 w-4 text-zinc-500 transition", open && "rotate-180")} />
        </button>
        {open && <p className="border-t border-zinc-100 p-4 text-sm leading-6 text-zinc-600">{block.markdown}</p>}
      </div>
    );
  }

  if (block.type === "citations") {
    return (
      <div className="rounded-lg bg-zinc-50 p-4">
        <p className="mb-2 text-sm font-semibold text-zinc-950">来源</p>
        <div className="flex flex-wrap gap-2">
          {block.citations.map((citation) => (
            <span className="rounded-full bg-white px-3 py-1 text-xs text-zinc-600" key={`${citation.title}_${citation.location}`}>
              {citation.title} · {citation.location}
            </span>
          ))}
        </div>
      </div>
    );
  }

  return null;
}

function GuidedProcedureArtifact({
  artifact,
  onAction,
}: ArtifactComponentProps<Extract<InteractionArtifact, { type: "guided_procedure" }>>) {
  const props = artifact.props as GuidedProcedureProps;
  const activeIndex = props.steps.findIndex((step) => step.stepId === props.currentStepId);
  const activeStep = props.steps[activeIndex] ?? props.steps[0];

  return (
    <ArtifactFrame artifact={artifact} eyebrow="Guided Procedure" icon={Wrench}>
      <div className="grid gap-0 lg:grid-cols-[320px_1fr]">
        <div className="border-b border-zinc-100 p-6 lg:border-b-0 lg:border-r">
          <p className="text-sm text-zinc-500">{props.deviceName}</p>
          <h3 className="mt-2 text-2xl font-semibold text-zinc-950">{props.procedureName}</h3>
          <div className="mt-6 space-y-3">
            {props.steps.map((step, index) => (
              <div
                className={cx(
                  "rounded-lg border p-3",
                  step.stepId === props.currentStepId ? "border-zinc-950 bg-zinc-950 text-white" : "border-zinc-200 bg-white",
                )}
                key={step.stepId}
              >
                <div className="flex items-center gap-2">
                  <span className="flex h-6 w-6 items-center justify-center rounded-full bg-white/15 text-xs font-semibold">{index + 1}</span>
                  <span className="text-sm font-medium">{step.title}</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="p-6">
          {activeStep ? (
            <>
              <div className="flex items-center gap-3">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-50 text-blue-700">
                  {activeStep.type === "measurement_input" ? <Gauge className="h-5 w-5" /> : <RotateCcw className="h-5 w-5" />}
                </div>
                <div>
                  <p className="text-sm text-zinc-500">第 {activeIndex + 1} 步</p>
                  <h3 className="text-2xl font-semibold text-zinc-950">{activeStep.title}</h3>
                </div>
              </div>
              <p className="mt-5 rounded-lg bg-zinc-50 p-4 text-sm leading-6 text-zinc-700">{activeStep.instruction}</p>
              {activeStep.expectedFeedback && (
                <div className="mt-5">
                  <p className="mb-2 text-sm font-semibold text-zinc-950">可输入反馈</p>
                  <div className="flex flex-wrap gap-2">
                    {activeStep.expectedFeedback.map((feedback) => (
                      <span className="rounded-full bg-blue-50 px-3 py-1 text-xs font-medium text-blue-700" key={feedback}>
                        {feedback}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="rounded-lg bg-emerald-50 p-6 text-emerald-800">
              <CheckCircle2 className="mb-3 h-6 w-6" />
              流程已经完成。
            </div>
          )}
        </div>
      </div>
      <ArtifactActions artifact={artifact} onAction={onAction} />
    </ArtifactFrame>
  );
}

const registry = {
  parameter_change: ParameterChangeCard,
  device_action: DeviceActionCard,
  knowledge_lesson: KnowledgeArtifact,
  guided_procedure: GuidedProcedureArtifact,
  die_material_adjust: DieMaterialAdjust,
  die_status_overview: DieStatusOverview,
};


export function ArtifactRenderer({ artifact, onAction }: ArtifactComponentProps) {
  const Component = registry[artifact.type] as (props: ArtifactComponentProps) => React.ReactNode;
  return <Component artifact={artifact} onAction={onAction} />;
}
