import type { ReactNode } from "react";
import Link from "next/link";
import { cn } from "@/lib/cn";
import type { AdminStatTone } from "@/components/admin/AdminStatCard";

export type AdminPipelineStep = {
  key: string;
  label: string;
  value: number | string;
  href?: string;
  icon?: ReactNode;
  tone?: AdminStatTone;
};

const toneStyles: Record<AdminStatTone, string> = {
  blue: "bg-sky-50 text-sky-700",
  green: "bg-emerald-50 text-emerald-700",
  orange: "bg-orange-50 text-orange-600",
  purple: "bg-violet-50 text-violet-700",
  rose: "bg-rose-50 text-rose-600",
  navy: "bg-primary/5 text-primary",
};

/** Lifecycle steps — labels stay exact; no claim that rows are the same records. */
export function AdminPipeline({
  steps,
  className,
}: {
  steps: AdminPipelineStep[];
  className?: string;
}) {
  return (
    <ol className={cn("grid grid-cols-1 gap-2.5 sm:grid-cols-2", className)}>
      {steps.map((step) => (
        <li key={step.key} className="min-w-0">
          <PipelineCard step={step} />
        </li>
      ))}
    </ol>
  );
}

function PipelineCard({ step }: { step: AdminPipelineStep }) {
  const tone = step.tone ?? "navy";
  const inner = (
    <div className="flex items-start gap-3">
      {step.icon ? (
        <span
          className={cn(
            "flex size-9 shrink-0 items-center justify-center rounded-[10px]",
            toneStyles[tone],
          )}
          aria-hidden="true"
        >
          {step.icon}
        </span>
      ) : null}
      <div className="min-w-0">
        <p className="text-[0.8125rem] font-medium leading-snug text-ink-60">{step.label}</p>
        <p className="mt-1.5 text-[1.375rem] font-semibold tabular-nums tracking-[-0.03em] text-primary">
          {step.value}
        </p>
      </div>
    </div>
  );

  const classes =
    "flex h-full min-w-0 flex-col rounded-[10px] border border-line/80 bg-[#FAFBFC] px-3.5 py-3";

  if (step.href) {
    return (
      <Link
        href={step.href}
        className={cn(
          classes,
          "transition hover:border-primary/25 hover:bg-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent",
        )}
      >
        {inner}
      </Link>
    );
  }

  return <div className={classes}>{inner}</div>;
}

/** Compact financial relationship list — snapshot totals, not a wallet or time series. */
export function AdminFinanceFlow({
  steps,
  className,
}: {
  steps: Array<{ key: string; label: string; value: string; note?: string }>;
  className?: string;
}) {
  return (
    <ol
      className={cn(
        "divide-y divide-line overflow-hidden rounded-[10px] border border-line/80 bg-surface shadow-pv",
        className,
      )}
    >
      {steps.map((step, index) => (
        <li key={step.key} className="relative px-3.5 py-3 sm:px-4">
          {index > 0 ? <span className="sr-only">Then </span> : null}
          <div className="flex items-start justify-between gap-3">
            <div className="min-w-0">
              <p className="text-[0.8125rem] font-medium text-primary">{step.label}</p>
              {step.note ? (
                <p className="mt-0.5 text-[0.75rem] leading-snug text-ink-40">{step.note}</p>
              ) : null}
            </div>
            <p className="shrink-0 text-[0.9375rem] font-semibold tabular-nums tracking-[-0.02em] text-primary">
              {step.value}
            </p>
          </div>
        </li>
      ))}
    </ol>
  );
}

export function AdminHealthRow({
  items,
  className,
}: {
  items: Array<{
    key: string;
    label: string;
    tone: "success" | "warning" | "neutral" | "danger";
    detail?: string;
  }>;
  className?: string;
}) {
  if (items.length === 0) {
    return (
      <div
        className={cn(
          "rounded-[10px] border border-dashed border-line bg-[#FAFBFC] px-3.5 py-3.5",
          className,
        )}
      >
        <p className="text-[0.875rem] font-semibold text-primary">No connected accounts yet</p>
        <p className="mt-1 text-[0.8125rem] leading-relaxed text-ink-60">
          Counts stay neutral until creators complete Stripe Connect Express onboarding.
        </p>
      </div>
    );
  }

  return (
    <ul className={cn("space-y-2.5", className)}>
      {items.map((item) => (
        <li key={item.key} className="flex items-start gap-2.5 text-[0.8125rem]">
          <span
            className={cn(
              "mt-1.5 size-2 shrink-0 rounded-full",
              item.tone === "success" && "bg-emerald-600",
              item.tone === "warning" && "bg-amber-500",
              item.tone === "danger" && "bg-red-600",
              item.tone === "neutral" && "bg-ink-40",
            )}
            aria-hidden="true"
          />
          <div className="min-w-0">
            <p className="font-medium text-primary">{item.label}</p>
            {item.detail ? (
              <p className="mt-0.5 leading-snug text-ink-60">{item.detail}</p>
            ) : null}
          </div>
        </li>
      ))}
    </ul>
  );
}

