"use client";

import { useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { Lock } from "lucide-react";
import { ApiClientError } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";
import { formatCurrency } from "@/lib/format";
import {
  deleteBranchMenuOverride,
  getBranchMenu,
  upsertBranchMenuOverride,
  type BranchMenuItem,
} from "@/lib/api/branch-menu";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { MenuItemLabels } from "@/components/menu/menu-item-labels";
import { Alert } from "@/components/ui/alert";
import { useConfirm } from "@/components/providers/confirm-provider";

type BranchMenuOverridesProps = {
  cafeId: string;
  branchId: string;
  numberLocale: string;
};

export function BranchMenuOverrides({
  cafeId,
  branchId,
  numberLocale,
}: BranchMenuOverridesProps) {
  const t = useTranslations("branchMenu");
  const tErrors = useTranslations("errors");
  const planTier = useAuthStore((s) => s.user?.planTier ?? "Free");
  const canOverridePrice = planTier !== "Free";
  const queryClient = useQueryClient();
  const confirmDialog = useConfirm();
  const [message, setMessage] = useState<string | null>(null);
  const [priceDraft, setPriceDraft] = useState<Record<string, string>>({});

  const { data: rows = [], isLoading } = useQuery({
    queryKey: ["branch-menu", cafeId, branchId, "manage"],
    queryFn: () => getBranchMenu(cafeId, branchId, { includeUnavailable: true }),
    enabled: !!cafeId && !!branchId,
  });

  const invalidate = () => {
    queryClient.invalidateQueries({ queryKey: ["branch-menu", cafeId, branchId] });
    queryClient.invalidateQueries({ queryKey: ["menu-items", cafeId] });
  };

  const upsert = useMutation({
    mutationFn: ({
      menuItemId,
      isAvailable,
      priceOverride,
    }: {
      menuItemId: string;
      isAvailable: boolean;
      priceOverride: number | null;
    }) =>
      upsertBranchMenuOverride(cafeId, branchId, menuItemId, {
        isAvailable,
        priceOverride,
      }),
    onSuccess: () => {
      setMessage(null);
      invalidate();
    },
    onError: (err: Error) => {
      if (err instanceof ApiClientError && err.code === "PLAN_LIMIT_REACHED") {
        setMessage(t("priceOverridePro"));
        return;
      }
      setMessage(tErrors("planLimit"));
    },
  });

  const resetOverride = useMutation({
    mutationFn: (menuItemId: string) =>
      deleteBranchMenuOverride(cafeId, branchId, menuItemId),
    onSuccess: () => invalidate(),
  });

  const sorted = useMemo(
    () => [...rows].sort((a, b) => a.name.localeCompare(b.name, "fa")),
    [rows]
  );

  const handleToggle = (row: BranchMenuItem) => {
    upsert.mutate({
      menuItemId: row.id,
      isAvailable: !row.isAvailable,
      priceOverride: row.hasPriceOverride ? row.effectivePrice : null,
    });
  };

  const handleSavePrice = (row: BranchMenuItem) => {
    const raw = priceDraft[row.id] ?? String(row.effectivePrice);
    const parsed = Number(raw.replace(/,/g, ""));
    if (!Number.isFinite(parsed) || parsed < 0) return;
    upsert.mutate({
      menuItemId: row.id,
      isAvailable: row.isAvailable,
      priceOverride: parsed,
    });
  };

  const handleReset = async (row: BranchMenuItem) => {
    if (!row.isOverridden) return;
    const ok = await confirmDialog({ description: t("confirmReset") });
    if (!ok) return;
    resetOverride.mutate(row.id);
  };

  if (isLoading) {
    return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
  }

  return (
    <div className="space-y-3">
      {message ? (
        <Alert variant="warning" onDismiss={() => setMessage(null)}>
          {message}
        </Alert>
      ) : null}

      <div className="overflow-x-auto rounded-xl border border-border/80 bg-card">
        <table className="w-full min-w-[32rem] text-start text-sm">
          <thead>
            <tr className="border-b border-border/80 bg-muted/30 text-[11px] uppercase tracking-wide text-muted-foreground">
              <th className="px-3 py-2 font-medium">{t("name")}</th>
              <th className="px-3 py-2 font-medium">{t("masterPrice")}</th>
              <th className="px-3 py-2 font-medium">{t("branchPrice")}</th>
              <th className="px-3 py-2 font-medium">{t("availability")}</th>
              <th className="px-3 py-2 font-medium">{t("actions")}</th>
            </tr>
          </thead>
          <tbody>
            {sorted.map((row) => (
              <tr
                key={row.id}
                className={cn(
                  "border-b border-border/60 last:border-0",
                  row.isOverridden && "bg-[#E1F5EE]/40"
                )}
              >
                <td className="px-3 py-2">
                  <div className="flex items-center gap-2">
                    <MenuItemLabels item={row} lines={1} primaryClassName="text-sm" />
                    {row.isOverridden ? (
                      <Badge variant="outline" className="text-[10px]">
                        {t("overrideActive")}
                      </Badge>
                    ) : null}
                  </div>
                </td>
                <td className="px-3 py-2 text-muted-foreground">
                  {formatCurrency(row.masterPrice, numberLocale)}
                </td>
                <td className="px-3 py-2">
                  {canOverridePrice ? (
                    <div className="flex items-center gap-1">
                      <Input
                        className="h-8 w-28 text-xs"
                        value={priceDraft[row.id] ?? String(row.effectivePrice)}
                        onChange={(e) =>
                          setPriceDraft((d) => ({ ...d, [row.id]: e.target.value }))
                        }
                      />
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        className="h-8 text-xs"
                        disabled={upsert.isPending}
                        onClick={() => handleSavePrice(row)}
                      >
                        {t("savePrice")}
                      </Button>
                    </div>
                  ) : (
                    <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
                      <Lock className="h-3 w-3" aria-hidden />
                      {t("priceOverridePro")}
                    </span>
                  )}
                </td>
                <td className="px-3 py-2">
                  <button
                    type="button"
                    role="switch"
                    aria-checked={row.isAvailable}
                    className={cn(
                      "relative inline-flex h-6 w-11 shrink-0 rounded-full border transition-colors",
                      row.isAvailable
                        ? "border-primary bg-primary"
                        : "border-border bg-muted"
                    )}
                    onClick={() => handleToggle(row)}
                  >
                    <span
                      className={cn(
                        "pointer-events-none inline-block h-5 w-5 translate-y-0.5 rounded-full bg-white shadow transition-transform",
                        row.isAvailable ? "translate-x-5" : "translate-x-0.5"
                      )}
                    />
                  </button>
                  <span className="ms-2 text-xs text-muted-foreground">
                    {row.isAvailable ? t("available") : t("unavailable")}
                  </span>
                </td>
                <td className="px-3 py-2">
                  <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    className="h-8 text-xs"
                    disabled={!row.isOverridden || resetOverride.isPending}
                    onClick={() => handleReset(row)}
                  >
                    {t("resetOverride")}
                  </Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
