import { type ReactNode } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { ArrowDownRight, ArrowUpRight, type LucideIcon } from "lucide-react";

/* ---------------- Metric Card ---------------- */
export interface MetricCardProps {
  label: string;
  value: string;
  delta?: string;
  trend?: "up" | "down" | "flat";
  icon?: LucideIcon;
  hint?: string;
  accent?: "primary" | "accent" | "warning" | "destructive";
}

export function MetricCard({
  label,
  value,
  delta,
  trend = "up",
  icon: Icon,
  hint,
  accent = "primary",
}: MetricCardProps) {
  const trendColor =
    trend === "up"
      ? "text-success"
      : trend === "down"
        ? "text-destructive"
        : "text-muted-foreground";
  const TrendIcon = trend === "down" ? ArrowDownRight : ArrowUpRight;
  return (
    <Card className="relative overflow-hidden">
      <div
        className={cn(
          "absolute inset-x-0 top-0 h-px opacity-70",
          accent === "primary" && "bg-gradient-to-r from-transparent via-primary to-transparent",
          accent === "accent" && "bg-gradient-to-r from-transparent via-accent to-transparent",
          accent === "warning" && "bg-gradient-to-r from-transparent via-warning to-transparent",
          accent === "destructive" &&
            "bg-gradient-to-r from-transparent via-destructive to-transparent",
        )}
      />
      <CardContent className="pt-5">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <div className="text-xs font-medium text-muted-foreground truncate">{label}</div>
            <div className="mt-1.5 text-2xl font-semibold tracking-tight tabular-nums">{value}</div>
            {(delta || hint) && (
              <div className="mt-1 flex items-center gap-2 text-[11px]">
                {delta && (
                  <span className={cn("flex items-center gap-0.5 font-medium", trendColor)}>
                    <TrendIcon className="h-3 w-3" /> {delta}
                  </span>
                )}
                {hint && <span className="text-muted-foreground truncate">{hint}</span>}
              </div>
            )}
          </div>
          {Icon && (
            <div
              className={cn(
                "h-9 w-9 shrink-0 rounded-lg grid place-items-center",
                accent === "primary" &&
                  "bg-gradient-to-br from-primary/15 to-accent/10 text-primary",
                accent === "accent" && "bg-accent/15 text-accent-foreground",
                accent === "warning" && "bg-warning/15 text-warning-foreground",
                accent === "destructive" && "bg-destructive/15 text-destructive",
              )}
            >
              <Icon className="h-4 w-4" />
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

/* ---------------- Analytics / Chart Card shell ---------------- */
export interface ChartWidgetProps {
  title: string;
  description?: string;
  action?: ReactNode;
  badge?: string;
  children: ReactNode;
  className?: string;
}

export function ChartWidget({
  title,
  description,
  action,
  badge,
  children,
  className,
}: ChartWidgetProps) {
  return (
    <Card className={cn("overflow-hidden", className)}>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <CardTitle className="text-base">{title}</CardTitle>
            {badge && (
              <Badge variant="secondary" className="text-[10px] h-4">
                {badge}
              </Badge>
            )}
          </div>
          {description && <p className="text-xs text-muted-foreground mt-0.5">{description}</p>}
        </div>
        {action}
      </CardHeader>
      <CardContent>{children}</CardContent>
    </Card>
  );
}

/* ---------------- Insight Panel ---------------- */
export interface InsightItem {
  title: string;
  reason: string;
  impact: string;
  tone: "primary" | "accent" | "warning" | "destructive";
}

export function InsightPanel({
  title,
  description,
  items,
  icon: Icon,
}: {
  title: string;
  description?: string;
  items: InsightItem[];
  icon?: LucideIcon;
}) {
  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-center gap-2">
          {Icon && <Icon className="h-4 w-4 text-primary" />}
          <CardTitle className="text-sm">{title}</CardTitle>
        </div>
        {description && <p className="text-xs text-muted-foreground">{description}</p>}
      </CardHeader>
      <CardContent className="space-y-3">
        {items.map((it) => (
          <div
            key={it.title}
            className={cn(
              "rounded-lg border p-3 transition-colors hover:bg-muted/30",
              it.tone === "primary" && "border-primary/20 bg-primary/5",
              it.tone === "accent" && "border-accent/30 bg-accent/5",
              it.tone === "warning" && "border-warning/30 bg-warning/5",
              it.tone === "destructive" && "border-destructive/30 bg-destructive/5",
            )}
          >
            <div className="flex items-start justify-between gap-2">
              <div className="text-xs font-semibold leading-snug">{it.title}</div>
              <Badge
                variant="outline"
                className={cn(
                  "text-[9px] shrink-0",
                  it.tone === "primary" && "border-primary/30 text-primary",
                  it.tone === "accent" && "border-accent/40 text-accent-foreground",
                  it.tone === "warning" && "border-warning/40 text-warning-foreground",
                  it.tone === "destructive" && "border-destructive/40 text-destructive",
                )}
              >
                {it.impact}
              </Badge>
            </div>
            <p className="mt-1 text-[11px] text-muted-foreground leading-relaxed">{it.reason}</p>
            <div className="mt-2 flex gap-2">
              <Button size="sm" variant="ghost" className="h-7 px-2 text-[11px]">
                Dismiss
              </Button>
              <Button size="sm" className="h-7 px-2 text-[11px]">
                Apply
              </Button>
            </div>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

/* ---------------- Timeline ---------------- */
export interface TimelineItem {
  time: string;
  title: string;
  detail: string;
  tone: "primary" | "accent" | "success" | "warning" | "destructive";
}

const dotColor: Record<TimelineItem["tone"], string> = {
  primary: "bg-primary",
  accent: "bg-accent",
  success: "bg-success",
  warning: "bg-warning",
  destructive: "bg-destructive",
};

export function Timeline({ items }: { items: TimelineItem[] }) {
  return (
    <ol className="relative space-y-4 pl-5 before:absolute before:left-1.5 before:top-1 before:bottom-1 before:w-px before:bg-border">
      {items.map((it, i) => (
        <li key={i} className="relative">
          <span
            className={cn(
              "absolute -left-[18px] top-1 h-2.5 w-2.5 rounded-full ring-2 ring-background",
              dotColor[it.tone],
            )}
          />
          <div className="flex items-center gap-2">
            <span className="text-[10px] font-mono text-muted-foreground tabular-nums">
              {it.time}
            </span>
            <span className="text-xs font-medium">{it.title}</span>
          </div>
          <p className="mt-0.5 text-[11px] text-muted-foreground leading-relaxed">{it.detail}</p>
        </li>
      ))}
    </ol>
  );
}

/* ---------------- Activity Feed ---------------- */
export interface ActivityItem {
  actor: string;
  action: string;
  target: string;
  time: string;
  tone: "primary" | "accent" | "success" | "warning" | "muted";
}

export function ActivityFeed({ items }: { items: ActivityItem[] }) {
  return (
    <ul className="divide-y divide-border">
      {items.map((it, i) => (
        <li key={i} className="flex items-start gap-3 py-3 first:pt-0 last:pb-0">
          <div
            className={cn(
              "mt-1 h-2 w-2 shrink-0 rounded-full",
              it.tone === "primary" && "bg-primary",
              it.tone === "accent" && "bg-accent",
              it.tone === "success" && "bg-success",
              it.tone === "warning" && "bg-warning",
              it.tone === "muted" && "bg-muted-foreground/40",
            )}
          />
          <div className="min-w-0 flex-1">
            <p className="text-xs leading-snug">
              <span className="font-medium text-foreground">{it.actor}</span>{" "}
              <span className="text-muted-foreground">{it.action}</span>{" "}
              <span className="font-medium text-foreground">{it.target}</span>
            </p>
            <p className="mt-0.5 text-[10px] text-muted-foreground">{it.time}</p>
          </div>
        </li>
      ))}
    </ul>
  );
}

/* ---------------- Quick Actions ---------------- */
export interface QuickAction {
  label: string;
  description: string;
  icon: LucideIcon;
  href?: string;
}

export function QuickActions({ actions }: { actions: QuickAction[] }) {
  return (
    <div className="grid grid-cols-2 gap-2">
      {actions.map((a) => (
        <button
          key={a.label}
          className="group rounded-lg border bg-card p-3 text-left transition-all hover:border-primary/40 hover:shadow-sm"
        >
          <div className="flex items-center gap-2">
            <div className="h-7 w-7 rounded-md bg-gradient-to-br from-primary/15 to-accent/10 grid place-items-center text-primary group-hover:scale-105 transition-transform">
              <a.icon className="h-3.5 w-3.5" />
            </div>
            <div className="text-xs font-semibold">{a.label}</div>
          </div>
          <p className="mt-1.5 text-[10px] text-muted-foreground leading-relaxed">
            {a.description}
          </p>
        </button>
      ))}
    </div>
  );
}

/* ---------------- Page Header ---------------- */
export function DashboardHeader({
  eyebrow,
  title,
  subtitle,
  actions,
}: {
  eyebrow?: ReactNode;
  title: string;
  subtitle?: string;
  actions?: ReactNode;
}) {
  return (
    <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
      <div className="min-w-0">
        {eyebrow && (
          <div className="flex items-center gap-2 text-xs text-muted-foreground">{eyebrow}</div>
        )}
        <h1 className="mt-1 text-2xl font-semibold tracking-tight">{title}</h1>
        {subtitle && <p className="text-sm text-muted-foreground">{subtitle}</p>}
      </div>
      {actions && <div className="flex items-center gap-2 flex-wrap">{actions}</div>}
    </div>
  );
}
