import type { ReactNode, SVGProps } from "react";

type Tone =
  | "teal"
  | "amber"
  | "red"
  | "neutral"
  | "success"
  | "slate";

type PageHeaderProps = {
  eyebrow: string;
  title: string;
  description: string;
  logo?: ReactNode;
  actions?: ReactNode;
};

type PanelProps = {
  title: string;
  description?: string;
  action?: ReactNode;
  children: ReactNode;
  className?: string;
  variant?: "card" | "plain";
};

type StatCardProps = {
  label: string;
  value: string;
  hint: string;
  change?: string;
  tone?: Tone;
  icon?: ReactNode;
};

type BadgeProps = {
  children: ReactNode;
  tone?: Tone;
};

type ProgressBarProps = {
  value: number;
  tone?: Tone;
};

type SparklineProps = {
  points: number[];
  tone?: "teal" | "amber";
};

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

const toneMap: Record<Tone, string> = {
  teal: "bg-primary/12 text-primary border-primary/20",
  amber: "bg-accent/12 text-accent border-accent/20",
  red: "bg-danger/10 text-danger border-danger/20",
  neutral: "bg-white/70 text-foreground border-border",
  success: "bg-success/12 text-success border-success/20",
  slate: "bg-surface-deep/8 text-foreground border-border",
};

const badgeToneMap: Record<Tone, string> = {
  teal: "bg-[#f6f8f2] text-[#123238] border-primary/45",
  amber: "bg-[#fff3df] text-[#5c3414] border-accent/45",
  red: "bg-[#ffe8df] text-[#6f241a] border-danger/45",
  neutral: "bg-[#f6f8f2] text-[#1e2723] border-white/80",
  success: "bg-[#eef7d8] text-[#293f18] border-success/45",
  slate: "bg-[#eef2f0] text-[#1e2723] border-white/70",
};

const progressToneMap: Record<Tone, string> = {
  teal: "bg-primary",
  amber: "bg-accent",
  red: "bg-danger",
  neutral: "bg-foreground/70",
  success: "bg-success",
  slate: "bg-surface-deep",
};

export function PageHeader({
  eyebrow,
  title,
  description,
  logo,
  actions,
}: PageHeaderProps) {
  return (
    <section className="relative z-50 overflow-visible rounded-[30px] border border-white/70 bg-white/68 px-6 py-6 shadow-[0_24px_70px_rgba(16,35,29,0.08)] backdrop-blur md:px-8">
      <div className="relative z-[60] flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div className="max-w-3xl space-y-3">
          <p className="font-mono text-xs uppercase tracking-[0.32em] text-primary">
            {eyebrow}
          </p>
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
            {logo}
            <h1 className="display-title text-3xl font-semibold tracking-tight text-foreground md:text-4xl">
              {title}
            </h1>
          </div>
          <p className="max-w-2xl text-sm leading-6 text-muted md:text-base">
            {description}
          </p>
        </div>
        {actions ? (
          <div className="relative z-[70] flex flex-wrap gap-3">{actions}</div>
        ) : null}
      </div>
    </section>
  );
}

export function Panel({
  title,
  description,
  action,
  children,
  className,
  variant = "card",
}: PanelProps) {
  const isPlain = variant === "plain";

  return (
    <section
      className={cn(
        isPlain ? "p-0" : "card-shell rounded-[28px] p-5 md:p-6",
        className,
      )}
    >
      <div
        className={cn(
          "mb-5 flex flex-col gap-3 md:flex-row md:items-start md:justify-between",
          isPlain && "border-b border-border pb-4",
        )}
      >
        <div className="space-y-1">
          <h2 className="text-lg font-semibold tracking-tight text-foreground">
            {title}
          </h2>
          {description ? (
            <p className="max-w-2xl text-sm leading-6 text-muted">{description}</p>
          ) : null}
        </div>
        {action}
      </div>
      {children}
    </section>
  );
}

export function StatCard({
  label,
  value,
  hint,
  change,
  tone = "neutral",
  icon,
}: StatCardProps) {
  return (
    <article className="card-shell rounded-[26px] p-5">
      <div className="flex items-start justify-between gap-3">
        <div className="space-y-3">
          <p className="text-sm font-medium text-muted">{label}</p>
          <div className="space-y-1">
            <p className="text-3xl font-semibold tracking-tight text-foreground">
              {value}
            </p>
            {change ? <Badge tone={tone}>{change}</Badge> : null}
          </div>
        </div>
        {icon ? (
          <div className={cn("rounded-2xl border p-3", toneMap[tone])}>{icon}</div>
        ) : null}
      </div>
      <p className="mt-4 text-sm leading-6 text-muted">{hint}</p>
    </article>
  );
}

export function Badge({ children, tone = "neutral" }: BadgeProps) {
  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full border px-3 py-1 font-mono text-[11px] uppercase tracking-[0.2em]",
        badgeToneMap[tone],
      )}
    >
      {children}
    </span>
  );
}

export function ProgressBar({ value, tone = "teal" }: ProgressBarProps) {
  return (
    <div className="h-2.5 rounded-full bg-black/6">
      <div
        className={cn("h-full rounded-full", progressToneMap[tone])}
        style={{ width: `${Math.min(100, Math.max(0, value))}%` }}
      />
    </div>
  );
}

