"use client";

import { Card, Chip, Button } from "@heroui/react";
import { formatPrice } from "@repo/utils";
import { ORDER_STATUS_CONFIG, PAYMENT_STATUS_CONFIG } from "@/lib/orders";
import type { OrderSummary } from "@/lib/orders";

interface Props {
  order: OrderSummary;
  onViewDetails: (orderId: string) => void;
}

function formatTimestamp(ts: number): string {
  return new Intl.DateTimeFormat("en-GB", {
    year: "numeric",
    month: "short",
    day: "numeric",
  }).format(new Date(ts));
}

export function OrderCard({ order, onViewDetails }: Props) {
  const statusCfg = ORDER_STATUS_CONFIG[order.status];
  const paymentCfg = PAYMENT_STATUS_CONFIG[order.paymentStatus];

  return (
    <article>
      <Card className="w-full rounded-xl p-5">
        <Card.Header className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
          <h3 className="font-[family-name:var(--font-fraunces)] text-base font-semibold text-[#1a2e2d] md:text-lg">
            {order.orderNumber}
          </h3>
          <div className="flex flex-wrap gap-2">
            <Chip
              size="sm"
              variant="soft"
              className={statusCfg.colorClass}
            >
              {statusCfg.label}
            </Chip>
            <Chip
              size="sm"
              variant="soft"
              className={paymentCfg.colorClass}
            >
              {paymentCfg.label}
            </Chip>
          </div>
        </Card.Header>

        <Card.Content className="space-y-1 text-sm text-[#1a2e2d]/70">
          <p>
            <span className="font-medium text-[#1a2e2d]">Placed:</span>{" "}
            {formatTimestamp(order.createdAt)}
          </p>
          <p>
            <span className="font-medium text-[#1a2e2d]">Ship to:</span>{" "}
            {order.shippingAddressSnapshot.city},{" "}
            {order.shippingAddressSnapshot.country}
          </p>
          {order.carrier && (
            <p>
              <span className="font-medium text-[#1a2e2d]">Carrier:</span>{" "}
              {order.carrier}
              {order.shippingMethod ? ` · ${order.shippingMethod}` : ""}
            </p>
          )}
          <p className="pt-1 text-base font-semibold text-[#236f6b]">
            {formatPrice(order.total, order.currency)}
          </p>
        </Card.Content>

        <Card.Footer>
          <Button
            variant="outline"
            size="sm"
            onPress={() => onViewDetails(order._id)}
          >
            View Details
          </Button>
        </Card.Footer>
      </Card>
    </article>
  );
}