export type AdminAttentionSeverity = "routine" | "warning" | "critical";

export type AdminAttentionItem = {
  key: string;
  title: string;
  detail: string;
  href?: string;
  count?: number | string;
  severity?: AdminAttentionSeverity;
};

const severityStyles: Record<
  AdminAttentionSeverity,
  { iconWrap: string; count: string; border: string; wash: string }
> = {
  routine: {
    iconWrap: "bg-slate-100 text-slate-600",
    count: "bg-slate-100 text-slate-700",
    border: "border-l-slate-400",
    wash: "hover:bg-slate-50/80",
  },
  warning: {
    iconWrap: "bg-amber-50 text-amber-700",
    count: "bg-amber-50 text-amber-900",
    border: "border-l-amber-500",
    wash: "hover:bg-amber-50/40",
  },
  critical: {
    iconWrap: "bg-red-50 text-red-700",
    count: "bg-red-50 text-red-900",
    border: "border-l-red-500",
    wash: "hover:bg-red-50/40",
  },
};

function AttentionIcon({ severity }: { severity: AdminAttentionSeverity }) {
  if (severity === "routine") {
    return (
      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
        <circle cx="7" cy="7" r="5.25" stroke="currentColor" strokeWidth="1.25" />
        <path d="M7 4.25v3.1" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
        <circle cx="7" cy="9.4" r="0.7" fill="currentColor" />
      </svg>
    );
  }

  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
      <path
        d="M7 1.75 12.25 11.5H1.75L7 1.75Z"
        stroke="currentColor"
        strokeWidth="1.25"
        strokeLinejoin="round"
      />
      <path d="M7 5.5v2.6" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
      <circle cx="7" cy="9.85" r="0.7" fill="currentColor" />
    </svg>
  );
}

export function AdminAttentionList({
  items,
  className,
}: {
  items: AdminAttentionItem[];
  className?: string;
}) {
  if (items.length === 0) {
    return (
      <div
        className={cn(
          "flex items-start gap-3 rounded-[10px] border border-emerald-200/70 bg-emerald-50/35 px-4 py-3.5 shadow-pv",
          className,
        )}
      >
        <span
          className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full bg-emerald-100 text-emerald-700"
          aria-hidden="true"
        >
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path
              d="M3.5 7.25 5.75 9.5 10.5 4.5"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </span>
        <div>
          <p className="text-[0.875rem] font-semibold text-emerald-950">Nothing needs attention</p>
          <p className="mt-0.5 text-[0.8125rem] leading-relaxed text-emerald-900/75">
            Current dashboard metrics show no outstanding operational or financial issues.
          </p>
        </div>
      </div>
    );
  }

  return (
    <ul
      className={cn(
        "overflow-hidden rounded-[10px] border border-line/80 bg-surface shadow-pv divide-y divide-line",
        className,
      )}
    >
      {items.map((item) => {
        const severity = item.severity ?? "warning";
        const styles = severityStyles[severity];

        const body: ReactNode = (
          <>
            <div
              className={cn(
                "mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full",
                styles.iconWrap,
              )}
            >
              <AttentionIcon severity={severity} />
            </div>
            <div className="min-w-0 flex-1">
              <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                <p className="text-[0.875rem] font-semibold text-primary">{item.title}</p>
                {item.count !== undefined ? (
                  <span
                    className={cn(
                      "rounded px-1.5 py-0.5 text-[0.75rem] font-semibold tabular-nums",
                      styles.count,
                    )}
                  >
                    {item.count}
                  </span>
                ) : null}
              </div>
              <p className="mt-1 text-[0.8125rem] leading-relaxed text-ink-60">{item.detail}</p>
            </div>
            {item.href ? (
              <span className="mt-1 shrink-0 text-[0.75rem] font-semibold text-accent transition group-hover:text-accent-hover">
                View
              </span>
            ) : null}
          </>
        );

        if (item.href) {
          return (
            <li key={item.key}>
              <Link
                href={item.href}
                className={cn(
                  "group flex items-start gap-3 border-l-[3px] bg-surface px-3.5 py-3.5 transition",
                  styles.border,
                  styles.wash,
                )}
              >
                {body}
              </Link>
            </li>
          );
        }

        return (
          <li
            key={item.key}
            className={cn(
              "flex items-start gap-3 border-l-[3px] bg-surface px-3.5 py-3.5",
              styles.border,
            )}
          >
            {body}
          </li>
        );
      })}
    </ul>
  );
}
