"use client";
import { motion } from "framer-motion";
import {
  Package,
  CheckCircle,
  Truck,
  Home,
  ClipboardList,
  Star,
  XCircle,
  AlertTriangle,
  ShieldAlert,
  type LucideProps,
} from "lucide-react";
import type { TimelineEvent, OrderStatus } from "./types";
import { formatOrderDate, formatOrderTime } from "./mockData";

const STATUS_ICONS: Record<string, React.ForwardRefExoticComponent<Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>>> = {
  placed: ClipboardList,
  confirmed: CheckCircle,
  packed: Package,
  shipped: Truck,
  out_for_delivery: Truck,
  delivered: Home,
  completed: Star,
  cancelled: XCircle,
  disputed: ShieldAlert,
};

const STATUS_COLORS: Record<string, { dot: string; line: string; icon: string }> = {
  placed: { dot: "#60a5fa", line: "#60a5fa40", icon: "#60a5fa" },
  confirmed: { dot: "#fb923c", line: "#fb923c40", icon: "#fb923c" },
  packed: { dot: "#a78bfa", line: "#a78bfa40", icon: "#a78bfa" },
  shipped: { dot: "#f0c040", line: "#f0c04040", icon: "#f0c040" },
  out_for_delivery: { dot: "#f97316", line: "#f9731640", icon: "#f97316" },
  delivered: { dot: "#22c55e", line: "#22c55e40", icon: "#22c55e" },
  completed: { dot: "#22c55e", line: "#22c55e40", icon: "#22c55e" },
  cancelled: { dot: "#6b7280", line: "#6b728040", icon: "#6b7280" },
  disputed: { dot: "#f87171", line: "#f8717140", icon: "#f87171" },
};

const UPCOMING_PIPELINE: OrderStatus[] = [
  "placed",
  "confirmed",
  "packed",
  "shipped",
  "out_for_delivery",
  "delivered",
  "completed",
];

interface Props {
  timeline: TimelineEvent[];
  currentStatus: OrderStatus;
  showUpcoming?: boolean;
}

export function OrderTimeline({ timeline, currentStatus, showUpcoming = true }: Props) {
  const currentIdx = UPCOMING_PIPELINE.indexOf(currentStatus);
  const isTerminal = ["cancelled", "disputed"].includes(currentStatus);

  // Build full list: completed events + upcoming steps
  const completedStatuses = new Set(timeline.map((e) => e.status));

  const upcomingSteps: OrderStatus[] = isTerminal
    ? []
    : UPCOMING_PIPELINE.slice(currentIdx + 1).filter((s) => !completedStatuses.has(s));

  return (
    <div className="relative">
      {/* Completed events */}
      {timeline.map((event, i) => {
        const Icon = STATUS_ICONS[event.status] ?? CheckCircle;
        const colors = STATUS_COLORS[event.status] ?? STATUS_COLORS.placed;
        const isLast = i === timeline.length - 1 && upcomingSteps.length === 0;

        return (
          <motion.div
            key={`${event.status}-${i}`}
            initial={{ opacity: 0, x: -16 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: i * 0.08, type: "spring", stiffness: 300, damping: 28 }}
            className="flex gap-4 relative"
          >
            {/* Line */}
            {!isLast && (
              <div
                className="absolute left-[19px] top-10 bottom-0 w-0.5"
                style={{ background: colors.line, minHeight: 24 }}
              />
            )}

            {/* Node */}
            <div className="relative shrink-0 z-10">
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ delay: i * 0.08 + 0.1, type: "spring", stiffness: 400, damping: 20 }}
                className="w-10 h-10 rounded-full flex items-center justify-center border-2"
                style={{
                  background: `${colors.dot}20`,
                  borderColor: colors.dot,
                }}
              >
                <Icon size={16} style={{ color: colors.icon }} />
              </motion.div>
            </div>

            {/* Content */}
            <div className="flex-1 pb-6">
              <div className="flex items-start justify-between gap-2 mb-0.5">
                <p className="text-sm font-bold text-[var(--text-primary)]">
                  {event.status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())}
                </p>
                <div className="text-right shrink-0">
                  <p className="text-[10px] text-[var(--text-muted)]">{formatOrderDate(event.timestamp)}</p>
                  <p className="text-[10px] text-[var(--text-muted)]">{formatOrderTime(event.timestamp)}</p>
                </div>
              </div>
              <p className="text-xs text-[var(--text-muted)] leading-relaxed">{event.description}</p>
              <span
                className="mt-1.5 inline-block text-[9px] px-2 py-0.5 rounded-full font-medium"
                style={{ background: "rgba(255,255,255,0.05)", color: "var(--text-muted)" }}
              >
                By {event.actor}
              </span>
            </div>
          </motion.div>
        );
      })}

      {/* Upcoming steps */}
      {showUpcoming &&
        upcomingSteps.map((status, i) => {
          const Icon = STATUS_ICONS[status] ?? CheckCircle;
          const isLastUpcoming = i === upcomingSteps.length - 1;

          return (
            <div key={status} className="flex gap-4 relative opacity-35">
              {!isLastUpcoming && (
                <div
                  className="absolute left-[19px] top-10 bottom-0 w-0.5"
                  style={{ background: "rgba(255,255,255,0.08)", minHeight: 24 }}
                />
              )}
              <div className="relative shrink-0 z-10">
                <div
                  className="w-10 h-10 rounded-full flex items-center justify-center border-2"
                  style={{ background: "rgba(255,255,255,0.03)", borderColor: "var(--border)" }}
                >
                  <Icon size={16} className="text-[var(--text-muted)]" />
                </div>
              </div>
              <div className="flex-1 pb-6">
                <p className="text-sm font-semibold text-[var(--text-muted)]">
                  {status.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())}
                </p>
                <p className="text-xs text-[var(--text-muted)] opacity-60 mt-0.5">Waiting for update…</p>
              </div>
            </div>
          );
        })}
    </div>
  );
}

// ─── Mini progress bar for order cards ───────────────────────────────────────
export function OrderProgressBar({ status }: { status: string }) {
  const steps = ["placed", "confirmed", "packed", "shipped", "delivered", "completed"];
  const currentStep = steps.indexOf(status);
  const pct = currentStep < 0 ? 0 : Math.round((currentStep / (steps.length - 1)) * 100);
  const isTerminal = ["cancelled", "disputed"].includes(status);

  if (isTerminal) {
    return (
      <div className="flex items-center gap-2">
        <div className="flex-1 h-1 rounded-full" style={{ background: "rgba(255,255,255,0.08)" }}>
          <div className="h-full rounded-full w-full" style={{ background: status === "cancelled" ? "#6b7280" : "#f87171" }} />
        </div>
        <span className="text-[9px] font-medium shrink-0" style={{ color: status === "cancelled" ? "#6b7280" : "#f87171" }}>
          {status === "cancelled" ? "Cancelled" : "Disputed"}
        </span>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-1.5 rounded-full overflow-hidden" style={{ background: "rgba(255,255,255,0.08)" }}>
        <motion.div
          initial={{ width: 0 }}
          animate={{ width: `${pct}%` }}
          transition={{ duration: 0.8, ease: [0.16, 1, 0.3, 1] }}
          className="h-full rounded-full"
          style={{ background: "linear-gradient(90deg, var(--accent), #f0c040)" }}
        />
      </div>
      <span className="text-[9px] font-medium text-[var(--accent)] shrink-0">{pct}%</span>
    </div>
  );
}
