import { Alert } from "react-native";
import { router } from "expo-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import { persistLanguageTag, useAuth } from "@/lib/auth";
import { SUPPORTED_LANGUAGES, t } from "@/lib/i18n";
import {
  Body,
  Button,
  Card,
  Heading,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Tag,
} from "@/components/ui";

/** Profil: konto, samtycken, minne, prenumeration, GDPR-åtgärder. */

interface Me {
  displayName: string;
  email: string;
  emailVerified: boolean;
  precisionMode: string;
}
interface Entitlements {
  plan: string;
  status: string;
  aiScansPerMonth: number;
  aiScansUsedThisMonth: number;
  expiresAt?: string;
}
interface Consent {
  kind: string;
  status: string;
}

/** Samtyckesetiketter ur i18n-katalogen: profile.consent.<kind> (12 språk). */
const CONSENT_KINDS = [
  "personalization",
  "anonymized_improvement",
  "image_training",
  "health_integration",
  "location_weather",
  "push_notifications",
  "product_analytics",
] as const;

export default function ProfileScreen() {
  const queryClient = useQueryClient();
  const logout = useAuth((s) => s.logout);

  const me = useQuery({ queryKey: ["me"], queryFn: () => api<Me>("/v1/me") });
  const entitlements = useQuery({
    queryKey: ["entitlements"],
    queryFn: () => api<Entitlements>("/v1/me/entitlements"),
  });
  const consents = useQuery({
    queryKey: ["consents"],
    queryFn: () => api<Consent[]>("/v1/me/consents"),
  });

  const setConsent = useMutation({
    mutationFn: ({ kind, granted }: { kind: string; granted: boolean }) =>
      api("/v1/me/consents", { method: "PUT", body: { kind, granted } }),
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["consents"] }),
  });

  const togglePrecision = useMutation({
    mutationFn: (mode: string) => api("/v1/me", { method: "PATCH", body: { precisionMode: mode } }),
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["me"] }),
  });

  const deleteAccount = useMutation({
    mutationFn: () => api("/v1/me", { method: "DELETE" }),
    onSuccess: () => void logout().then(() => router.replace("/(auth)/login")),
  });

  const resend = useMutation({
    mutationFn: () => api("/v1/auth/resend-verification", { method: "POST" }),
  });

  // Språkval (i18n M4): sparas i backend-preferenserna + lokalt, byter direkt.
  const localePrefs = useQuery({
    queryKey: ["locale-preferences"],
    queryFn: () => api<{ languageTag: string }>("/v1/me/locale-preferences"),
  });
  const setLanguage = useMutation({
    mutationFn: (languageTag: string) =>
      api("/v1/me/locale-preferences", { method: "PATCH", body: { languageTag } }),
    onSuccess: async (_data, languageTag) => {
      await persistLanguageTag(languageTag);
      await queryClient.invalidateQueries();
    },
  });

  if (me.isLoading) return <LoadingView />;

  const consentMap = new Map((consents.data ?? []).map((c) => [c.kind, c.status]));

  return (
    <Screen>
      <Card>
        <Heading>{me.data?.displayName}</Heading>
        <Small>{me.data?.email}</Small>
        {me.data && !me.data.emailVerified && (
          <>
            <Small>⚠︎ {t("profile.emailUnverified")}</Small>
            <Button
              label={
                resend.isSuccess ? t("profile.verificationSent") : t("profile.resendVerification")
              }
              variant="ghost"
              onPress={() => resend.mutate()}
            />
          </>
        )}
        <Row>
          <Body>{t("profile.modeLabel")}</Body>
          <Button
            label={t("onboarding.modeSimple")}
            variant={me.data?.precisionMode === "simple" ? "secondary" : "ghost"}
            onPress={() => togglePrecision.mutate("simple")}
          />
          <Button
            label={t("onboarding.modeExact")}
            variant={me.data?.precisionMode === "exact" ? "secondary" : "ghost"}
            onPress={() => togglePrecision.mutate("exact")}
          />
        </Row>
      </Card>

      <Card>
        <Heading>{t("profile.language")}</Heading>
        <Row style={{ flexWrap: "wrap" }}>
          {SUPPORTED_LANGUAGES.map((lang) => (
            <Button
              key={lang.code}
              label={t(lang.labelKey)}
              variant={
                (localePrefs.data?.languageTag ?? "sv-SE").startsWith(lang.code)
                  ? "secondary"
                  : "ghost"
              }
              onPress={() => setLanguage.mutate(lang.tag)}
            />
          ))}
        </Row>
      </Card>

      {entitlements.data && (
        <Card onPress={() => router.push("/paywall")}>
          <Row style={{ justifyContent: "space-between" }}>
            <Heading>{t("profile.subscription")}</Heading>
            <Tag
              label={`${entitlements.data.plan} · ${entitlements.data.status}`}
              tone={entitlements.data.status === "free" ? "neutral" : "success"}
            />
          </Row>
          <Small>
            {t("profile.aiScansUsed", {
              used: entitlements.data.aiScansUsedThisMonth,
              total: entitlements.data.aiScansPerMonth,
            })}
          </Small>
        </Card>
      )}

      <Card onPress={() => router.push("/memory")}>
        <Heading>🧠 {t("profile.memory")}</Heading>
        <Small>{t("profile.memorySubtitle")}</Small>
      </Card>

      <Card>
        <Heading>{t("profile.consents")}</Heading>
        {CONSENT_KINDS.map((kind) => {
          const granted = consentMap.get(kind) === "granted";
          return (
            <Row key={kind} style={{ justifyContent: "space-between" }}>
              <Small>{t(`profile.consent.${kind}`)}</Small>
              <Button
                label={granted ? t("common.on") : t("common.off")}
                variant={granted ? "secondary" : "ghost"}
                onPress={() => setConsent.mutate({ kind, granted: !granted })}
              />
            </Row>
          );
        })}
        <Small>{t("profile.consentsNote")}</Small>
      </Card>

      <Spacer />
      <Button
        label={t("profile.logout")}
        variant="ghost"
        onPress={() => void logout().then(() => router.replace("/(auth)/login"))}
      />
      <Button
        label={t("profile.deleteAccount")}
        variant="danger"
        onPress={() =>
          Alert.alert(t("profile.deleteTitle"), t("profile.deleteBody"), [
            { text: t("common.cancel"), style: "cancel" },
            {
              text: t("memory.delete"),
              style: "destructive",
              onPress: () => deleteAccount.mutate(),
            },
          ])
        }
      />
    </Screen>
  );
}
