import { useState, type ReactNode } from "react";
import { businesses } from "@/mocks/dshn";
import { orders, type Order } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import { Container, WBtn, WCard, StatusPill, cn, fmt } from "../WebUI";
import WebPageHeader from "../components/WebPageHeader";

type Tab = "new" | "current" | "done";

export default function Orders() {
  const { t, navigate } = useWeb();
  const [tab, setTab] = useState<Tab>("new");

  const tabs: { id: Tab; label: string }[] = [
    { id: "new", label: t("newOrders") },
    { id: "current", label: t("currentOrders") },
    { id: "done", label: t("doneOrders") },
  ];

  const list = orders.filter((o) => o.status === tab);

  return (
    <div className="animate-fade-in">
      <WebPageHeader title={t("myOrders")} crumb={t("myOrders")} />
      <Container className="py-8">
        <div className="flex items-center gap-2 mb-6 flex-wrap">
          {tabs.map((x) => {
            const count = orders.filter((o) => o.status === x.id).length;
            return (
              <button
                key={x.id}
                type="button"
                onClick={() => setTab(x.id)}
                className={cn(
                  "flex items-center gap-2 h-10 px-4 rounded-full text-[13.5px] font-semibold cursor-pointer transition-colors",
                  tab === x.id ? "bg-primary-500 text-background-50" : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
                )}
              >
                {x.label}
                <span className={cn("min-w-[20px] h-5 px-1.5 rounded-full text-[11px] font-bold flex items-center justify-center", tab === x.id ? "bg-background-50/25" : "bg-background-200 text-foreground-700")}>
                  {count}
                </span>
              </button>
            );
          })}
        </div>

        {list.length === 0 ? (
          <WCard className="py-16 text-center">
            <i className="ri-inbox-line text-[34px] text-foreground-400 leading-none" />
            <p className="text-[14px] text-foreground-600 mt-3">{t("empty")}</p>
          </WCard>
        ) : (
          <WCard className="overflow-hidden">
            <table className="w-full">
              <thead>
                <tr className="bg-background-50 border-b border-background-200">
                  <Th>{t("orderNumber")}</Th>
                  <Th>{t("business")}</Th>
                  <Th>المنتجات</Th>
                  <Th>{t("total")}</Th>
                  <Th>{t("status")}</Th>
                  <Th>{""}</Th>
                </tr>
              </thead>
              <tbody>
                {list.map((o) => (
                  <OrderRow key={o.id} order={o} onView={() => navigate("orderDetails", { orderId: o.id })} />
                ))}
              </tbody>
            </table>
          </WCard>
        )}
      </Container>
    </div>
  );
}

function Th({ children }: { children: ReactNode }) {
  return <th className="text-start text-[12.5px] font-bold text-foreground-600 px-5 py-3.5 whitespace-nowrap">{children}</th>;
}

function OrderRow({ order, onView }: { order: Order; onView: () => void }) {
  const { t } = useWeb();
  const biz = businesses.find((b) => b.id === order.businessId);
  return (
    <tr className="border-b border-background-200 last:border-0 hover:bg-background-50 transition-colors">
      <td className="px-5 py-4">
        <button type="button" onClick={onView} className="text-[14px] font-bold text-foreground-950 hover:underline cursor-pointer">#{order.number}</button>
      </td>
      <td className="px-5 py-4">
        <div className="flex items-center gap-3">
          <div className="w-9 h-9 rounded-full overflow-hidden bg-background-200 shrink-0">
            {biz && <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />}
          </div>
          <span className="text-[13.5px] text-foreground-800">{biz?.name}</span>
        </div>
      </td>
      <td className="px-5 py-4">
        <div className="flex items-center gap-2">
          <div className="flex -space-x-2 rtl:space-x-reverse">
            {order.items.slice(0, 3).map((i) => (
              <span key={i.productId} className="w-8 h-8 rounded-full overflow-hidden border-2 border-background-100 bg-background-200">
                <img src={i.image} alt={i.name} className="w-full h-full object-cover object-top" />
              </span>
            ))}
          </div>
          <span className="text-[12.5px] text-foreground-600">{order.itemsCount} {t("productCount")}</span>
        </div>
      </td>
      <td className="px-5 py-4 text-[13.5px] font-bold text-foreground-950 whitespace-nowrap">{fmt(order.total)} ر.س</td>
      <td className="px-5 py-4">
        <StatusPill tone={order.statusTone}>{order.statusLabel}</StatusPill>
      </td>
      <td className="px-5 py-4 text-end">
        <WBtn size="sm" variant="secondary" onClick={onView}>{t("viewDetails")}</WBtn>
      </td>
    </tr>
  );
}