"use client";

import { useEffect, useMemo, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations, useLocale } from "next-intl";
import { Link } from "@/i18n/routing";
import { Pencil } from "lucide-react";
import { apiGet, apiPatch, apiPost, apiPut } from "@/lib/api/client";
import { InventoryUnitField } from "@/components/inventory/inventory-unit-field";
import { useAuthStore } from "@/lib/stores/auth.store";
import { useBranchStore } from "@/lib/stores/branch.store";
import { formatNumber } from "@/lib/format";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { LabeledField } from "@/components/ui/labeled-field";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { notify } from "@/lib/notify";

type Ingredient = {
  id: string;
  name: string;
  unit: string;
  quantityOnHand: number;
  reorderLevel: number;
  unitCost: number;
  parLevel: number;
  lowStockWarningPercent: number;
  warningThreshold: number;
  stockValueToman: number;
  isLowStock: boolean;
};

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

type RecipeLine = {
  id: string;
  ingredientId: string;
  ingredientName: string;
  unit: string;
  quantityPerUnit: number;
};

type MenuItemRecipe = {
  menuItemId: string;
  menuItemName: string;
  lines: RecipeLine[];
  materialCostPerUnitToman: number;
};

type PurchasesSummary = {
  totalPaidToman: number;
  purchaseCount: number;
  recent: {
    id: string;
    ingredientName: string;
    delta: number;
    unit: string;
    totalPaidToman: number;
    createdAt: string;
  }[];
};

