import { View } from "react-native";
import { router } from "expo-router";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { t } from "@/lib/i18n";
import { formatMinor } from "@/lib/money";
import {
  Body,
  Card,
  EmptyState,
  ErrorView,
  Heading,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
  Title,
} from "@/components/ui";
import { spacing } from "@/lib/theme";
import { formatQuantity } from "@/lib/units";

/** Hemma (spec §4.4): matlager, bäst före, matlådor, inköpslista, budget, hushåll. */

interface InventoryItem {
  id: string;
  displayName: string;
  quantity: number;
  unit: string;
  locationName: string;
  expiry: { status: string; daysLeft: number | null; pastBestBefore: boolean };
}
interface BudgetSummary {
  currency: string;
  week: { purchasedMinor: number; wasteMinor: number; budgetMinor: number | null };
  month: { purchasedMinor: number; wasteMinor: number };
}

export default function HomeScreen() {
  const inventory = useQuery({
    queryKey: ["inventory"],
    queryFn: () => api<{ items: InventoryItem[] }>("/v1/inventory?limit=100"),
  });
  const expiring = useQuery({
    queryKey: ["inventory-expiring"],
    queryFn: () => api<{ items: InventoryItem[] }>("/v1/inventory/expiring"),
  });
  const budget = useQuery({
    queryKey: ["budget"],
    queryFn: () => api<BudgetSummary>("/v1/budget/summary"),
  });

  if (inventory.isLoading) return <LoadingView />;
  if (inventory.isError) return <ErrorView onRetry={() => void inventory.refetch()} />;

  const items = inventory.data?.items ?? [];
  const urgent = expiring.data?.items ?? [];

  const grouped = new Map<string, InventoryItem[]>();
  for (const item of items) {
    const list = grouped.get(item.locationName) ?? [];
    list.push(item);
    grouped.set(item.locationName, list);
  }

  return (
    <Screen>
      <Title>{t("home.title")}</Title>

      <Row>
        <QuickLink label={t("home.shopping")} glyph="🛒" onPress={() => router.push("/shopping")} />
        <QuickLink
          label={t("home.mealBoxes")}
          glyph="🍱"
          onPress={() => router.push("/meal-boxes")}
        />
        <QuickLink
          label={t("home.household")}
          glyph="👥"
          onPress={() => router.push("/household")}
        />
        <QuickLink label={t("profile.title")} glyph="⚙️" onPress={() => router.push("/profile")} />
      </Row>

      {budget.data && (
        <Card>
          <Heading>{t("home.budget")}</Heading>
          <Row style={{ justifyContent: "space-between" }}>
            <Small>{t("home.thisWeek")}</Small>
            <Body>
              {formatMinor(budget.data.week.purchasedMinor, budget.data.currency)}
              {budget.data.week.budgetMinor != null
                ? ` / ${formatMinor(budget.data.week.budgetMinor, budget.data.currency)}`
                : ""}
            </Body>
          </Row>
          <Row style={{ justifyContent: "space-between" }}>
            <Small>{t("home.wasteWeek")}</Small>
            <Body>{formatMinor(budget.data.week.wasteMinor, budget.data.currency)}</Body>
          </Row>
        </Card>
      )}

      {urgent.length > 0 && (
        <Card>
          <Heading>⏳ {t("home.useSoon")}</Heading>
          {urgent.slice(0, 5).map((item) => (
            <Row key={item.id} style={{ justifyContent: "space-between" }}>
              <Body>{item.displayName}</Body>
              <ExpiryTag expiry={item.expiry} />
            </Row>
          ))}
          {/* Mjölkprincipen (spec §13): bäst före ≠ dålig – döm aldrig mat i onödan. */}
          {urgent.some((i) => i.expiry.pastBestBefore) && <Small>{t("home.useSoonHint")}</Small>}
        </Card>
      )}

      <Heading>{t("home.inventory")}</Heading>
      {items.length === 0 && <EmptyState text={t("home.emptyInventory")} />}
      {[...grouped.entries()].map(([location, locationItems]) => (
        <Card key={location}>
          <Heading>{location}</Heading>
          {locationItems.slice(0, 12).map((item) => (
            <Row key={item.id} style={{ justifyContent: "space-between" }}>
              <Body>
                {item.displayName} · {formatQuantity(item.quantity, item.unit)}
              </Body>
              <ExpiryTag expiry={item.expiry} />
            </Row>
          ))}
          {locationItems.length > 12 && (
            <Small>{t("home.moreItems", { count: locationItems.length - 12 })}</Small>
          )}
        </Card>
      ))}
      <Spacer />
    </Screen>
  );
}

function QuickLink({
  label,
  glyph,
  onPress,
}: {
  label: string;
  glyph: string;
  onPress: () => void;
}) {
  return (
    <Card onPress={onPress} style={{ flex: 1, alignItems: "center", paddingVertical: spacing.sm }}>
      <Body>{glyph}</Body>
      <Small>{label}</Small>
    </Card>
  );
}

function ExpiryTag({ expiry }: { expiry: InventoryItem["expiry"] }) {
  if (expiry.status === "expired") return <Tag label={t("home.expired")} tone="danger" />;
  if (expiry.pastBestBefore) return <Tag label={t("home.pastBestBefore")} tone="warning" />;
  if (expiry.status === "expiring") {
    return (
      <Tag
        label={
          expiry.daysLeft === 0
            ? t("home.expiresToday")
            : t("home.expiresIn", { days: expiry.daysLeft ?? 0, count: expiry.daysLeft ?? 0 })
        }
        tone="warning"
      />
    );
  }
  if (expiry.status === "use_soon") {
    return (
      <Tag
        label={t("home.expiresIn", { days: expiry.daysLeft ?? 0, count: expiry.daysLeft ?? 0 })}
        tone="neutral"
      />
    );
  }
  return <View />;
}

function formatQty(quantity: number): string {
  return Number.isInteger(quantity) ? String(quantity) : quantity.toFixed(1);
}
