"use client";

import Link from "next/link";
import {
  RiMoneyDollarCircleLine,
  RiShoppingBagLine,
  RiStoreLine,
  RiUserLine,
  RiArrowRightLine,
} from "@remixicon/react";
import type { DashboardStats } from "@/lib/actions/dashboard";

function formatCurrency(amount: number): string {
  return `৳${amount.toLocaleString("en-BD", { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

const STATUS_COLORS: Record<string, string> = {
  pending: "bg-yellow-100 text-yellow-800",
  processing: "bg-blue-100 text-blue-800",
  shipped: "bg-purple-100 text-purple-800",
  delivered: "bg-green-100 text-green-800",
  cancelled: "bg-red-100 text-red-800",
};

export default function DashboardClient({ stats }: { stats: DashboardStats }) {
  const statCards = [
    {
      label: "Total Orders",
      value: stats.totalOrders.toLocaleString(),
      icon: RiShoppingBagLine,
      color: "text-blue-600",
      bg: "bg-blue-50",
    },
    {
      label: "Total Revenue",
      value: formatCurrency(stats.totalRevenue),
      icon: RiMoneyDollarCircleLine,
      color: "text-green-600",
      bg: "bg-green-50",
    },
    {
      label: "Active Products",
      value: stats.totalProducts.toLocaleString(),
      icon: RiStoreLine,
      color: "text-purple-600",
      bg: "bg-purple-50",
    },
    {
      label: "Customers",
      value: stats.totalCustomers.toLocaleString(),
      icon: RiUserLine,
      color: "text-orange-600",
      bg: "bg-orange-50",
    },
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Dashboard</h1>
        <p className="text-muted-foreground">
          Overview of your store&apos;s performance.
        </p>
      </div>

      {/* Stat Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {statCards.map((card) => (
          <div
            key={card.label}
            className="rounded-xl border bg-card p-6 shadow-sm"
          >
            <div className="flex items-center justify-between">
              <p className="text-sm font-medium text-muted-foreground">
                {card.label}
              </p>
              <div className={`rounded-lg p-2 ${card.bg}`}>
                <card.icon className={`h-5 w-5 ${card.color}`} />
              </div>
            </div>
            <p className="mt-2 text-2xl font-bold">{card.value}</p>
          </div>
        ))}
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Recent Orders */}
        <div className="lg:col-span-2 rounded-xl border bg-card shadow-sm">
          <div className="flex items-center justify-between border-b p-4">
            <h2 className="font-semibold">Recent Orders</h2>
            <Link
              href="/admin/dashboard/orders"
              className="flex items-center gap-1 text-sm text-primary hover:underline"
            >
              View all <RiArrowRightLine className="h-4 w-4" />
            </Link>
          </div>
          <div className="divide-y">
            {stats.recentOrders.length === 0 ? (
              <p className="p-6 text-center text-sm text-muted-foreground">
                No orders yet.
              </p>
            ) : (
              stats.recentOrders.map((order) => (
                <div
                  key={order.id}
                  className="flex items-center justify-between p-4"
                >
                  <div className="space-y-1">
                    <p className="text-sm font-medium">{order.orderNumber}</p>
                    <p className="text-xs text-muted-foreground">
                      {order.customerName}
                    </p>
                  </div>
                  <div className="text-right space-y-1">
                    <p className="text-sm font-semibold">
                      {formatCurrency(order.grandTotal)}
                    </p>
                    <span
                      className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
                        STATUS_COLORS[order.status] ?? "bg-gray-100 text-gray-800"
                      }`}
                    >
                      {order.status}
                    </span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Top Products */}
        <div className="rounded-xl border bg-card shadow-sm">
          <div className="border-b p-4">
            <h2 className="font-semibold">Top Products</h2>
          </div>
          <div className="divide-y">
            {stats.topProducts.length === 0 ? (
              <p className="p-6 text-center text-sm text-muted-foreground">
                No product data yet.
              </p>
            ) : (
              stats.topProducts.map((product, i) => (
                <div key={i} className="p-4">
                  <p className="text-sm font-medium truncate">{product.name}</p>
                  <div className="mt-1 flex items-center justify-between text-xs text-muted-foreground">
                    <span>{product.unitsSold} sold</span>
                    <span>{formatCurrency(product.revenue)}</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* Revenue chart placeholder */}
      <div className="rounded-xl border bg-card shadow-sm p-6">
        <h2 className="font-semibold mb-4">Revenue (Last 7 Days)</h2>
        <div className="flex items-end gap-2 h-40">
          {stats.revenueLast7Days.map((day) => {
            const maxRevenue = Math.max(
              ...stats.revenueLast7Days.map((d) => d.revenue),
              1,
            );
            const height = Math.max(
              (day.revenue / maxRevenue) * 100,
              2,
            );
            return (
              <div key={day.date} className="flex-1 flex flex-col items-center gap-1">
                <span className="text-[10px] text-muted-foreground">
                  {formatCurrency(day.revenue)}
                </span>
                <div
                  className="w-full bg-primary rounded-t"
                  style={{ height: `${height}%` }}
                />
                <span className="text-[10px] text-muted-foreground">
                  {day.date.slice(5)}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Order Status Breakdown */}
      {Object.keys(stats.ordersByStatus).length > 0 && (
        <div className="rounded-xl border bg-card shadow-sm p-6">
          <h2 className="font-semibold mb-4">Order Status Breakdown</h2>
          <div className="flex flex-wrap gap-3">
            {Object.entries(stats.ordersByStatus).map(([status, count]) => (
              <div
                key={status}
                className="flex items-center gap-2 rounded-lg border px-4 py-2"
              >
                <span
                  className={`inline-block h-2 w-2 rounded-full ${
                    status === "pending"
                      ? "bg-yellow-500"
                      : status === "processing"
                        ? "bg-blue-500"
                        : status === "shipped"
                          ? "bg-purple-500"
                          : status === "delivered"
                            ? "bg-green-500"
                            : "bg-red-500"
                  }`}
                />
                <span className="text-sm capitalize">{status}</span>
                <span className="text-sm font-bold">{count}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