export function InventoryScreen() {
  const t = useTranslations("inventory");
  const tCommon = useTranslations("common");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const branchId = useBranchStore((s) => s.branchId);
  const setBranchId = useBranchStore((s) => s.setBranchId);
  const qc = useQueryClient();

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

  useEffect(() => {
    if (!branchId && branches.length > 0) setBranchId(branches[0]!.id);
  }, [branchId, branches, setBranchId]);
  const [tab, setTab] = useState<"materials" | "recipes">("materials");

  const [name, setName] = useState("");
  const [unit, setUnit] = useState("گرم");
  const [qty, setQty] = useState("500");
  const [reorder, setReorder] = useState("50");
  const [totalPaid, setTotalPaid] = useState("");
  const [parLevel, setParLevel] = useState("500");
  const [warningPct, setWarningPct] = useState("20");
  const [adjustQty, setAdjustQty] = useState<Record<string, string>>({});
  const [adjustPaid, setAdjustPaid] = useState<Record<string, string>>({});
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState("");
  const [editUnit, setEditUnit] = useState("گرم");
  const [editReorder, setEditReorder] = useState("0");
  const [editUnitCost, setEditUnitCost] = useState("0");
  const [editParLevel, setEditParLevel] = useState("0");
  const [editWarningPct, setEditWarningPct] = useState("20");

  const [selectedMenuItemId, setSelectedMenuItemId] = useState("");
  const [recipeDraft, setRecipeDraft] = useState<RecipeLine[]>([]);
  const [newRecipeIngredientId, setNewRecipeIngredientId] = useState("");
  const [newRecipeQty, setNewRecipeQty] = useState("10");

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

  const monthRange = useMemo(() => {
    const now = new Date();
    const from = new Date(now.getFullYear(), now.getMonth(), 1);
    const pad = (n: number) => String(n).padStart(2, "0");
    const fmt = (d: Date) =>
      `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
    return { from: fmt(from), to: fmt(now) };
  }, []);

  const { data: purchasesSummary } = useQuery({
    queryKey: ["inventory", cafeId, "purchases", branchId, monthRange.from, monthRange.to],
    queryFn: () =>
      apiGet<PurchasesSummary>(
        `/api/cafes/${cafeId}/inventory/purchases?branchId=${encodeURIComponent(branchId!)}&from=${monthRange.from}&to=${monthRange.to}`
      ),
    enabled: !!cafeId && !!branchId && tab === "materials",
  });

  const { data: lowStock = [] } = useQuery({
    queryKey: ["inventory", cafeId, "low"],
    queryFn: () => apiGet<Ingredient[]>(`/api/cafes/${cafeId}/inventory/low-stock`),
    enabled: !!cafeId,
  });

  const { data: menuItems = [] } = useQuery({
    queryKey: ["menu", "items", cafeId],
    queryFn: () => apiGet<MenuItem[]>(`/api/cafes/${cafeId}/menu/items`),
    enabled: !!cafeId && tab === "recipes",
  });

  const { data: recipe, isLoading: recipeLoading } = useQuery({
    queryKey: ["inventory", cafeId, "recipe", selectedMenuItemId],
    queryFn: () =>
      apiGet<MenuItemRecipe>(
        `/api/cafes/${cafeId}/inventory/menu-items/${selectedMenuItemId}/recipe`
      ),
    enabled: !!cafeId && !!selectedMenuItemId,
  });

  const impliedUnitCost = useMemo(() => {
    const q = parseFloat(qty) || 0;
    const paid = parseFloat(totalPaid) || 0;
    if (q > 0 && paid > 0) return paid / q;
    return 0;
  }, [qty, totalPaid]);

  const createIngredient = useMutation({
    mutationFn: () => {
      const quantity = parseFloat(qty) || 0;
      const paid = parseFloat(totalPaid) || 0;
      return apiPost(`/api/cafes/${cafeId}/inventory/ingredients`, {
        name,
        unit: unit.trim() || t("defaultUnit"),
        quantityOnHand: quantity,
        reorderLevel: parseFloat(reorder) || 0,
        unitCost: impliedUnitCost,
        parLevel: parseFloat(parLevel) || quantity || 0,
        lowStockWarningPercent: parseFloat(warningPct) || 20,
        totalPaidToman: paid > 0 ? paid : null,
        branchId: paid > 0 ? branchId : null,
      });
    },
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["inventory", cafeId] });
      notify.success(t("created"));
    },
  });

  const updateIngredient = useMutation({
    mutationFn: (id: string) =>
      apiPatch(`/api/cafes/${cafeId}/inventory/ingredients/${id}`, {
        name: editName.trim(),
        unit: editUnit.trim() || t("defaultUnit"),
        reorderLevel: parseFloat(editReorder) || 0,
        unitCost: parseFloat(editUnitCost) || 0,
        parLevel: parseFloat(editParLevel) || 0,
        lowStockWarningPercent: parseFloat(editWarningPct) || 20,
      }),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["inventory", cafeId] });
      setEditingId(null);
      notify.success(t("updated"));
    },
  });

  const adjustStock = useMutation({
    mutationFn: ({ id, delta, paid }: { id: string; delta: number; paid?: number }) =>
      apiPost(`/api/cafes/${cafeId}/inventory/ingredients/${id}/adjust`, {
        delta,
        note: delta > 0 ? t("purchaseNote") : t("adjustNote"),
        totalPaidToman: delta > 0 ? paid : null,
        branchId: delta > 0 ? branchId : null,
      }),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["inventory", cafeId] });
      void qc.invalidateQueries({ queryKey: ["inventory", cafeId, "purchases"] });
      void qc.invalidateQueries({ queryKey: ["expenses"] });
      notify.success(t("adjusted"));
    },
    onError: () => notify.error(t("purchaseRequired")),
  });

  const saveRecipe = useMutation({
    mutationFn: () =>
      apiPut(`/api/cafes/${cafeId}/inventory/menu-items/${selectedMenuItemId}/recipe`, {
        lines: recipeDraft.map((l) => ({
          ingredientId: l.ingredientId,
          quantityPerUnit: l.quantityPerUnit,
        })),
      }),
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ["inventory", cafeId, "recipe", selectedMenuItemId] });
      notify.success(t("recipeSaved"));
    },
  });

  useEffect(() => {
    if (recipe?.lines) setRecipeDraft(recipe.lines.map((l) => ({ ...l })));
  }, [recipe]);

  const startEdit = (ing: Ingredient) => {
    setEditingId(ing.id);
    setEditName(ing.name);
    setEditUnit(ing.unit);
    setEditReorder(String(ing.reorderLevel));
    setEditUnitCost(String(ing.unitCost));
    setEditParLevel(String(ing.parLevel));
    setEditWarningPct(String(ing.lowStockWarningPercent));
  };

  if (!cafeId) return null;

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

      {lowStock.length > 0 ? (
        <Card className="rounded-xl border border-amber-300 bg-amber-50/80 p-4">
          <p className="text-sm font-medium text-amber-900">{t("lowStockAlert")}</p>
          <p className="mt-1 text-sm text-amber-800">
            {lowStock.map((i) => i.name).join("، ")}
          </p>
        </Card>
      ) : null}

      {tab === "materials" && branchId && purchasesSummary ? (
        <Card className="rounded-xl border border-[#0F6E56]/25 bg-[#E1F5EE]/40 p-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div>
              <p className="text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
                {t("purchasesThisMonth")}
              </p>
              <p className="mt-1 text-lg font-medium text-[#0F6E56]">
                {formatNumber(purchasesSummary.totalPaidToman, numberLocale)} ت
              </p>
              <p className="text-xs text-muted-foreground">
                {t("purchaseCount", { count: purchasesSummary.purchaseCount })}
              </p>
            </div>
            <Link
              href="/expenses"
              className="text-sm font-medium text-[#0C447C] hover:underline"
            >
              {t("viewInExpenses")}
            </Link>
          </div>
          {purchasesSummary.recent.length > 0 ? (
            <ul className="mt-3 space-y-1 border-t border-[#0F6E56]/15 pt-3 text-sm">
              {purchasesSummary.recent.slice(0, 5).map((p) => (
                <li key={p.id} className="flex justify-between gap-2">
                  <span>
                    {p.ingredientName} (+{formatNumber(p.delta, numberLocale)} {p.unit})
                  </span>
                  <span className="shrink-0 font-medium">
                    {formatNumber(p.totalPaidToman, numberLocale)} ت
                  </span>
                </li>
              ))}
            </ul>
          ) : null}
        </Card>
      ) : null}

      {tab === "materials" && !branchId ? (
        <p className="text-sm text-amber-800">{t("selectBranchForPurchases")}</p>
      ) : null}

      <div className="flex gap-2">
        <Button
          variant={tab === "materials" ? "default" : "outline"}
          className={tab === "materials" ? "bg-[#0F6E56]" : ""}
          onClick={() => setTab("materials")}
        >
          {t("tabMaterials")}
        </Button>
        <Button
          variant={tab === "recipes" ? "default" : "outline"}
          className={tab === "recipes" ? "bg-[#0F6E56]" : ""}
          onClick={() => setTab("recipes")}
        >
          {t("tabRecipes")}
        </Button>
      </div>

      {tab === "materials" ? (
        <>
          <Card className="rounded-xl border border-border/80 shadow-sm">
            <CardHeader>
              <CardTitle className="text-base">{t("addIngredient")}</CardTitle>
            </CardHeader>
            <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
              <LabeledField label={t("name")}>
                <Input value={name} onChange={(e) => setName(e.target.value)} />
              </LabeledField>
              <InventoryUnitField value={unit} onChange={setUnit} id="ingredient-unit-new" />
              <LabeledField label={t("quantity")}>
                <Input value={qty} onChange={(e) => setQty(e.target.value)} dir="ltr" className="text-end" />
              </LabeledField>
              <LabeledField label={t("parLevel")}>
                <Input value={parLevel} onChange={(e) => setParLevel(e.target.value)} dir="ltr" className="text-end" />
              </LabeledField>
              <LabeledField label={t("totalPaid")}>
                <Input
                  value={totalPaid}
                  onChange={(e) => setTotalPaid(e.target.value)}
                  dir="ltr"
                  className="text-end"
                  placeholder="0"
                />
              </LabeledField>
              {impliedUnitCost > 0 ? (
                <p className="text-xs text-muted-foreground sm:col-span-2">
                  {t("impliedUnitCost")}: {formatNumber(impliedUnitCost, numberLocale)} ت / {unit}
                </p>
              ) : null}
              <LabeledField label={t("warningPercent")}>
                <Input value={warningPct} onChange={(e) => setWarningPct(e.target.value)} dir="ltr" className="text-end" />
              </LabeledField>
              <LabeledField label={t("reorderLevel")}>
                <Input value={reorder} onChange={(e) => setReorder(e.target.value)} dir="ltr" className="text-end" />
              </LabeledField>
              <Button
                className="bg-[#0F6E56] hover:bg-[#0c5a46] self-end"
                disabled={!name.trim()}
                onClick={() => createIngredient.mutate()}
              >
                {tCommon("save")}
              </Button>
            </CardContent>
          </Card>

          {isLoading ? (
            <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
          ) : ingredients.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("empty")}</p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {ingredients.map((ing) => {
                const isEditing = editingId === ing.id;
                return (
                  <Card
                    key={ing.id}
                    className={cn(
                      "rounded-xl border shadow-sm",
                      ing.isLowStock ? "border-amber-300 bg-amber-50/50" : "border-border/80"
                    )}
                  >
                    <CardContent className="space-y-3 p-4">
                      {isEditing ? (
                        <>
                          <p className="text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">
                            {t("editIngredient")}
                          </p>
                          <LabeledField label={t("name")}>
                            <Input value={editName} onChange={(e) => setEditName(e.target.value)} />
                          </LabeledField>
                          <InventoryUnitField
                            value={editUnit}
                            onChange={setEditUnit}
                            id={`ingredient-unit-${ing.id}`}
                          />
                          <div className="grid gap-2 sm:grid-cols-2">
                            <LabeledField label={t("parLevel")}>
                              <Input
                                value={editParLevel}
                                onChange={(e) => setEditParLevel(e.target.value)}
                                dir="ltr"
                                className="text-end"
                              />
                            </LabeledField>
                            <LabeledField label={t("unitCost")}>
                              <Input
                                value={editUnitCost}
                                onChange={(e) => setEditUnitCost(e.target.value)}
                                dir="ltr"
                                className="text-end"
                              />
                            </LabeledField>
                            <LabeledField label={t("warningPercent")}>
                              <Input
                                value={editWarningPct}
                                onChange={(e) => setEditWarningPct(e.target.value)}
                                dir="ltr"
                                className="text-end"
                              />
                            </LabeledField>
                            <LabeledField label={t("reorderLevel")}>
                              <Input
                                value={editReorder}
                                onChange={(e) => setEditReorder(e.target.value)}
                                dir="ltr"
                                className="text-end"
                              />
                            </LabeledField>
                          </div>
                          <p className="text-[11px] text-muted-foreground">
                            {t("quantity")}: {formatNumber(ing.quantityOnHand)} {ing.unit} —{" "}
                            {t("quantityEditHint")}
                          </p>
                          <div className="flex gap-2">
                            <Button
                              size="sm"
                              className="bg-[#0F6E56] hover:bg-[#0c5a46]"
                              disabled={!editName.trim() || updateIngredient.isPending}
                              onClick={() => updateIngredient.mutate(ing.id)}
                            >
                              {tCommon("save")}
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setEditingId(null)}
                            >
                              {tCommon("cancel")}
                            </Button>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="flex items-start justify-between gap-2">
                            <h3 className="text-sm font-medium">{ing.name}</h3>
                            <div className="flex shrink-0 items-center gap-1">
                              {ing.isLowStock ? (
                                <Badge variant="outline">{t("lowStock")}</Badge>
                              ) : null}
                              <Button
                                type="button"
                                size="icon"
                                variant="ghost"
                                className="size-8"
                                aria-label={t("editIngredient")}
                                onClick={() => startEdit(ing)}
                              >
                                <Pencil className="size-4" />
                              </Button>
                            </div>
                          </div>
                          <p className="text-sm font-medium text-[#0F6E56]">
                            {formatNumber(ing.quantityOnHand)} {ing.unit}
                          </p>
                          <p className="text-[11px] text-muted-foreground">
                            {t("warningAt")}: {formatNumber(ing.warningThreshold)} {ing.unit}
                            <span className="mx-1">·</span>
                            {t("stockValue")}: {formatNumber(ing.stockValueToman)} ت
                          </p>
                          <div className="space-y-2">
                            <div className="flex flex-wrap items-end gap-2">
                              <LabeledField label={t("adjustDelta")} className="min-w-0 flex-1">
                                <Input
                                  inputMode="decimal"
                                  value={adjustQty[ing.id] ?? ""}
                                  onChange={(e) =>
                                    setAdjustQty((s) => ({ ...s, [ing.id]: e.target.value }))
                                  }
                                  dir="ltr"
                                  className="h-9 text-end"
                                  placeholder="+100"
                                />
                              </LabeledField>
                              {parseFloat(adjustQty[ing.id] ?? "0") > 0 ? (
                                <LabeledField label={t("totalPaid")} className="min-w-0 flex-1">
                                  <Input
                                    inputMode="decimal"
                                    value={adjustPaid[ing.id] ?? ""}
                                    onChange={(e) =>
                                      setAdjustPaid((s) => ({ ...s, [ing.id]: e.target.value }))
                                    }
                                    dir="ltr"
                                    className="h-9 text-end"
                                  />
                                </LabeledField>
                              ) : null}
                              <Button
                                size="sm"
                                variant="outline"
                                disabled={!branchId && parseFloat(adjustQty[ing.id] ?? "0") > 0}
                                onClick={() => {
                                  const delta = parseFloat(adjustQty[ing.id] ?? "0");
                                  if (!delta) return;
                                  const paid = parseFloat(adjustPaid[ing.id] ?? "0");
                                  if (delta > 0 && paid <= 0) {
                                    notify.error(t("purchaseRequired"));
                                    return;
                                  }
                                  adjustStock.mutate({
                                    id: ing.id,
                                    delta,
                                    paid: delta > 0 ? paid : undefined,
                                  });
                                  setAdjustQty((s) => ({ ...s, [ing.id]: "" }));
                                  setAdjustPaid((s) => ({ ...s, [ing.id]: "" }));
                                }}
                              >
                                {t("adjust")}
                              </Button>
                            </div>
                            {parseFloat(adjustQty[ing.id] ?? "0") > 0 ? (
                              <p className="text-[11px] text-muted-foreground">{t("purchaseHint")}</p>
                            ) : null}
                          </div>
                        </>
                      )}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </>
      ) : (
        <Card className="rounded-xl border border-border/80 p-4 space-y-4">
          <LabeledField label={t("selectMenuItem")}>
            <select
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
              value={selectedMenuItemId}
              onChange={(e) => {
                setSelectedMenuItemId(e.target.value);
                setRecipeDraft([]);
              }}
            >
              <option value="">{t("selectMenuItemPlaceholder")}</option>
              {menuItems.map((m) => (
                <option key={m.id} value={m.id}>
                  {m.name}
                </option>
              ))}
            </select>
          </LabeledField>

          {selectedMenuItemId && recipe ? (
            <>
              <p className="text-sm text-muted-foreground">
                {t("materialCostPerUnit")}: {formatNumber(recipe.materialCostPerUnitToman)} ت
              </p>
              <p className="text-[11px] uppercase tracking-[0.06em] text-muted-foreground">
                {t("recipeLines")}
              </p>
              {recipeDraft.map((line, idx) => (
                <div key={line.ingredientId} className="flex flex-wrap items-end gap-2">
                  <span className="text-sm flex-1 min-w-[120px]">
                    {line.ingredientName} ({line.unit})
                  </span>
                  <Input
                    className="w-28 text-end"
                    dir="ltr"
                    value={String(line.quantityPerUnit)}
                    onChange={(e) => {
                      const next = [...recipeDraft];
                      next[idx] = { ...line, quantityPerUnit: parseFloat(e.target.value) || 0 };
                      setRecipeDraft(next);
                    }}
                  />
                  <Button
                    size="sm"
                    variant="ghost"
                    className="text-destructive"
                    onClick={() => setRecipeDraft(recipeDraft.filter((_, i) => i !== idx))}
                  >
                    {tCommon("delete")}
                  </Button>
                </div>
              ))}
              <div className="flex flex-wrap items-end gap-2 border-t pt-3">
                <select
                  className="h-10 flex-1 min-w-[140px] rounded-md border border-input px-2 text-sm"
                  value={newRecipeIngredientId}
                  onChange={(e) => setNewRecipeIngredientId(e.target.value)}
                >
                  <option value="">{t("pickIngredient")}</option>
                  {ingredients.map((i) => (
                    <option key={i.id} value={i.id}>
                      {i.name} ({i.unit})
                    </option>
                  ))}
                </select>
                <Input
                  className="w-24 text-end"
                  dir="ltr"
                  value={newRecipeQty}
                  onChange={(e) => setNewRecipeQty(e.target.value)}
                  placeholder={t("perUnit")}
                />
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => {
                    const ing = ingredients.find((i) => i.id === newRecipeIngredientId);
                    if (!ing) return;
                    if (recipeDraft.some((l) => l.ingredientId === ing.id)) return;
                    setRecipeDraft([
                      ...recipeDraft,
                      {
                        id: `draft_${ing.id}`,
                        ingredientId: ing.id,
                        ingredientName: ing.name,
                        unit: ing.unit,
                        quantityPerUnit: parseFloat(newRecipeQty) || 0,
                      },
                    ]);
                  }}
                >
                  {t("addLine")}
                </Button>
              </div>
              <Button
                className="bg-[#0F6E56]"
                disabled={saveRecipe.isPending}
                onClick={() => saveRecipe.mutate()}
              >
                {t("saveRecipe")}
              </Button>
              <p className="text-xs text-muted-foreground">{t("recipeHint")}</p>
            </>
          ) : selectedMenuItemId ? (
            <p className="text-sm text-muted-foreground">{tCommon("loading")}</p>
          ) : null}
        </Card>
      )}
    </div>
  );
}
