"use client";

import { lazy, Suspense, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import {
  TrendingUp,
  TrendingDown,
  Minus,
  ShoppingBag,
  CreditCard,
  Utensils,
  BarChart3,
  ArrowRight,
  ArrowLeft,
  ChefHat,
  TableProperties,
} from "lucide-react";
import { Link } from "@/i18n/routing";
import { apiGet } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useLiveClock } from "@/lib/hooks/use-live-clock";
import {
  addDaysIso,
  isoTodayTehran,
  percentChange,
  revenueChartPoints,
  sumSnapshots,
  topProductsFromRange,
  type DailyReportSnapshot,
} from "@/lib/reports/analytics";
import { fetchCafeTableBoard } from "@/lib/api/branch-tables";
import { formatCurrency, formatNumber } from "@/lib/format";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Card } from "@/components/ui/card";

const LazyMiniChart = lazy(() =>
  import("@/components/overview/overview-mini-chart").then((m) => ({
    default: m.OverviewMiniChart,
  }))
);

function KpiValue({
  value,
  loading,
  currency = false,
  locale = "fa-IR",
}: {
  value: number | null;
  loading: boolean;
  currency?: boolean;
  locale?: string;
}) {
  if (loading) return <Skeleton className="h-7 w-28 mt-1" />;
  if (value === null) return <span className="text-2xl font-bold text-muted-foreground">—</span>;
  return (
    <span className="text-2xl font-bold text-foreground tabular-nums">
      {currency ? formatCurrency(value, locale) : formatNumber(value, locale)}
    </span>
  );
}

function TrendBadge({ delta, label }: { delta: number | null; label: string }) {
  if (delta === null) return null;
  const up = delta > 0;
  const flat = delta === 0;
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium",
        up
          ? "bg-green-100 text-green-700"
          : flat
          ? "bg-muted text-muted-foreground"
          : "bg-red-100 text-red-600"
      )}
    >
      {up ? (
        <TrendingUp className="h-3 w-3" />
      ) : flat ? (
        <Minus className="h-3 w-3" />
      ) : (
        <TrendingDown className="h-3 w-3" />
      )}
      {Math.abs(delta).toFixed(1)}%
      <span className="text-muted-foreground">{label}</span>
    </span>
  );
}

