import { useState, useEffect } from "react";
import { router } from "expo-router";
import {
  ActivityIndicator,
  Alert,
  Pressable,
  ScrollView,
  Text,
  View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import * as ImagePicker from "expo-image-picker";
import { api } from "@/lib/api";
import { getActiveRestaurant } from "@/lib/active-restaurant";
import { aiStore } from "@/lib/ai-store";
import type { AiImportResponse } from "@menulio/shared";

export default function OnboardingScanStep() {
  const [analyzing, setAnalyzing] = useState(false);
  const [currentStage, setCurrentStage] = useState(0);
  const [error, setError] = useState<string | null>(null);

  const stages = [
    { title: "Fotoğraf okunuyor...", icon: "document-text-outline" as const },
    { title: "Kategoriler ve başlıklar bulunuyor...", icon: "list-outline" as const },
    { title: "Yemekler ve açıklamalar çıkarılıyor...", icon: "restaurant-outline" as const },
    { title: "Fiyatlar ve para birimi algılanıyor...", icon: "pricetag-outline" as const },
  ];

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (analyzing) {
      interval = setInterval(() => {
        setCurrentStage((prev) => (prev < stages.length - 1 ? prev + 1 : prev));
      }, 1200);
    }
    return () => clearInterval(interval);
  }, [analyzing, stages.length]);

  async function processImage(base64: string) {
    setError(null);
    setAnalyzing(true);
    setCurrentStage(0);

    try {
      const active = await getActiveRestaurant();
      if (!active?.menuId) {
        throw new Error("Aktif restoran veya menü bulunamadı.");
      }

      const formattedImage = base64.startsWith("data:")
        ? base64
        : `data:image/jpeg;base64,${base64}`;

      const response = await api.post<AiImportResponse>(`/menus/${active.menuId}/import-ai`, {
        image: formattedImage,
      });

      aiStore.setImportData(response);
      router.push("/(onboarding)/ai-review");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Fotoğraf analiz edilirken bir hata oluştu.");
    } finally {
      setAnalyzing(false);
    }
  }

  async function takePhoto() {
    try {
      const permission = await ImagePicker.requestCameraPermissionsAsync();
      if (!permission.granted) {
        Alert.alert("İzin Gerekli", "Menü fotoğrafı çekebilmek için kamera erişimine izin vermelisiniz.");
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ["images"],
        quality: 0.8,
        base64: true,
      });

      if (!result.canceled && result.assets[0]?.base64) {
        await processImage(result.assets[0].base64);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Kamera açılamadı.");
    }
  }

  async function pickFromGallery() {
    try {
      const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (!permission.granted) {
        Alert.alert("İzin Gerekli", "Menü görseli seçebilmek için galeri erişimine izin vermelisiniz.");
        return;
      }

      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ["images"],
        quality: 0.8,
        base64: true,
      });

      if (!result.canceled && result.assets[0]?.base64) {
        await processImage(result.assets[0].base64);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Galeri açılamadı.");
    }
  }

  if (analyzing) {
    return (
      <View style={{ flex: 1, backgroundColor: "#FAF8F5", justifyContent: "center", alignItems: "center", padding: 24 }}>
        <View
          style={{
            backgroundColor: "#FFFFFF",
            borderRadius: 24,
            padding: 32,
            alignItems: "center",
            width: "100%",
            maxWidth: 360,
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 8 },
            shadowOpacity: 0.08,
            shadowRadius: 24,
            elevation: 8,
          }}
        >
          <View
            style={{
              width: 72,
              height: 72,
              borderRadius: 36,
              backgroundColor: "#FDF4E6",
              alignItems: "center",
              justifyContent: "center",
              marginBottom: 20,
            }}
          >
            <Ionicons name="sparkles" size={32} color="#C8A96B" />
          </View>

          <Text style={{ fontSize: 20, fontWeight: "700", color: "#1C1917", marginBottom: 6, textAlign: "center" }}>
            Menünüz Analiz Ediliyor
          </Text>
          <Text style={{ fontSize: 13, color: "#78716C", textAlign: "center", marginBottom: 24 }}>
            Menulio AI menünüzü dijitalleştiriyor...
          </Text>

          <View style={{ width: "100%", gap: 14 }}>
            {stages.map((stage, idx) => {
              const isDone = idx < currentStage;
              const isCurrent = idx === currentStage;
              return (
                <View key={idx} style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
                  <View
                    style={{
                      width: 28,
                      height: 28,
                      borderRadius: 14,
                      backgroundColor: isDone ? "#ECFDF5" : isCurrent ? "#FDF4E6" : "#F5F5F4",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    {isDone ? (
                      <Ionicons name="checkmark-circle" size={18} color="#10B981" />
                    ) : isCurrent ? (
                      <ActivityIndicator size="small" color="#C8A96B" />
                    ) : (
                      <Ionicons name={stage.icon} size={15} color="#A8A29E" />
                    )}
                  </View>
                  <Text
                    style={{
                      fontSize: 13,
                      fontWeight: isCurrent ? "700" : "500",
                      color: isDone ? "#10B981" : isCurrent ? "#C8A96B" : "#A8A29E",
                      flex: 1,
                    }}
                  >
                    {stage.title}
                  </Text>
                </View>
              );
            })}
          </View>
        </View>
      </View>
    );
  }

  return (
    <ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: "#FAF8F5", padding: 24, justifyContent: "center" }}>
      <View style={{ maxWidth: 440, width: "100%", alignSelf: "center" }}>
        {/* Step Badge */}
        <View
          style={{
            alignSelf: "flex-start",
            backgroundColor: "#F3EDE2",
            paddingHorizontal: 12,
            paddingVertical: 6,
            borderRadius: 99,
            marginBottom: 16,
          }}
        >
          <Text style={{ color: "#926E27", fontSize: 12, fontWeight: "700" }}>
            ADIM 2 / 4 • AI MENU SCANNER
          </Text>
        </View>

        <Text style={{ fontSize: 28, fontWeight: "800", color: "#1C1917", marginBottom: 8, letterSpacing: -0.5 }}>
          Menü Fotoğrafını Yükleyin
        </Text>
        <Text style={{ fontSize: 14, color: "#78716C", lineHeight: 22, marginBottom: 32 }}>
          Basılı menünüzün fotoğrafını çekin veya galeriden seçin. Menulio AI saniyeler içinde tüm yemekleri, kategorileri ve fiyatları dijitalleştirsin.
        </Text>

        {error ? (
          <View
            style={{
              backgroundColor: "#FEF2F2",
              borderWidth: 1,
              borderColor: "#FCA5A5",
              borderRadius: 12,
              padding: 12,
              marginBottom: 20,
              flexDirection: "row",
              alignItems: "center",
              gap: 8,
            }}
          >
            <Ionicons name="alert-circle" size={18} color="#DC2626" />
            <Text style={{ color: "#DC2626", fontSize: 13, flex: 1 }}>{error}</Text>
          </View>
        ) : null}

        {/* Primary CTA: Take Photo */}
        <Pressable
          onPress={takePhoto}
          style={({ pressed }) => ({
            backgroundColor: "#1C1917",
            borderRadius: 16,
            padding: 18,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            gap: 12,
            marginBottom: 12,
            opacity: pressed ? 0.9 : 1,
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 4 },
            shadowOpacity: 0.1,
            shadowRadius: 12,
            elevation: 4,
          })}
        >
          <Ionicons name="camera-outline" size={22} color="#FFFFFF" />
          <Text style={{ color: "#FFFFFF", fontSize: 16, fontWeight: "700" }}>
            Menü Fotoğrafı Çek
          </Text>
        </Pressable>

        {/* Secondary CTA: Pick from Gallery */}
        <Pressable
          onPress={pickFromGallery}
          style={({ pressed }) => ({
            backgroundColor: "#FFFFFF",
            borderWidth: 1.5,
            borderColor: "#E7E5E4",
            borderRadius: 16,
            padding: 16,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            gap: 10,
            marginBottom: 24,
            opacity: pressed ? 0.85 : 1,
          })}
        >
          <Ionicons name="images-outline" size={20} color="#1C1917" />
          <Text style={{ color: "#1C1917", fontSize: 15, fontWeight: "600" }}>
            Galeriden Seç
          </Text>
        </Pressable>

        {/* Tertiary: Skip to manual */}
        <Pressable
          onPress={() => router.replace("/menu")}
          style={{ padding: 12, alignItems: "center", flexDirection: "row", justifyContent: "center", gap: 6 }}
        >
          <Ionicons name="create-outline" size={16} color="#78716C" />
          <Text style={{ color: "#78716C", fontSize: 14, fontWeight: "600", textDecorationLine: "underline" }}>
            Fotoğrafım yok, menüyü elle oluşturacağım →
          </Text>
        </Pressable>
      </View>
    </ScrollView>
  );
}
