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 {
  Body,
  Button,
  Card,
  EmptyState,
  ErrorView,
  Heading,
  LoadingView,
  ProgressBar,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
  Title,
} from "@/components/ui";
import { spacing } from "@/lib/theme";

/** Min dag (spec §4.3): måltider, makron, återstående mål, nästa steg. */

interface DayResponse {
  date: string;
  meals: Array<{
    id: string;
    titleSv: string;
    mealType: string;
    nutrition: { kcal: number; proteinG: number };
    nutritionIsEstimate: boolean;
    estimateMinKcal: number | null;
    estimateMaxKcal: number | null;
  }>;
  summary: {
    consumed: {
      kcal: number;
      proteinG: number;
      carbsG: number;
      fatG: number;
      fiberG: number;
      saltG: number;
    };
    targets: {
      kcal: number;
      proteinG: number;
      carbsG: number;
      fatG: number;
      fiberG: number;
      saltMaxG: number;
    };
    remaining: { kcal: number };
    progress: {
      kcal: number;
      proteinG: number;
      carbsG: number;
      fatG: number;
      fiberG: number;
      saltOfMax: number;
    };
    saltWarning: boolean;
  };
  note: string;
}

/** Måltidstypernas etiketter bor i i18n-katalogen: myday.mealType.<typ> (12 språk). */
const mealTypeLabel = (mealType: string): string =>
  ["breakfast", "lunch", "dinner", "snack", "dessert"].includes(mealType)
    ? t(`myday.mealType.${mealType}`)
    : mealType;

export default function MyDayScreen() {
  const today = new Date().toISOString().slice(0, 10);
  const query = useQuery({
    queryKey: ["day", today],
    queryFn: () => api<DayResponse>(`/v1/meals/day?date=${today}`),
  });

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

  const { summary, meals, note } = query.data;
  const remaining = summary.remaining.kcal;

  const macros = [
    {
      key: "myday.protein",
      value: summary.consumed.proteinG,
      target: summary.targets.proteinG,
      progress: summary.progress.proteinG,
      unit: "g",
    },
    {
      key: "myday.carbs",
      value: summary.consumed.carbsG,
      target: summary.targets.carbsG,
      progress: summary.progress.carbsG,
      unit: "g",
    },
    {
      key: "myday.fat",
      value: summary.consumed.fatG,
      target: summary.targets.fatG,
      progress: summary.progress.fatG,
      unit: "g",
    },
    {
      key: "myday.fiber",
      value: summary.consumed.fiberG,
      target: summary.targets.fiberG,
      progress: summary.progress.fiberG,
      unit: "g",
    },
  ] as const;

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

      <Card>
        <Row style={{ justifyContent: "space-between" }}>
          <Heading>{t("myday.calories")}</Heading>
          <Body>
            {Math.round(summary.consumed.kcal)} / {summary.targets.kcal} kcal
          </Body>
        </Row>
        <ProgressBar progress={summary.progress.kcal} />
        <Small>
          {remaining >= 0
            ? t("myday.remaining", { kcal: remaining })
            : t("myday.over", { kcal: Math.abs(remaining) })}
        </Small>
      </Card>

      <Card>
        {macros.map((macro) => (
          <View key={macro.key} style={{ gap: 4, marginBottom: spacing.sm }}>
            <Row style={{ justifyContent: "space-between" }}>
              <Small>{t(macro.key)}</Small>
              <Small>
                {Math.round(macro.value)} / {macro.target} {macro.unit}
              </Small>
            </Row>
            <ProgressBar progress={macro.progress} />
          </View>
        ))}
        <Row style={{ justifyContent: "space-between" }}>
          <Small>{t("myday.salt")}</Small>
          <Row>
            {summary.saltWarning && <Tag label={t("myday.overRecommended")} tone="warning" />}
            <Small>
              {Math.round(summary.consumed.saltG * 10) / 10} / max {summary.targets.saltMaxG} g
            </Small>
          </Row>
        </Row>
      </Card>

      <Heading>{t("myday.todaysMeals")}</Heading>
      {meals.length === 0 && <EmptyState text={t("myday.noMeals")} />}
      {meals.map((meal) => (
        <Card key={meal.id}>
          <Row style={{ justifyContent: "space-between" }}>
            <Body>
              {meal.titleSv}
              {meal.nutritionIsEstimate ? " ~" : ""}
            </Body>
            <Tag label={mealTypeLabel(meal.mealType)} />
          </Row>
          <Small>
            {meal.nutritionIsEstimate && meal.estimateMinKcal != null
              ? t("myday.estimateRange", {
                  min: meal.estimateMinKcal,
                  max: meal.estimateMaxKcal ?? meal.estimateMinKcal,
                  kcal: Math.round(meal.nutrition.kcal),
                })
              : t("myday.kcalProtein", {
                  kcal: Math.round(meal.nutrition.kcal),
                  protein: Math.round(meal.nutrition.proteinG),
                })}
          </Small>
        </Card>
      ))}

      <Spacer size={spacing.sm} />
      <Button label={t("myday.logMeal")} onPress={() => router.push("/log-meal")} />
      <Small>{note}</Small>
      <Small>{t("myday.targetsNote")}</Small>
    </Screen>
  );
}
