import { CheckCircle2, Circle, ExternalLink, Loader2, RotateCcw, Truck } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { useT } from "@/lib/i18n";
import { useCartStore } from "@/stores/cartStore";
import { wc, type WcOrder } from "@/lib/woocommerce";
import {
  currentStage,
  extractOrderTracking,
  shippingSteps,
  UNKNOWN_CARRIER_LABEL,
  type OrderTracking as OrderTrackingInfo,
} from "@/lib/tracking";

/**
 * Shipping progress + track & trace for one order in the customer account.
 *
 * The tracking code is read from the order meta or the customer note (see
 * src/lib/tracking.ts) — never from internal order notes.
 */
export function OrderShippingStatus({ order }: { order: WcOrder }) {
  const t = useT();
  const tracking = extractOrderTracking(order);
  const steps = shippingSteps(order, tracking);
  const stage = currentStage(steps);

  const labels: Record<string, [string, string]> = {
    ordered: ["Besteld", "Ordered"],
    shipped: ["Verzonden", "Shipped"],
    delivered: ["Geleverd", "Delivered"],
  };

  return (
    <div className="rounded-2xl border border-border/60 bg-muted/20 px-4 py-3.5">
      <ol className="flex items-center gap-2">
        {steps.map((step, index) => (
          <li key={step.key} className="flex-1 flex items-center gap-2 min-w-0">
            <span className="flex items-center gap-1.5 min-w-0">
              {step.done ? (
                <CheckCircle2 className="w-4 h-4 shrink-0 text-primary" />
              ) : (
                <Circle className="w-4 h-4 shrink-0 text-muted-foreground/50" />
              )}
              <span
                className={`text-[11px] font-semibold uppercase tracking-wide truncate ${
                  step.done ? "text-foreground" : "text-muted-foreground/60"
                }`}
              >
                {t(...labels[step.key])}
              </span>
            </span>
            {index < steps.length - 1 && (
              <span
                aria-hidden="true"
                className={`hidden sm:block h-px flex-1 ${steps[index + 1].done ? "bg-primary/50" : "bg-border"}`}
              />
            )}
          </li>
        ))}
      </ol>

      {tracking && (
        <div className="mt-3 flex flex-wrap items-center gap-2">
          {tracking.url ? (
            <a
              href={tracking.url}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 gradient-primary text-white font-bold px-4 py-2 rounded-xl text-xs"
            >
              <Truck className="w-3.5 h-3.5" />
              {t("Volg je zending", "Track your shipment")}
              <span className="font-semibold opacity-80">
                · {tracking.carrier?.label ?? UNKNOWN_CARRIER_LABEL}
              </span>
              <ExternalLink className="w-3 h-3" />
            </a>
          ) : (
            <span className="inline-flex items-center gap-2 text-xs font-semibold text-muted-foreground">
              <Truck className="w-3.5 h-3.5" />
              {t("Track & trace", "Track & trace")}:{" "}
              <code className="font-mono">{tracking.code}</code>
            </span>
          )}

          {stage === "shipped" && (
            <span className="text-[11px] text-muted-foreground">
              {t("Je pakket is onderweg.", "Your parcel is on its way.")}
            </span>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * Puts the same products back in the cart. Product data is re-fetched per line
 * item so the cart gets a real slug/image/price instead of a guess.
 */
export function ReorderButton({ items }: { items: WcOrder["line_items"] }) {
  const t = useT();
  const { addItem } = useCartStore();
  const [loading, setLoading] = useState(false);

  const reorder = async () => {
    if (items.length === 0) return;

    setLoading(true);
    let added = 0;

    try {
      for (const item of items) {
        try {
          const { data: product } = await wc.getProduct(item.product_id);
          const quantity = Math.max(1, Number(item.quantity) || 1);

          for (let i = 0; i < quantity; i += 1) {
            addItem({
              id: product.id,
              name: product.name,
              price: Number.parseFloat(product.price || product.regular_price || "0") || 0,
              salePrice: product.on_sale
                ? Number.parseFloat(product.sale_price) || undefined
                : undefined,
              image: product.images?.[0]?.src ?? "",
              slug: product.slug,
            });
          }

          added += 1;
        } catch {
          // Product removed or unpublished: skip it and report at the end.
        }
      }

      if (added > 0) {
        toast.success(t("Toegevoegd aan je winkelmand", "Added to your cart"));
      } else {
        toast.error(
          t("Deze producten zijn niet meer beschikbaar", "These products are no longer available"),
        );
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      type="button"
      onClick={reorder}
      disabled={loading}
      className="inline-flex items-center gap-2 border border-border rounded-xl px-4 py-2 text-xs font-bold hover:border-primary/50 transition-colors disabled:opacity-50"
    >
      {loading ? (
        <Loader2 className="w-3.5 h-3.5 animate-spin" />
      ) : (
        <RotateCcw className="w-3.5 h-3.5" />
      )}
      {t("Opnieuw bestellen", "Order again")}
    </button>
  );
}

export type { OrderTrackingInfo };
