import { useState } from "react";
import { Alert, View } from "react-native";
import { router, useLocalSearchParams } from "expo-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { t } from "@/lib/i18n";
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";
import { formatQuantity } from "@/lib/units";

/** Receptdetalj: säkerhet, näring, ingredienser vs lager, varianter, betyg. */

interface RecipeDetail {
  id: string;
  titleSv: string;
  descriptionSv: string;
  portions: number;
  totalTimeMinutes: number;
  spiceLevel: number;
  nutritionPerPortion: { kcal: number; proteinG: number; carbsG: number; fatG: number };
  estimatedCostMinorPerPortion: number | null;
  costCurrency?: string;
  allergens: string[];
  ingredients: Array<{
    id: string;
    displayNameSv: string;
    quantity: number;
    unit: string;
    optional: boolean;
    groupName: string | null;
    canonicalIngredientId: string;
  }>;
  steps: Array<{
    id: string;
    stepNumber: number;
    instructionSv: string;
    temperatureC: number | null;
  }>;
  safety: { safe: boolean; violations: Array<{ severity: string; messageSv: string }> };
  variants: Array<{ id: string; titleSv: string; variantType: string }>;
  myRating: { stars: number } | null;
  isFavorite: boolean;
  ratingAverage: number | null;
  ratingCount: number;
  creatorDisplayName: string | null;
  verificationStatus: string;
}

export default function RecipeScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const queryClient = useQueryClient();
  const [portions, setPortions] = useState<number | null>(null);

  const query = useQuery({
    queryKey: ["recipe", id],
    queryFn: () => api<RecipeDetail>(`/v1/recipes/${id}`),
  });

  const scaled = useQuery({
    queryKey: ["recipe-scaled", id, portions],
    queryFn: () =>
      api<{ ingredients: RecipeDetail["ingredients"] }>(
        `/v1/recipes/${id}/scaled?portions=${portions}`,
      ),
    enabled: portions != null,
  });

  const favorite = useMutation({
    mutationFn: (isFavorite: boolean) =>
      api(`/v1/recipes/${id}/favorite`, { method: isFavorite ? "DELETE" : "POST" }),
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["recipe", id] }),
  });

  const rate = useMutation({
    mutationFn: (stars: number) =>
      api(`/v1/recipes/${id}/rate`, { method: "POST", body: { stars, feedbackTags: [] } }),
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["recipe", id] }),
  });

  if (query.isLoading) return <LoadingView />;
  if (query.isError || !query.data) return <ErrorView onRetry={() => void query.refetch()} />;
  const recipe = query.data;
  const shownPortions = portions ?? recipe.portions;
  const ingredients =
    portions != null && scaled.data ? scaled.data.ingredients : recipe.ingredients;
  const blockers = recipe.safety.violations.filter((v) => v.severity === "blocker");
  const warnings = recipe.safety.violations.filter((v) => v.severity === "warning");

  return (
    <Screen>
      <Title>{recipe.titleSv}</Title>
      <Row>
        <Tag label={t("recipe.time", { min: recipe.totalTimeMinutes })} />
        <Tag label={`${Math.round(recipe.nutritionPerPortion.kcal)} kcal`} />
        <Tag
          label={`${Math.round(recipe.nutritionPerPortion.proteinG)} g protein`}
          tone="success"
        />
        {recipe.estimatedCostMinorPerPortion != null && (
          <Tag
            label={t("recipe.cost", {
              amount: formatMinor(
                recipe.estimatedCostMinorPerPortion,
                recipe.costCurrency ?? "SEK",
              ),
            })}
          />
        )}
        {recipe.verificationStatus === "editorial" && <Tag label="✓ plattformen" tone="success" />}
      </Row>
      <Body muted>{recipe.descriptionSv}</Body>
      {recipe.creatorDisplayName && <Small>Skapat av {recipe.creatorDisplayName}</Small>}

      {!recipe.safety.safe && (
        <Card style={{ borderColor: colors.danger, backgroundColor: colors.dangerSoft }}>
          <Body>⛔ {t("recipe.notSafe")}</Body>
          {blockers.map((v, i) => (
            <Small key={i}>{v.messageSv}</Small>
          ))}
        </Card>
      )}
      {warnings.length > 0 && (
        <Card style={{ backgroundColor: colors.warningSoft, borderColor: colors.warning }}>
          {warnings.map((v, i) => (
            <Small key={i}>⚠️ {v.messageSv}</Small>
          ))}
        </Card>
      )}

      {recipe.variants.length > 0 && (
        <Row>
          {recipe.variants.map((variant) => (
            <Tag key={variant.id} label={`↔ ${variant.titleSv}`} tone="accent" />
          ))}
        </Row>
      )}

      <Card>
        <Row style={{ justifyContent: "space-between" }}>
          <Heading>{t("recipe.ingredients")}</Heading>
          <Row>
            <Button
              label="−"
              variant="ghost"
              onPress={() => setPortions(Math.max(1, shownPortions - 1))}
            />
            <Body>{t("recipe.portions", { count: shownPortions })}</Body>
            <Button
              label="+"
              variant="ghost"
              onPress={() => setPortions(Math.min(24, shownPortions + 1))}
            />
          </Row>
        </Row>
        {ingredients.map((ing) => (
          <Row key={ing.id ?? ing.displayNameSv} style={{ justifyContent: "space-between" }}>
            <Body>
              {ing.displayNameSv}
              {ing.optional ? " (valfritt)" : ""}
            </Body>
            <Small>{formatQuantity(ing.quantity, ing.unit)}</Small>
          </Row>
        ))}
      </Card>

      <Card>
        <Heading>{t("recipe.steps")}</Heading>
        {recipe.steps.map((step) => (
          <View key={step.id} style={{ marginBottom: spacing.sm }}>
            <Body>
              {step.stepNumber}. {step.instructionSv}
              {step.temperatureC ? ` (${step.temperatureC} °C)` : ""}
            </Body>
          </View>
        ))}
      </Card>

      <Button
        label={`👨‍🍳 ${t("recipe.cook")}`}
        onPress={() => router.push(`/cooking/${recipe.id}?portions=${shownPortions}`)}
      />
      <Row>
        <View style={{ flex: 1 }}>
          <Button
            label={recipe.isFavorite ? `★ ${t("recipe.saved")}` : `☆ ${t("recipe.save")}`}
            variant="secondary"
            onPress={() => favorite.mutate(recipe.isFavorite)}
          />
        </View>
      </Row>

      <Card>
        <Heading>{t("cooked.rate")}</Heading>
        <Row>
          {[1, 2, 3, 4, 5].map((stars) => (
            <Button
              key={stars}
              label={(recipe.myRating?.stars ?? 0) >= stars ? "★" : "☆"}
              variant="ghost"
              onPress={() => rate.mutate(stars)}
            />
          ))}
        </Row>
        {recipe.ratingAverage != null && (
          <Small>
            {t("recipe.avgRating", {
              avg: recipe.ratingAverage.toFixed(1),
              count: recipe.ratingCount,
            })}
          </Small>
        )}
      </Card>
      <Spacer />
    </Screen>
  );
}

function formatQty(quantity: number): string {
  return Number.isInteger(quantity) ? String(quantity) : String(Math.round(quantity * 100) / 100);
}
