import { useState } from "react";
import { Alert, View } from "react-native";
import { router } from "expo-router";
import * as ImagePicker from "expo-image-picker";
import { useQuery } from "@tanstack/react-query";
import { api, uploadImage } from "@/lib/api";
import { t } from "@/lib/i18n";
import {
  Body,
  Card,
  Heading,
  LoadingView,
  Row,
  Screen,
  Small,
  Spacer,
  Title,
} from "@/components/ui";
import { spacing } from "@/lib/theme";

/** Skanna (spec §4.2): kyl, frys, skafferi, ingredienser, tallrik, kvitto, streckkod, datum, näringsdeklaration. */

const SCAN_TYPES = [
  { type: "fridge", glyph: "🧊", labelKey: "scan.fridge" },
  { type: "freezer", glyph: "❄️", labelKey: "scan.freezer" },
  { type: "pantry", glyph: "🗄️", labelKey: "scan.pantry" },
  { type: "ingredients", glyph: "🥕", labelKey: "scan.ingredients" },
  { type: "plate", glyph: "🍽️", labelKey: "scan.plate" },
  { type: "receipt", glyph: "🧾", labelKey: "scan.receipt" },
  { type: "barcode", glyph: "🏷️", labelKey: "scan.barcode" },
  { type: "expiry_date", glyph: "📅", labelKey: "scan.expiry" },
  { type: "nutrition_label", glyph: "🔬", labelKey: "scan.nutrition" },
] as const;

interface CreateScanResponse {
  scan: { id: string };
  uploads: Array<{ key: string; uploadUrl: string; headers: Record<string, string> }>;
}
interface Entitlements {
  aiScansPerMonth: number;
  aiScansUsedThisMonth: number;
}

export default function ScanScreen() {
  const [busyType, setBusyType] = useState<string | null>(null);
  const entitlements = useQuery({
    queryKey: ["entitlements"],
    queryFn: () => api<Entitlements>("/v1/me/entitlements"),
  });

  const startScan = async (scanType: string) => {
    if (scanType === "barcode") {
      router.push("/barcode");
      return;
    }
    setBusyType(scanType);
    try {
      // 1. Ta bild
      const permission = await ImagePicker.requestCameraPermissionsAsync();
      let picked: ImagePicker.ImagePickerResult;
      if (permission.granted) {
        picked = await ImagePicker.launchCameraAsync({ quality: 0.7 });
      } else {
        picked = await ImagePicker.launchImageLibraryAsync({ quality: 0.7 });
      }
      const asset = picked.assets?.[0];
      if (picked.canceled || !asset) return;

      // 2. Skapa jobb + presignad upload (kvotkontroll sker i API:t)
      const created = await api<CreateScanResponse>("/v1/scans", {
        method: "POST",
        body: { scanType, imageCount: 1, contentType: "image/jpeg" },
      });

      // 3. Ladda upp + starta analysen
      const upload = created.uploads[0];
      if (!upload) throw new Error(t("common.error"));
      await uploadImage(upload, asset.uri);
      await api(`/v1/scans/${created.scan.id}/start`, { method: "POST" });

      // 4. Vidare till granskningsvyn som pollar tills resultatet kommer
      router.push(`/scan-review/${created.scan.id}`);
    } catch (err) {
      Alert.alert(t("common.oops"), err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusyType(null);
    }
  };

  const quota = entitlements.data
    ? entitlements.data.aiScansPerMonth - entitlements.data.aiScansUsedThisMonth
    : null;

  return (
    <Screen>
      <Title>{t("scan.title")}</Title>
      <Small>{t("scan.subtitle")}</Small>
      {quota != null && <Small>{t("scan.quotaLeft", { count: Math.max(0, quota) })}</Small>}
      <Spacer size={spacing.sm} />

      {busyType && <LoadingView />}

      <View style={{ flexDirection: "row", flexWrap: "wrap", gap: spacing.sm }}>
        {SCAN_TYPES.map((item) => (
          <Card
            key={item.type}
            onPress={() => void startScan(item.type)}
            style={{ width: "31%", alignItems: "center", paddingVertical: spacing.md }}
          >
            <Body>{item.glyph}</Body>
            <Small>{t(item.labelKey as never)}</Small>
          </Card>
        ))}
      </View>

      <Spacer />
      <Card>
        <Heading>{t("scan.tips.title")}</Heading>
        <Small>• {t("scan.tips.overview")}</Small>
        <Small>• {t("scan.tips.shelf")}</Small>
        <Small>• {t("scan.tips.light")}</Small>
        <Small>• {t("scan.tips.move")}</Small>
      </Card>
    </Screen>
  );
}
