"use client";

import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import { Loader2, ReceiptText, ChefHat, Printer } from "lucide-react";
import { apiGet, apiGetPaged, ApiClientError } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatCurrency, formatNumber } from "@/lib/format";
import { isoTodayTehran } from "@/lib/reports/analytics";
import { printReceipt, printKitchen } from "@/lib/api/print";
import { fetchKitchenStations } from "@/lib/api/kitchen-stations";
import type { Order } from "@/lib/api/types";
import { notify } from "@/lib/notify";
import { Button } from "@/components/ui/button";
import { JalaliDateField } from "@/components/ui/jalali-date-field";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent } from "@/components/ui/card";
import { PageHeader } from "@/components/layout/page-header";
import { cn } from "@/lib/utils";

type Branch = { id: string; name: string };

const PAGE_SIZE = 30;

export function RecentOrdersScreen() {
  const t = useTranslations("recentOrders");
  const tPrint = useTranslations("print");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);

  const [date, setDate] = useState<string>(() => isoTodayTehran());
  const [branchId, setBranchId] = useState<string>("");
  const [page, setPage] = useState(1);
  const [printing, setPrinting] = useState<string | null>(null);

  const { data: branches = [] } = useQuery({
    queryKey: ["branches", cafeId],
    queryFn: () => apiGet<Branch[]>(`/api/cafes/${cafeId}/branches`),
    enabled: !!cafeId,
  });

  const { data: stations = [] } = useQuery({
    queryKey: ["kitchen-stations", cafeId],
    queryFn: () => fetchKitchenStations(cafeId!),
    enabled: !!cafeId,
  });

  const queryString = useMemo(() => {
    const p = new URLSearchParams({ date, page: String(page), pageSize: String(PAGE_SIZE) });
    if (branchId) p.set("branchId", branchId);
    return p.toString();
  }, [date, branchId, page]);

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["recent-orders", cafeId, queryString],
    queryFn: () => apiGetPaged<Order>(`/api/cafes/${cafeId}/orders/closed?${queryString}`),
    enabled: !!cafeId,
  });

  const orders = data?.items ?? [];
  const total = data?.meta.total ?? 0;
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  const timeFmt = useMemo(
    () => new Intl.DateTimeFormat(numberLocale, { hour: "2-digit", minute: "2-digit", hour12: false }),
    [numberLocale]
  );

  const printErr = (e: unknown): string => {
    const code = e instanceof ApiClientError ? e.code : "";
    if (code === "PRINTER_NOT_CONFIGURED" || code === "KITCHEN_PRINTER_NOT_CONFIGURED")
      return tPrint("notConfigured");
    if (code === "NO_STATION_ITEMS") return tPrint("noStationItems");
    if (code === "PRINTER_CONNECTION_FAILED") return tPrint("connectionFailed");
    return tPrint("printFailed");
  };

  const run = async (key: string, fn: () => Promise<void>) => {
    setPrinting(key);
    try {
      await fn();
      notify.success(tPrint("sent"));
    } catch (e) {
      notify.error(printErr(e));
    } finally {
      setPrinting(null);
    }
  };

  if (!cafeId) return null;

  return (
    <div className="space-y-6">
      <PageHeader title={t("title")} subtitle={t("subtitle")} />

      <Card className="rounded-xl border border-border/80 bg-card">
        <CardContent className="flex flex-wrap items-end gap-4 pt-6">
          <LabeledField label={t("date")} htmlFor="ro-date">
            <JalaliDateField
              id="ro-date"
              className="w-40"
              value={date}
              onChange={(iso) => { setDate(iso); setPage(1); }}
            />
          </LabeledField>
          {branches.length > 1 ? (
            <LabeledField label={t("branch")} htmlFor="ro-branch">
              <select
                id="ro-branch"
                className="h-9 min-w-[10rem] rounded-md border border-input bg-background px-3 text-sm"
                value={branchId}
                onChange={(e) => { setBranchId(e.target.value); setPage(1); }}
              >
                <option value="">{t("allBranches")}</option>
                {branches.map((b) => (
                  <option key={b.id} value={b.id}>{b.name}</option>
                ))}
              </select>
            </LabeledField>
          ) : null}
        </CardContent>
      </Card>

      {isLoading ? (
        <div className="flex items-center justify-center py-12 text-muted-foreground">
          <Loader2 className="size-5 animate-spin" />
        </div>
      ) : isError ? (
        <div className="flex flex-col items-center gap-3 py-10 text-center text-sm text-muted-foreground">
          <p>{t("loadFailed")}</p>
          <Button variant="outline" size="sm" onClick={() => refetch()}>{t("retry")}</Button>
        </div>
      ) : orders.length === 0 ? (
        <p className="py-12 text-center text-sm text-muted-foreground">{t("empty")}</p>
      ) : (
        <div className="space-y-3">
          {orders.map((o) => {
            const cancelled = o.status === "Cancelled";
            const items = o.items.filter((i) => !i.isVoided);
            return (
              <Card key={o.id} className="rounded-xl border border-border/80">
                <CardContent className="space-y-3 p-4">
                  <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
                    <span className="font-semibold">#{formatNumber(o.displayNumber, numberLocale)}</span>
                    {o.tableNumber ? (
                      <span className="text-sm text-muted-foreground">{t("table")} {o.tableNumber}</span>
                    ) : null}
                    <span className="text-sm tabular-nums text-muted-foreground">
                      {timeFmt.format(new Date(o.createdAt))}
                    </span>
                    <span className={cn(
                      "rounded-full px-2 py-0.5 text-xs font-medium",
                      cancelled ? "bg-red-50 text-red-700" : "bg-emerald-50 text-emerald-700",
                    )}>
                      {cancelled ? t("statusCancelled") : t("statusPaid")}
                    </span>
                    <span className="ms-auto font-bold tabular-nums text-primary">
                      {formatCurrency(o.total, numberLocale)}
                    </span>
                  </div>

                  {items.length > 0 ? (
                    <p className="text-xs leading-relaxed text-muted-foreground">
                      {items.map((i) =>
                        `${formatNumber(i.quantity, numberLocale)}× ${i.menuItemName}${i.notes ? ` (${i.notes})` : ""}`
                      ).join(" · ")}
                    </p>
                  ) : null}

                  <div className="flex flex-wrap gap-2 border-t border-border/60 pt-3">
                    <Button
                      variant="outline" size="sm" className="gap-1.5"
                      disabled={printing === `${o.id}:receipt`}
                      onClick={() => run(`${o.id}:receipt`, () => printReceipt(cafeId, o.id))}
                    >
                      <ReceiptText className="size-3.5" /> {t("receipt")}
                    </Button>
                    <Button
                      variant="outline" size="sm" className="gap-1.5"
                      disabled={printing === `${o.id}:kitchen`}
                      onClick={() => run(`${o.id}:kitchen`, () => printKitchen(cafeId, o.id))}
                    >
                      <ChefHat className="size-3.5" /> {t("kitchen")}
                    </Button>
                    {stations.map((s) => (
                      <Button
                        key={s.id}
                        variant="ghost" size="sm" className="gap-1.5"
                        disabled={printing === `${o.id}:${s.id}`}
                        onClick={() => run(`${o.id}:${s.id}`, () => printKitchen(cafeId, o.id, s.id))}
                      >
                        <Printer className="size-3.5" /> {s.name}
                      </Button>
                    ))}
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {totalPages > 1 ? (
        <div className="flex items-center justify-center gap-3 pt-1">
          <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
            {t("prevPage")}
          </Button>
          <span className="text-xs tabular-nums text-muted-foreground">
            {formatNumber(page, numberLocale)} / {formatNumber(totalPages, numberLocale)}
          </span>
          <Button variant="outline" size="sm" disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>
            {t("nextPage")}
          </Button>
        </div>
      ) : null}
    </div>
  );
}