export function Sparkline({ points, tone = "teal" }: SparklineProps) {
  if (points.length < 2) {
    return null;
  }

  const min = Math.min(...points);
  const max = Math.max(...points);
  const range = max - min || 1;

  const plotted = points.map((point, index) => {
    const x = (index / (points.length - 1)) * 100;
    const normalized = (point - min) / range;
    const y = 34 - normalized * 24;
    return `${x},${y}`;
  });

  const linePoints = plotted.join(" ");
  const areaPoints = `0,38 ${linePoints} 100,38`;
  const stroke = tone === "amber" ? "#c06a36" : "#0f766e";
  const fill = tone === "amber" ? "rgba(192, 106, 54, 0.14)" : "rgba(15, 118, 110, 0.14)";

  return (
    <svg
      aria-hidden="true"
      className="h-16 w-full"
      viewBox="0 0 100 40"
      preserveAspectRatio="none"
    >
      <polygon fill={fill} points={areaPoints} />
      <polyline
        fill="none"
        points={linePoints}
        stroke={stroke}
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="2.8"
      />
      <circle
        cx={100}
        cy={Number(plotted.at(-1)?.split(",")[1] ?? 20)}
        fill={stroke}
        r="2.6"
      />
    </svg>
  );
}

function IconBase(props: SVGProps<SVGSVGElement>) {
  return (
    <svg
      fill="none"
      height="20"
      stroke="currentColor"
      strokeLinecap="round"
      strokeLinejoin="round"
      strokeWidth="1.8"
      viewBox="0 0 24 24"
      width="20"
      {...props}
    />
  );
}

export function DashboardIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M4 13h7V4H4zM13 20h7v-9h-7zM13 11h7V4h-7zM4 20h7v-5H4z" />
    </IconBase>
  );
}

export function BuildingsIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M4 20V7l8-3 8 3v13" />
      <path d="M9 20v-4h6v4" />
      <path d="M8 9h.01M12 9h.01M16 9h.01M8 12h.01M12 12h.01M16 12h.01" />
    </IconBase>
  );
}

export function UsersIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M16 21v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2" />
      <circle cx="9.5" cy="7" r="4" />
      <path d="M20 8a3 3 0 0 1 0 6" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
    </IconBase>
  );
}

export function WrenchIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="m14.7 6.3 3 3" />
      <path d="M12.2 8.8 4 17l3 3 8.2-8.2" />
      <path d="M14 4a4 4 0 0 1 5.66 5.66l-2.12-2.12-2.83 2.83 2.12 2.12A4 4 0 0 1 14 4Z" />
    </IconBase>
  );
}

export function WalletIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M3 7.5A2.5 2.5 0 0 1 5.5 5H19a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5.5A2.5 2.5 0 0 1 3 16.5z" />
      <path d="M16 12h5" />
      <circle cx="16" cy="12" r="0.75" fill="currentColor" stroke="none" />
    </IconBase>
  );
}

export function ShieldIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M12 3 5 6v6c0 5 3.4 8.6 7 10 3.6-1.4 7-5 7-10V6z" />
      <path d="m9.5 12 1.7 1.7 3.3-3.4" />
    </IconBase>
  );
}

export function MessageIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M21 12a8.5 8.5 0 0 1-8.5 8.5A8.4 8.4 0 0 1 8 19.2L3 21l1.8-5A8.4 8.4 0 0 1 3.5 12 8.5 8.5 0 0 1 12 3.5 8.5 8.5 0 0 1 21 12Z" />
    </IconBase>
  );
}

export function DocumentIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M7 3.5h6l4 4V20a1.5 1.5 0 0 1-1.5 1.5h-8A1.5 1.5 0 0 1 6 20V5A1.5 1.5 0 0 1 7.5 3.5Z" />
      <path d="M13 3.5V8h4" />
      <path d="M9 12h6M9 15h6M9 18h3" />
    </IconBase>
  );
}

export function CalendarIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M7 2v4M17 2v4M3 10h18" />
      <rect height="16" rx="2.5" width="18" x="3" y="6" />
    </IconBase>
  );
}

export function CarIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M6 16h12l1.5-4.5A2 2 0 0 0 17.6 9H6.4a2 2 0 0 0-1.9 2.5Z" />
      <path d="M5 16v3M19 16v3M7.5 12h9" />
      <circle cx="7.5" cy="18.5" r="1.5" />
      <circle cx="16.5" cy="18.5" r="1.5" />
    </IconBase>
  );
}

export function BoltIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M13 2 6 13h5l-1 9 8-12h-5z" />
    </IconBase>
  );
}

export function ArrowUpRightIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M7 17 17 7" />
      <path d="M8 7h9v9" />
    </IconBase>
  );
}

export function AlertIcon(props: SVGProps<SVGSVGElement>) {
  return (
    <IconBase {...props}>
      <path d="M12 9v4" />
      <circle cx="12" cy="17" r="0.8" fill="currentColor" stroke="none" />
      <path d="M10.3 3.8 2.9 17a2 2 0 0 0 1.7 3h14.8a2 2 0 0 0 1.7-3L13.7 3.8a2 2 0 0 0-3.4 0Z" />
    </IconBase>
  );
}
