"use client";

import Link from "next/link";
import { useMemo } from "react";
import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";

import { PlayerPanel } from "@/components/layout/player-panel";
import { OrderMetaLine } from "@/features/orders/order-meta-line";
import { StatusDot, ticketStatusDisplay } from "@/features/orders/ticket-item-status";
import {
  loadPersistedOrderGroup,
  ticketDetailHref,
  type TicketItemGroup,
} from "@/features/orders/group-ticket-items";
import { useActivePlayerCurrency } from "@/hooks/use-active-player-currency";
import { useCurrencyCatalog } from "@/hooks/use-currency-catalog";
import { formatMinorAsCurrency } from "@/lib/money";
import { isCreditFundingPlayer } from "@/lib/player-funding-mode";
import { playLabel } from "@/lib/play-labels";
import { cn } from "@/lib/utils";
import { usePlayerSessionStore } from "@/stores/player-session-store";

type TicketOrderGroupScreenProps = {
  groupKey: string;
};

export function TicketOrderGroupScreen({ groupKey }: TicketOrderGroupScreenProps) {
  const { t } = useTranslation("player");
  const { activeCurrency } = useActivePlayerCurrency();
  const creditMode = isCreditFundingPlayer(usePlayerSessionStore((state) => state.profile));
  useCurrencyCatalog();

  const decodedKey = decodeURIComponent(groupKey);

  const group = useMemo(
    (): TicketItemGroup | null => loadPersistedOrderGroup(decodedKey),
    [decodedKey],
  );

  if (!group) {
    return (
      <PlayerPanel
        title={t("orders.groupDetail")}
        backHref="/orders"
        backLabel={t("orders.title")}
      >
        <div className="rounded-xl border border-dashed border-[#dce7f7] bg-[#f8fbff] px-3 py-8 text-center">
          <p className="text-sm font-bold text-slate-700">{t("orders.groupNotFound")}</p>
          <Link
            href="/orders"
            className="mt-4 inline-flex h-9 items-center rounded-lg bg-[#07459f] px-4 text-sm font-bold text-white"
          >
            {t("orders.backToOrders")}
          </Link>
        </div>
      </PlayerPanel>
    );
  }

  const cur = group.currency_code ?? activeCurrency;
  const st = ticketStatusDisplay(
    group.status,
    group.win_amount,
    group.jackpot_win_amount,
    t,
    creditMode,
  );
  const totalWin = group.win_amount + group.jackpot_win_amount;
  return (
    <PlayerPanel
      title={t("orders.groupDetail")}
      backHref="/orders"
      backLabel={t("orders.title")}
    >
      <div className="space-y-3">
        <div className="rounded-xl border border-[#e5edf8] bg-white p-3 shadow-[0_8px_24px_rgba(15,23,42,0.05)]">
          <div className="flex items-start justify-between gap-3">
            <p className="truncate font-mono text-lg font-black text-[#0b3f96]">
              {group.draw_no ?? "—"}
            </p>
            <StatusDot label={st.label} dotClass={st.dotClass} ring={st.ring} />
          </div>
          <OrderMetaLine orderNo={group.order_no} placedAt={group.placed_at} t={t} />
          <p className="mt-2 text-[11px] font-bold uppercase tracking-wide text-[#7890b8]">
            {t("orders.itemCount", { count: group.items.length })}
          </p>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <div className="rounded-lg bg-[#f8fbff] px-3 py-2">
              <p className="text-[10px] font-bold uppercase text-[#7890b8]">{t("orders.stake")}</p>
              <p className="mt-1 text-sm font-black text-slate-900">
                {formatMinorAsCurrency(group.total_bet_amount, cur)}
              </p>
            </div>
            <div className="rounded-lg bg-[#f8fbff] px-3 py-2">
              <p className="text-[10px] font-bold uppercase text-[#7890b8]">{t("orders.deduction")}</p>
              <p className="mt-1 text-sm font-black text-[#0b3f96]">
                {formatMinorAsCurrency(group.actual_deduct_amount, cur)}
              </p>
            </div>
          </div>
          {group.status === "partial_failed" ? (
            <p className="mt-2 text-xs font-bold text-amber-700">
              {t("orders.partialFailedHint")}
            </p>
          ) : null}
          {totalWin > 0 && group.status === "settled_win" ? (
            <p className="mt-2 text-xs font-bold text-emerald-600">
              {t("orders.win", { amount: formatMinorAsCurrency(totalWin, cur) })}
            </p>
          ) : null}
        </div>

        <p className="px-0.5 text-sm font-black text-[#0b3f96]">{t("orders.betItems")}</p>
        <div className="space-y-2">
          {group.items.map((row, index) => {
            const lineCur = row.currency_code ?? cur;
            const lineSt = ticketStatusDisplay(
              row.status,
              row.win_amount,
              row.jackpot_win_amount,
              t,
              creditMode,
            );
            const lineWin = row.win_amount + row.jackpot_win_amount;
            return (
              <Link
                key={row.ticket_no}
                href={ticketDetailHref(row.ticket_no, group)}
                aria-label={t("orders.viewBetLine")}
                className={cn(
                  "flex items-center gap-3 rounded-xl border border-[#e5edf8] bg-white px-3 py-3",
                  "shadow-[0_6px_18px_rgba(15,23,42,0.04)] transition-colors hover:border-[#b9ccf6]",
                )}
              >
                <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-[#eaf2ff] text-xs font-black text-[#0b56b7]">
                  {index + 1}
                </span>
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-black text-[#0b3f96]">
                    {playLabel(row.play_code, t)} · {row.original_number ?? row.play_code}
                  </p>
                  <p className="mt-0.5 truncate font-mono text-[11px] text-slate-500">
                    {t("orders.ticketNo", { ticketNo: row.ticket_no })}
                  </p>
                  <div className="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-slate-600">
                    <span>
                      {t("orders.stake")}{" "}
                      <span className="font-bold tabular-nums text-slate-900">
                        {formatMinorAsCurrency(row.total_bet_amount, lineCur)}
                      </span>
                    </span>
                    <span>
                      {t("orders.deduction")}{" "}
                      <span className="font-bold tabular-nums text-[#0b3f96]">
                        {formatMinorAsCurrency(row.actual_deduct_amount, lineCur)}
                      </span>
                    </span>
                  </div>
                  {row.status === "failed" || row.status === "refunded" ? (
                    <p className="mt-1 text-xs font-bold text-red-600">
                      {t("orders.lineFailedTitle")}
                    </p>
                  ) : null}
                  {lineWin > 0 && row.status === "settled_win" ? (
                    <p className="mt-1 text-xs font-bold text-emerald-600">
                      {t("orders.win", { amount: formatMinorAsCurrency(lineWin, lineCur) })}
                    </p>
                  ) : null}
                </div>
                <div className="flex shrink-0 flex-col items-end gap-1">
                  <StatusDot label={lineSt.label} dotClass={lineSt.dotClass} ring={lineSt.ring} />
                  <ChevronRight className="size-4 text-[#7890b8]" />
                </div>
              </Link>
            );
          })}
        </div>
      </div>
    </PlayerPanel>
  );
}
