import { useState } from "react";
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,
  Input,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
  Title,
} from "@/components/ui";
import { colors, spacing } from "@/lib/theme";

/** "Vad ska vi äta?" (spec §4.1, §18) – appens viktigaste vy. */

interface Recommendation {
  recipeId: string;
  titleSv: string;
  score: number;
  whySv: string;
  missingIngredients: string[];
  usesExpiring: Array<{ nameSv: string; daysLeft: number | null }>;
  coveragePercent: number;
}
interface MealBoxSuggestion {
  mealBoxId: string;
  titleSv: string;
  portionsRemaining: number;
  recommendedUseBy: string;
  whySv: string;
}
interface WhatToEatResponse {
  recommendations: Recommendation[];
  mealBoxSuggestions: MealBoxSuggestion[];
  context: { activeHolidays: string[]; remainingKcal: number; remainingProteinG: number };
}

export default function WhatToEatScreen() {
  const [craving, setCraving] = useState("");
  const [submittedCraving, setSubmittedCraving] = useState("");

  const query = useQuery({
    queryKey: ["what-to-eat", submittedCraving],
    queryFn: () =>
      api<WhatToEatResponse>(
        `/v1/recommendations/what-to-eat?limit=5${submittedCraving ? `&craving=${encodeURIComponent(submittedCraving)}` : ""}`,
      ),
  });

  return (
    <Screen>
      <Title>{t("wte.title")}</Title>
      <Small>{t("wte.subtitle")}</Small>
      <Spacer size={spacing.sm} />

      <Row>
        <View style={{ flex: 1 }}>
          <Input
            placeholder={t("wte.cravingPlaceholder")}
            value={craving}
            onChangeText={setCraving}
            onSubmitEditing={() => setSubmittedCraving(craving)}
            returnKeyType="search"
          />
        </View>
      </Row>
      <Spacer size={spacing.sm} />

      {query.isLoading && <LoadingView />}
      {query.isError && <ErrorView onRetry={() => void query.refetch()} />}

      {query.data && (
        <>
          {query.data.context.activeHolidays.length > 0 && (
            <Row>
              {query.data.context.activeHolidays.map((holiday) => (
                <Tag key={holiday} label={`🎉 ${holiday}`} tone="accent" />
              ))}
            </Row>
          )}

          {query.data.mealBoxSuggestions.length > 0 && (
            <>
              <Heading>{t("wte.mealBoxFirst")}</Heading>
              {query.data.mealBoxSuggestions.map((box) => (
                <Card key={box.mealBoxId} onPress={() => router.push("/meal-boxes")}>
                  <Row style={{ justifyContent: "space-between" }}>
                    <Body>🍱 {box.titleSv}</Body>
                    <Tag
                      label={t("mealbox.portionsLeft", { count: box.portionsRemaining })}
                      tone="success"
                    />
                  </Row>
                  <Small>{box.whySv}</Small>
                </Card>
              ))}
              <Spacer size={spacing.sm} />
            </>
          )}

          {query.data.recommendations.length === 0 && <EmptyState text={t("wte.empty")} />}

          {query.data.recommendations.map((rec, index) => (
            <Card key={rec.recipeId} onPress={() => router.push(`/recipe/${rec.recipeId}`)}>
              <Row style={{ justifyContent: "space-between" }}>
                <Heading>
                  {index === 0 ? "⭐ " : ""}
                  {rec.titleSv}
                </Heading>
              </Row>
              <Row>
                <Tag
                  label={t("wte.coverage", { pct: rec.coveragePercent })}
                  tone={rec.coveragePercent >= 80 ? "success" : "neutral"}
                />
                {rec.usesExpiring.slice(0, 2).map((item) => (
                  <Tag key={item.nameSv} label={`⏳ ${item.nameSv}`} tone="warning" />
                ))}
              </Row>
              <View
                style={{
                  backgroundColor: colors.surfaceAlt,
                  borderRadius: 10,
                  padding: spacing.sm,
                  marginTop: spacing.xs,
                }}
              >
                <Small>💡 {rec.whySv}</Small>
              </View>
              {rec.missingIngredients.length > 0 && (
                <Small>
                  {t("wte.missing", { items: rec.missingIngredients.slice(0, 4).join(", ") })}
                </Small>
              )}
            </Card>
          ))}

          <Spacer size={spacing.sm} />
          <Button
            label={t("wte.refresh")}
            variant="secondary"
            onPress={() => void query.refetch()}
          />
        </>
      )}
    </Screen>
  );
}