export function OverviewScreen() {
  const t = useTranslations("overview");
  const tNav = useTranslations("nav");
  const locale = useLocale();
  const rtl = locale !== "en";
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const ArrowIcon = rtl ? ArrowLeft : ArrowRight;

  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const branchId = useAuthStore((s) => s.user?.branchId ?? null);
  const role = useAuthStore((s) => s.user?.role);

  const clock = useLiveClock(10_000);

  const today = useMemo(() => isoTodayTehran(), []);
  const sevenDaysAgo = useMemo(() => addDaysIso(today, -6), [today]);
  const yesterday = useMemo(() => addDaysIso(today, -1), [today]);

  const timeStr = clock.toLocaleTimeString(
    locale === "fa" ? "fa-IR" : locale === "ar" ? "ar-SA" : "en-US",
    { hour: "2-digit", minute: "2-digit", timeZone: "Asia/Tehran" }
  );
  const dateStr = clock.toLocaleDateString(
    locale === "fa" ? "fa-IR-u-ca-persian" : locale === "ar" ? "ar-SA" : "en-GB",
    { weekday: "long", year: "numeric", month: "long", day: "numeric", timeZone: "Asia/Tehran" }
  );

  const { data: weekSnapshots = [], isLoading } = useQuery({
    queryKey: ["overview-week", cafeId, today],
    queryFn: () =>
      apiGet<DailyReportSnapshot[]>(
        `/api/cafes/${cafeId}/reports/daily/range?from=${sevenDaysAgo}&to=${today}`
      ),
    enabled: !!cafeId,
    staleTime: 60_000,
  });

  const { data: prevSnapshots = [] } = useQuery({
    queryKey: ["overview-yesterday", cafeId, yesterday],
    queryFn: () =>
      apiGet<DailyReportSnapshot[]>(
        `/api/cafes/${cafeId}/reports/daily/range?from=${yesterday}&to=${yesterday}`
      ),
    enabled: !!cafeId,
    staleTime: 300_000,
  });

  const { data: tables = [] } = useQuery({
    queryKey: ["overview-tables", cafeId, branchId],
    queryFn: () => fetchCafeTableBoard(cafeId!, branchId),
    enabled: !!cafeId,
    staleTime: 30_000,
    refetchInterval: 30_000,
  });

  const todaySnapshot = useMemo(
    () => weekSnapshots.find((s) => s.date === today) ?? null,
    [weekSnapshots, today]
  );
  const todayTotals = useMemo(
    () => (todaySnapshot ? sumSnapshots([todaySnapshot]) : null),
    [todaySnapshot]
  );
  const yesterdayTotals = useMemo(
    () => (prevSnapshots.length > 0 ? sumSnapshots(prevSnapshots) : null),
    [prevSnapshots]
  );

  const revenueDelta = useMemo(
    () => todayTotals && yesterdayTotals
        ? percentChange(todayTotals.totalRevenue, yesterdayTotals.totalRevenue)
        : null,
    [todayTotals, yesterdayTotals]
  );
  const ordersDelta = useMemo(
    () => todayTotals && yesterdayTotals
        ? percentChange(todayTotals.totalOrders, yesterdayTotals.totalOrders)
        : null,
    [todayTotals, yesterdayTotals]
  );
  const netIncomeDelta = useMemo(
    () => todayTotals && yesterdayTotals
        ? percentChange(todayTotals.netIncome, yesterdayTotals.netIncome)
        : null,
    [todayTotals, yesterdayTotals]
  );

  const chartPoints = useMemo(
    () => revenueChartPoints(weekSnapshots, locale, rtl),
    [weekSnapshots, locale, rtl]
  );

  const topProducts = useMemo(() => topProductsFromRange(weekSnapshots, 5), [weekSnapshots]);

  const tableStats = useMemo(() => {
    const active = tables.filter((tb) => tb.isActive);
    return {
      free: active.filter((tb) => tb.status === "Free").length,
      busy: active.filter((tb) => tb.status === "Busy").length,
      cleaning: active.filter((tb) => tb.status === "Cleaning").length,
      total: active.length,
    };
  }, [tables]);

  const quickLinks = [
    { key: "pos", href: "/pos", icon: CreditCard, labelKey: "pos" },
    { key: "tables", href: "/tables", icon: TableProperties, labelKey: "tables" },
    { key: "reports", href: "/reports", icon: BarChart3, labelKey: "reports" },
    { key: "kds", href: "/kds", icon: ChefHat, labelKey: "kds" },
  ] as const;

  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 auto-rows-auto">

      {/* Welcome + Clock */}
      <Card className="col-span-2 p-5 flex flex-col bg-primary/5 border-primary/20">
        <p className="text-xs font-semibold uppercase tracking-widest text-primary/70 mb-1">
          {t("greeting")}
          {role && <span className="ms-1.5 text-muted-foreground normal-case tracking-normal font-normal">· {role}</span>}
        </p>
        <p className="text-3xl font-bold text-foreground tabular-nums leading-none">{timeStr}</p>
        <p className="mt-1.5 text-xs text-muted-foreground truncate">{dateStr}</p>
        <div className="mt-auto pt-4">
          <span className="text-[11px] text-muted-foreground/50">Meezi</span>
        </div>
      </Card>

      {/* Revenue KPI */}
      <Card className="col-span-1 p-5 flex flex-col">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {t("todayRevenue")}
          </span>
          <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10">
            <CreditCard className="h-3.5 w-3.5 text-primary" />
          </div>
        </div>
        <KpiValue value={todayTotals?.totalRevenue ?? null} loading={isLoading} currency locale={numberLocale} />
        <div className="mt-2">
          <TrendBadge delta={revenueDelta} label={t("vsYesterday")} />
        </div>
      </Card>

      {/* Orders KPI */}
      <Card className="col-span-1 p-5 flex flex-col">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {t("todayOrders")}
          </span>
          <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-blue-100">
            <ShoppingBag className="h-3.5 w-3.5 text-blue-600" />
          </div>
        </div>
        <KpiValue value={todayTotals?.totalOrders ?? null} loading={isLoading} locale={numberLocale} />
        <div className="mt-2">
          <TrendBadge delta={ordersDelta} label={t("vsYesterday")} />
        </div>
      </Card>

      {/* 7-day Chart (3×2) */}
      <Card className="col-span-2 lg:col-span-3 lg:row-span-2 p-5 flex flex-col">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-semibold text-foreground">{t("revenueChart")}</h3>
          <Link
            href="/reports"
            className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary transition-colors"
          >
            {tNav("reports")}
            <ArrowIcon className="h-3 w-3" />
          </Link>
        </div>
        <div className="flex-1 min-h-[180px] lg:min-h-[220px]">
          {isLoading ? (
            <Skeleton className="h-full w-full" />
          ) : chartPoints.length === 0 ? (
            <div className="h-full flex items-center justify-center">
              <p className="text-sm text-muted-foreground">{t("noData")}</p>
            </div>
          ) : (
            <Suspense fallback={<Skeleton className="h-full w-full" />}>
              <LazyMiniChart data={chartPoints} numberLocale={numberLocale} />
            </Suspense>
          )}
        </div>
      </Card>

      {/* Table Status (1×2) */}
      <Card className="col-span-2 lg:col-span-1 lg:row-span-2 p-5 flex flex-col">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-sm font-semibold text-foreground">{t("tableStatus")}</h3>
          <Link href="/tables" className="text-muted-foreground hover:text-primary transition-colors">
            <TableProperties className="h-3.5 w-3.5" />
          </Link>
        </div>

        <div className="flex flex-col items-center justify-center flex-1 gap-4">
          {/* Occupancy ring */}
          <div className="relative flex h-24 w-24 items-center justify-center">
            <svg className="absolute inset-0 -rotate-90" viewBox="0 0 36 36">
              <circle cx="18" cy="18" r="15.5" fill="none" stroke="hsl(var(--muted))" strokeWidth="3" />
              {tableStats.total > 0 && (
                <circle
                  cx="18" cy="18" r="15.5" fill="none"
                  stroke="hsl(var(--primary))" strokeWidth="3" strokeLinecap="round"
                  strokeDasharray={`${(tableStats.busy / tableStats.total) * 97.4} 97.4`}
                />
              )}
            </svg>
            <div className="text-center">
              <p className="text-2xl font-bold text-foreground tabular-nums leading-none">{tableStats.busy}</p>
              <p className="text-[10px] text-muted-foreground mt-0.5">/ {tableStats.total}</p>
            </div>
          </div>

          <div className="w-full space-y-2.5">
            {[
              { label: t("tableFree"), count: tableStats.free, cls: "bg-green-500", txt: "text-green-600" },
              { label: t("tableBusy"), count: tableStats.busy, cls: "bg-amber-500", txt: "text-amber-600" },
              { label: t("tableCleaning"), count: tableStats.cleaning, cls: "bg-blue-500", txt: "text-blue-600" },
            ].map(({ label, count, cls, txt }) => (
              <div key={label} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className={cn("h-2 w-2 rounded-full", cls)} />
                  <span className="text-xs text-muted-foreground">{label}</span>
                </div>
                <span className={cn("text-sm font-semibold tabular-nums", txt)}>
                  {formatNumber(count, numberLocale)}
                </span>
              </div>
            ))}
          </div>
        </div>
      </Card>

      {/* Top Products (2 cols) */}
      <Card className="col-span-2 p-5">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-semibold text-foreground">{t("topProducts")}</h3>
          <Utensils className="h-4 w-4 text-muted-foreground" />
        </div>
        {isLoading ? (
          <div className="space-y-2.5">{[...Array(5)].map((_, i) => <Skeleton key={i} className="h-5 w-full" />)}</div>
        ) : topProducts.length === 0 ? (
          <p className="text-sm text-muted-foreground">{t("noData")}</p>
        ) : (
          <div className="space-y-2">
            {topProducts.map((p, idx) => {
              const maxRevenue = topProducts[0]?.revenue ?? 1;
              const pct = Math.round((p.revenue / maxRevenue) * 100);
              return (
                <div key={p.productId} className="flex items-center gap-3">
                  <span className="w-4 shrink-0 text-[11px] font-medium text-muted-foreground tabular-nums text-end">
                    {idx + 1}
                  </span>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-foreground truncate">{p.name}</span>
                      <span className="text-[11px] text-muted-foreground tabular-nums shrink-0 ms-2">
                        {formatNumber(p.quantity, numberLocale)} {t("unit")}
                      </span>
                    </div>
                    <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                      <div
                        className="h-full rounded-full bg-primary/60 transition-all duration-500"
                        style={{ width: `${pct}%` }}
                      />
                    </div>
                  </div>
                  <span className="shrink-0 text-[11px] text-muted-foreground tabular-nums">
                    {formatCurrency(p.revenue, numberLocale)}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </Card>

      {/* Net Income KPI */}
      <Card className="col-span-1 p-5 flex flex-col">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
            {t("netIncome")}
          </span>
          <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-purple-100">
            <BarChart3 className="h-3.5 w-3.5 text-purple-600" />
          </div>
        </div>
        <KpiValue value={todayTotals?.netIncome ?? null} loading={isLoading} currency locale={numberLocale} />
        <div className="mt-2">
          <TrendBadge delta={netIncomeDelta} label={t("vsYesterday")} />
        </div>
      </Card>

      {/* Quick Links */}
      <Card className="col-span-1 p-5 flex flex-col">
        <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground mb-3">
          {t("quickLinks")}
        </p>
        <div className="grid grid-cols-2 gap-2 flex-1">
          {quickLinks.map(({ key, href, icon: Icon, labelKey }) => (
            <Link
              key={key}
              href={href}
              className="flex flex-col items-center justify-center gap-1.5 rounded-xl bg-muted/50 border border-border p-2.5 text-center transition-colors hover:bg-accent hover:text-accent-foreground group"
            >
              <Icon className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
              <span className="text-[10px] text-muted-foreground group-hover:text-primary transition-colors leading-tight">
                {tNav(labelKey)}
              </span>
            </Link>
          ))}
        </div>
      </Card>
    </div>
  );
}
