import { useState } from "react";
import { Pressable, Text, View } from "react-native";
import { router } from "expo-router";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { t } from "@/lib/i18n";
import {
  Body,
  Button,
  Card,
  Heading,
  Input,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
  Title,
} from "@/components/ui";
import { colors, spacing } from "@/lib/theme";

/** Onboarding (spec §6): mål, kost, allergier, hushåll, läge – allt frivilligt. */

// Etiketter hämtas ur i18n-katalogen (12 språk) – id:na är stabila API-värden.
const GOALS = [
  "lose_weight",
  "build_muscle",
  "maintain_weight",
  "more_protein",
  "less_waste",
  "lower_cost",
  "cook_more",
] as const;

const DIETS = ["omnivore", "flexitarian", "pescatarian", "vegetarian", "vegan"] as const;

const ALLERGENS = [
  "gluten",
  "milk",
  "eggs",
  "tree_nuts",
  "peanuts",
  "fish",
  "crustaceans",
  "soy",
  "sesame",
] as const;

export default function OnboardingScreen() {
  const setOnboardingCompleted = useAuth((s) => s.setOnboardingCompleted);
  const [step, setStep] = useState(0);
  const [goal, setGoal] = useState<string | null>(null);
  const [diet, setDiet] = useState<string>("omnivore");
  const [allergens, setAllergens] = useState<string[]>([]);
  const [mode, setMode] = useState<"simple" | "exact">("simple");
  const [householdKind, setHouseholdKind] = useState<"create" | "join" | "skip">("create");
  const [householdName, setHouseholdName] = useState(t("onboarding.householdDefaultName"));
  const [inviteCode, setInviteCode] = useState("");
  const [weightKg, setWeightKg] = useState("");
  const [heightCm, setHeightCm] = useState("");
  const [birthYear, setBirthYear] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const toggleAllergen = (id: string) =>
    setAllergens((prev) => (prev.includes(id) ? prev.filter((a) => a !== id) : [...prev, id]));

  const finish = async () => {
    setBusy(true);
    setError(null);
    try {
      await api("/v1/me/onboarding", {
        method: "POST",
        body: {
          precisionMode: mode,
          healthProfile: {
            ...(weightKg ? { weightKg: Number(weightKg) } : {}),
            ...(heightCm ? { heightCm: Number(heightCm) } : {}),
            ...(birthYear ? { birthYear: Number(birthYear) } : {}),
          },
          preferences: {
            ...(goal ? { primaryGoal: goal } : {}),
            dietPattern: diet,
            allergens,
          },
          householdChoice:
            householdKind === "create"
              ? { kind: "create", name: householdName || t("onboarding.householdDefaultName") }
              : householdKind === "join"
                ? { kind: "join", inviteCode }
                : { kind: "skip" },
        },
      });
      setOnboardingCompleted(true);
      router.replace("/(tabs)");
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  const steps = [
    // 0: Mål
    <View key="goal" style={{ gap: spacing.sm }}>
      <Heading>{t("onboarding.goal")}</Heading>
      {GOALS.map((id) => (
        <SelectRow
          key={id}
          label={t(`onboarding.goal.${id}`)}
          selected={goal === id}
          onPress={() => setGoal(id)}
        />
      ))}
    </View>,
    // 1: Kost + allergier
    <View key="diet" style={{ gap: spacing.sm }}>
      <Heading>{t("onboarding.diet")}</Heading>
      <Row>
        {DIETS.map((id) => (
          <Chip
            key={id}
            label={t(`onboarding.diet.${id}`)}
            selected={diet === id}
            onPress={() => setDiet(id)}
          />
        ))}
      </Row>
      <Spacer />
      <Heading>{t("onboarding.allergies")}</Heading>
      <Row>
        {ALLERGENS.map((id) => (
          <Chip
            key={id}
            label={t(`onboarding.allergen.${id}`)}
            selected={allergens.includes(id)}
            onPress={() => toggleAllergen(id)}
          />
        ))}
      </Row>
      <Small>{t("onboarding.allergyNote")}</Small>
    </View>,
    // 2: Kroppsdata (frivilligt, för energiberäkning)
    <View key="body" style={{ gap: spacing.sm }}>
      <Heading>{t("onboarding.bodyTitle")}</Heading>
      <Input
        placeholder={t("onboarding.weightPlaceholder")}
        keyboardType="numeric"
        value={weightKg}
        onChangeText={setWeightKg}
      />
      <Input
        placeholder={t("onboarding.heightPlaceholder")}
        keyboardType="numeric"
        value={heightCm}
        onChangeText={setHeightCm}
      />
      <Input
        placeholder={t("onboarding.birthYearPlaceholder")}
        keyboardType="numeric"
        value={birthYear}
        onChangeText={setBirthYear}
      />
      <Small>{t("onboarding.notMedical")}</Small>
    </View>,
    // 3: Hushåll
    <View key="household" style={{ gap: spacing.sm }}>
      <Heading>{t("onboarding.household")}</Heading>
      <SelectRow
        label={t("onboarding.householdCreate")}
        selected={householdKind === "create"}
        onPress={() => setHouseholdKind("create")}
      />
      {householdKind === "create" && (
        <Input
          placeholder={t("onboarding.householdName")}
          value={householdName}
          onChangeText={setHouseholdName}
        />
      )}
      <SelectRow
        label={t("onboarding.householdJoin")}
        selected={householdKind === "join"}
        onPress={() => setHouseholdKind("join")}
      />
      {householdKind === "join" && (
        <Input
          placeholder={t("onboarding.inviteCode")}
          autoCapitalize="characters"
          value={inviteCode}
          onChangeText={setInviteCode}
        />
      )}
      <SelectRow
        label={t("common.skip")}
        selected={householdKind === "skip"}
        onPress={() => setHouseholdKind("skip")}
      />
    </View>,
    // 4: Läge (spec §5)
    <View key="mode" style={{ gap: spacing.sm }}>
      <Heading>{t("onboarding.mode")}</Heading>
      <Card onPress={() => setMode("simple")} style={mode === "simple" ? sel : undefined}>
        <Body>{t("onboarding.modeSimple")}</Body>
        <Small>{t("onboarding.modeSimpleDesc")}</Small>
      </Card>
      <Card onPress={() => setMode("exact")} style={mode === "exact" ? sel : undefined}>
        <Body>{t("onboarding.modeExact")}</Body>
        <Small>{t("onboarding.modeExactDesc")}</Small>
      </Card>
      <Small>{t("onboarding.modesCombine")}</Small>
    </View>,
  ];

  const last = step === steps.length - 1;
  return (
    <Screen>
      <Title>{t("onboarding.title")}</Title>
      <Small>{t("onboarding.subtitle")}</Small>
      <Row style={{ marginVertical: spacing.sm }}>
        {steps.map((_, i) => (
          <View
            key={i}
            style={{
              flex: 1,
              height: 4,
              borderRadius: 2,
              backgroundColor: i <= step ? colors.primary : colors.border,
            }}
          />
        ))}
      </Row>
      {steps[step]}
      {error && <Text style={{ color: colors.danger }}>{error}</Text>}
      <Spacer />
      <Row>
        {step > 0 && (
          <View style={{ flex: 1 }}>
            <Button label={t("common.back")} variant="ghost" onPress={() => setStep(step - 1)} />
          </View>
        )}
        <View style={{ flex: 2 }}>
          <Button
            label={last ? t("common.done") : t("common.next")}
            onPress={() => (last ? void finish() : setStep(step + 1))}
            loading={busy}
          />
        </View>
      </Row>
    </Screen>
  );
}

const sel = { borderColor: colors.primary, borderWidth: 2, backgroundColor: colors.primarySoft };

function SelectRow({
  label,
  selected,
  onPress,
}: {
  label: string;
  selected: boolean;
  onPress: () => void;
}) {
  return (
    <Pressable
      onPress={onPress}
      style={{
        padding: spacing.md,
        borderRadius: 12,
        borderWidth: selected ? 2 : 1,
        borderColor: selected ? colors.primary : colors.border,
        backgroundColor: selected ? colors.primarySoft : colors.surface,
      }}
    >
      <Text style={{ color: colors.text, fontWeight: selected ? "700" : "400" }}>{label}</Text>
    </Pressable>
  );
}

function Chip({
  label,
  selected,
  onPress,
}: {
  label: string;
  selected: boolean;
  onPress: () => void;
}) {
  return (
    <Pressable
      onPress={onPress}
      style={{
        paddingHorizontal: 14,
        paddingVertical: 8,
        borderRadius: 999,
        borderWidth: 1,
        borderColor: selected ? colors.primary : colors.border,
        backgroundColor: selected ? colors.primarySoft : colors.surface,
      }}
    >
      <Text style={{ color: selected ? colors.primaryDark : colors.textMuted, fontSize: 13 }}>
        {label}
      </Text>
    </Pressable>
  );
}
