import { Alert } from "react-native";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { t } from "@/lib/i18n";
import {
  Body,
  Button,
  Card,
  EmptyState,
  ErrorView,
  LoadingView,
  Row,
  Screen,
  Small,
  Tag,
} from "@/components/ui";

/** Matlådor (spec §24). */

interface MealBox {
  id: string;
  titleSv: string;
  portionsRemaining: number;
  recommendedUseBy: string;
  frozen: boolean;
  kcalPerPortion?: number;
}

export default function MealBoxesScreen() {
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["meal-boxes"],
    queryFn: () => api<{ mealBoxes: MealBox[] }>("/v1/meal-boxes"),
  });

  const consume = useMutation({
    mutationFn: (id: string) =>
      api(`/v1/meal-boxes/${id}/consume`, {
        method: "POST",
        body: { portions: 1, logAsMeal: true },
      }),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["meal-boxes"] });
      await queryClient.invalidateQueries({ queryKey: ["day"] });
      Alert.alert(t("mealbox.enjoyTitle"), t("mealbox.enjoyBody"));
    },
    onError: (err) =>
      Alert.alert(t("common.oops"), err instanceof Error ? err.message : t("common.error")),
  });

  if (query.isLoading) return <LoadingView />;
  if (query.isError || !query.data) return <ErrorView onRetry={() => void query.refetch()} />;

  const boxes = query.data.mealBoxes;
  const today = new Date().toISOString().slice(0, 10);

  return (
    <Screen>
      {boxes.length === 0 && <EmptyState text={t("mealbox.empty")} />}
      {boxes.map((box) => {
        const urgent = box.recommendedUseBy <= today;
        return (
          <Card key={box.id}>
            <Row style={{ justifyContent: "space-between" }}>
              <Body>
                {box.frozen ? "❄️ " : "🍱 "}
                {box.titleSv}
              </Body>
              <Tag
                label={t("mealbox.portionsLeft", { count: box.portionsRemaining })}
                tone="success"
              />
            </Row>
            <Row style={{ justifyContent: "space-between" }}>
              <Tag
                label={t("mealbox.eatBy", { date: box.recommendedUseBy })}
                tone={urgent ? "danger" : "neutral"}
              />
              <Button
                label={t("mealbox.eat")}
                variant="secondary"
                onPress={() => consume.mutate(box.id)}
              />
            </Row>
          </Card>
        );
      })}
      {/* Mjölkprincipen (spec §13): vägledning, inte dom – användaren avgör med sinnena. */}
      <Small>{t("mealbox.guidanceNote")}</Small>
    </Screen>
  );
}
