"use client";

import { cn } from "@/lib/utils";
import type { OrderStatus, RecentOrderDto } from "../dtos/dashboard.dto";

interface RecentOrdersProps {
  orders: RecentOrderDto[];
  isLoading?: boolean;
}

function StatusBadge({ status }: { status: OrderStatus }) {
  const styles: Record<OrderStatus, string> = {
    pending:
      "bg-yellow-50 text-yellow-700 border-yellow-200",
    processing:
      "bg-blue-50 text-blue-700 border-blue-200",
    dispatched:
      "bg-purple-50 text-purple-700 border-purple-200",
    delivered:
      "bg-green-50 text-green-700 border-green-200",
  };

  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize",
        styles[status]
      )}
    >
      {status}
    </span>
  );
}

function formatCurrency(amount: number): string {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 0,
  }).format(amount);
}

function formatRelativeTime(isoDate: string | null): string {
  if (!isoDate || Number.isNaN(Date.parse(isoDate))) return "Date unavailable";
  const date = new Date(isoDate);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMins / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffMins < 1) return "Just now";
  if (diffMins < 60) return `${diffMins}m ago`;
  if (diffHours < 24) return `${diffHours}h ago`;
  return `${diffDays}d ago`;
}

function SkeletonTable() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-4 rounded-lg border border-gray-100 bg-gray-50 p-3"
        >
          <div className="h-4 w-20 animate-pulse rounded bg-gray-200" />
          <div className="h-4 w-28 animate-pulse rounded bg-gray-200" />
          <div className="h-4 w-24 animate-pulse rounded bg-gray-200" />
          <div className="ml-auto h-4 w-16 animate-pulse rounded bg-gray-200" />
        </div>
      ))}
    </div>
  );
}

export function RecentOrders({ orders, isLoading = false }: RecentOrdersProps) {
  return (
    <div className="rounded-xl border border-gray-200/80 bg-white p-6 shadow-sm">
      <div className="mb-4 flex items-center justify-between">
        <h2 className="text-base font-semibold text-navy-900">Recent Orders</h2>
        <span className="text-xs text-gray-400">
          Showing {orders.length} most recent
        </span>
      </div>

      {isLoading ? (
        <SkeletonTable />
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-200 text-left">
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Order ID
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Customer
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Product
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Company
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Status
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Amount
                </th>
                <th className="pb-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                  Date
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {orders.map((order) => (
                <tr
                  key={order.orderId}
                  className="transition-colors hover:bg-gray-50"
                >
                  <td className="py-3 pr-4 text-sm font-mono text-gray-500">
                    {order.orderId.slice(0, 8)}
                  </td>
                  <td className="py-3 pr-4 text-sm font-medium text-navy-900">
                    {order.customerName}
                  </td>
                  <td className="py-3 pr-4 text-sm text-gray-600">
                    {order.productName}
                  </td>
                  <td className="py-3 pr-4 text-sm text-gray-600">
                    {order.companyName}
                  </td>
                  <td className="py-3 pr-4">
                    <StatusBadge status={order.status} />
                  </td>
                  <td className="py-3 pr-4 text-sm font-medium text-navy-900">
                    {formatCurrency(order.totalAmount)}
                  </td>
                  <td className="py-3 text-xs text-gray-400">
                    {formatRelativeTime(order.createdAt)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
