import { Pressable, View } from "react-native";
import { useCallback, useMemo } from "react";
import { router, useFocusEffect } from "expo-router";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { t } from "@/lib/i18n";
import * as Haptics from "expo-haptics";
import { formatMinor } from "@/lib/money";
import {
  Body,
  Button,
  Card,
  ErrorView,
  Heading,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
  Title,
} from "@/components/ui";
import { colors, spacing } from "@/lib/theme";

/** 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;
  locationType: 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 };
}

const LOCATION_ORDER = ["fridge", "freezer", "pantry", "garage_freezer", "wine_fridge"];
const orderIndex = (type: string) => {
  const i = LOCATION_ORDER.indexOf(type);
  return i === -1 ? LOCATION_ORDER.length : i;
};

export default function HomeScreen() {
  const inventory = useQuery({
    queryKey: ["inventory"],
    queryFn: () =>
      api<{ items: InventoryItem[]; trustStatus?: "up_to_date" | "needs_check" | "uncertain" }>(
        "/v1/inventory?limit=200",
      ),
  });
  const expiring = useQuery({
    queryKey: ["inventory-expiring"],
    queryFn: () => api<{ items: InventoryItem[] }>("/v1/inventory/expiring"),
  });
  const budget = useQuery({
    queryKey: ["budget"],
    queryFn: () => api<BudgetSummary>("/v1/budget/summary"),
  });
  const onboardingStatus = useQuery({
    queryKey: ["onboarding-status"],
    queryFn: () =>
      api<{ step: "a" | "b" | "c"; onboardingCompleted: boolean }>("/v1/onboarding/status"),
  });
  const setOnboardingStep = useAuth((s) => s.setOnboardingStep);

  useFocusEffect(
    useCallback(() => {
      void onboardingStatus.refetch();
    }, []),
  );

  const items = inventory.data?.items ?? [];
  // Distinkta platser (Kyl/Frys/Skafferi …) för genvägsknappar in i Matlager.
  const locations = useMemo(() => {
    const seen = new Map<string, string>();
    for (const it of items)
      if (!seen.has(it.locationType)) seen.set(it.locationType, it.locationName);
    return [...seen.entries()]
      .map(([type, name]) => ({ type, name }))
      .sort((a, b) => orderIndex(a.type) - orderIndex(b.type));
  }, [items]);

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

  const urgent = expiring.data?.items ?? [];
  const trustStatus = inventory.data?.trustStatus;
  const needsProfile = onboardingStatus.data && !onboardingStatus.data.onboardingCompleted;
  const profileStep = onboardingStatus.data?.step ?? "b";

  return (
    <Screen>
      <Title>{t("home.title")}</Title>
      {needsProfile && (
        <Card
          onPress={() => {
            setOnboardingStep(profileStep);
            router.push("/onboarding");
          }}
        >
          <Heading>{t("home.completeProfile.title")}</Heading>
          <Small>{t("home.completeProfile.body")}</Small>
        </Card>
      )}
      {trustStatus && (
        <Pressable onPress={() => router.push("/reconciliation")}>
          <Small style={{ marginBottom: spacing.xs, opacity: 0.8, color: colors.primary }}>
            {t(`home.trustStatus.${trustStatus}`)}
          </Small>
        </Pressable>
      )}

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

      <Card onPress={() => router.push("/saved-recipes")}>
        <Body>⭐ {t("home.savedRecipes")}</Body>
      </Card>

      <Card onPress={() => router.push("/submit-recipe")}>
        <Body>✍️ {t("home.submitRecipe")}</Body>
      </Card>

      {/* Matlager – städat, öppnas per plats eller som helhet (spec §8). */}
      <Card>
        <Heading>🧺 {t("home.inventory")}</Heading>
        <Small>{t("home.inventorySubtitle")}</Small>
        <Row style={{ marginTop: spacing.xs }}>
          {locations.map((loc) => (
            <Button
              key={loc.type}
              label={LOCATION_ORDER.includes(loc.type) ? t(`home.location.${loc.type}`) : loc.name}
              variant="ghost"
              onPress={() => router.push(`/kitchen?loc=${loc.type}`)}
            />
          ))}
          <Button
            label={locations.length ? t("home.openAll") : t("home.open")}
            variant="primary"
            onPress={() => router.push("/kitchen")}
          />
        </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>
      )}

      {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>
        </Card>
      )}

      <Spacer />
    </Screen>
  );
}

function QuickLink({
  label,
  glyph,
  onPress,
}: {
  label: string;
  glyph: string;
  onPress: () => void;
}) {
  return (
    <Card
      onPress={() => {
        void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
        onPress();
      }}
      style={{ flex: 1, alignItems: "center", paddingVertical: spacing.sm }}
    >
      <Body>{glyph}</Body>
      <Small numberOfLines={1} adjustsFontSizeToFit style={{ textAlign: "center" }}>
        {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 />;
}
