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

export default function OnboardingAiReviewStep() {
  const [importData, setImportData] = useState(aiStore.getImportData());
  const [categories, setCategories] = useState<AiExtractedCategory[]>(importData?.categories ?? []);
  const [saving, setSaving] = useState(false);
  const [newCatName, setNewCatName] = useState("");
  const [showAddCat, setShowAddCat] = useState(false);

  useEffect(() => {
    const data = aiStore.getImportData();
    if (!data) {
      router.replace("/(onboarding)/scan");
      return;
    }
    setImportData(data);
    setCategories(data.categories);
  }, []);

  const totalItems = categories.reduce((acc, c) => acc + c.items.length, 0);

  function updateItem(categoryId: string, itemId: string, field: "name" | "price" | "description", value: string) {
    setCategories((prev) =>
      prev.map((cat) => {
        if (cat.id !== categoryId) return cat;
        return {
          ...cat,
          items: cat.items.map((itm) => {
            if (itm.id !== itemId) return itm;
            if (field === "price") {
              const parsed = Number(value.replace(",", "."));
              return { ...itm, price: Number.isNaN(parsed) ? 0 : parsed };
            }
            return { ...itm, [field]: value };
          }),
        };
      }),
    );
  }

  function deleteItem(categoryId: string, itemId: string) {
    setCategories((prev) =>
      prev.map((cat) => {
        if (cat.id !== categoryId) return cat;
        return {
          ...cat,
          items: cat.items.filter((i) => i.id !== itemId),
        };
      }),
    );
  }

  function addItem(categoryId: string) {
    const newItem: AiExtractedItem = {
      id: `custom-item-${Date.now()}`,
      name: "Yeni Ürün",
      price: 100,
      description: "",
    };

    setCategories((prev) =>
      prev.map((cat) => {
        if (cat.id !== categoryId) return cat;
        return { ...cat, items: [...cat.items, newItem] };
      }),
    );
  }

  function deleteCategory(categoryId: string) {
    setCategories((prev) => prev.filter((c) => c.id !== categoryId));
  }

  function addCategory() {
    if (!newCatName.trim()) return;
    const newCat: AiExtractedCategory = {
      id: `custom-cat-${Date.now()}`,
      name: newCatName.trim(),
      items: [],
    };
    setCategories((prev) => [...prev, newCat]);
    setNewCatName("");
    setShowAddCat(false);
  }

  async function onSaveAndContinue() {
    if (categories.length === 0 || totalItems === 0) {
      Alert.alert("Uyarı", "Lütfen en az bir kategori ve ürün ekleyin.");
      return;
    }

    setSaving(true);
    try {
      const active = await getActiveRestaurant();
      if (!active?.menuId) {
        throw new Error("Menü bulunamadı.");
      }

      const payload = {
        menuId: active.menuId,
        categories: categories.map((cat) => ({
          name: cat.name,
          items: cat.items.map((itm) => ({
            name: itm.name,
            description: itm.description || null,
            price: itm.price,
          })),
        })),
      };

      await api.post(`/ai-imports/${importData?.importId ?? "new"}/apply`, payload);

      aiStore.clear();
      Alert.alert("Başarılı 🎉", "Menünüz başarıyla aktarıldı!", [
        { text: "Menüye Git", onPress: () => router.replace("/menu") },
      ]);
    } catch (err) {
      Alert.alert("Hata", err instanceof Error ? err.message : "Menü kaydedilemedi.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <View style={{ flex: 1, backgroundColor: "#FAF8F5" }}>
      <ScrollView contentContainerStyle={{ padding: 20, paddingBottom: 110 }}>
        {/* Header Badge */}
        <View
          style={{
            alignSelf: "flex-start",
            backgroundColor: "#F3EDE2",
            paddingHorizontal: 12,
            paddingVertical: 6,
            borderRadius: 99,
            marginBottom: 12,
          }}
        >
          <Text style={{ color: "#926E27", fontSize: 12, fontWeight: "700" }}>
            ADIM 3 / 4 • AI REVIEW & ONAY
          </Text>
        </View>

        <Text style={{ fontSize: 26, fontWeight: "800", color: "#1C1917", marginBottom: 6 }}>
          Çıkarılan Menüyü İnceleyin
        </Text>
        <Text style={{ fontSize: 13, color: "#78716C", marginBottom: 20 }}>
          AI sonuçlarını kontrol edin, gerekiyorsa fiyat veya isimleri düzenleyin.
        </Text>

        {/* Summary Banner */}
        <View
          style={{
            backgroundColor: "#FFFFFF",
            borderRadius: 16,
            padding: 16,
            marginBottom: 24,
            borderWidth: 1,
            borderColor: "rgba(200, 169, 107, 0.25)",
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.04,
            shadowRadius: 8,
          }}
        >
          <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
            <View>
              <Text style={{ fontSize: 18, fontWeight: "700", color: "#1C1917" }}>
                {totalItems} Ürün • {categories.length} Kategori
              </Text>
              <Text style={{ fontSize: 12, color: "#78716C", marginTop: 2 }}>
                Model: {importData?.model ?? "Menulio Vision"}
              </Text>
            </View>
            <View
              style={{
                backgroundColor: "#ECFDF5",
                paddingHorizontal: 10,
                paddingVertical: 4,
                borderRadius: 8,
                flexDirection: "row",
                alignItems: "center",
                gap: 4,
              }}
            >
              <Ionicons name="checkmark-circle" size={14} color="#059669" />
              <Text style={{ color: "#059669", fontSize: 12, fontWeight: "700" }}>Hazır</Text>
            </View>
          </View>

        </View>

        {/* Categories & Items List */}
        {categories.map((category) => (
          <View
            key={category.id}
            style={{
              backgroundColor: "#FFFFFF",
              borderRadius: 16,
              padding: 16,
              marginBottom: 20,
              borderWidth: 1,
              borderColor: "#E7E5E4",
            }}
          >
            {/* Category Header */}
            <View
              style={{
                flexDirection: "row",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: 12,
                paddingBottom: 10,
                borderBottomWidth: 1.5,
                borderBottomColor: "#C8A96B40",
              }}
            >
              <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
                <Ionicons name="restaurant-outline" size={18} color="#C8A96B" />
                <Text style={{ fontSize: 18, fontWeight: "700", color: "#C8A96B" }}>
                  {category.name} ({category.items.length})
                </Text>
              </View>
              <Pressable
                onPress={() => deleteCategory(category.id)}
                style={{ flexDirection: "row", alignItems: "center", gap: 4 }}
              >
                <Ionicons name="trash-outline" size={14} color="#EF4444" />
                <Text style={{ color: "#EF4444", fontSize: 12, fontWeight: "600" }}>Kategoriyi Sil</Text>
              </Pressable>
            </View>

            {/* Items in Category */}
            <View style={{ gap: 12 }}>
              {category.items.map((item) => {
                return (
                  <View
                    key={item.id}
                    style={{
                      backgroundColor: "#FAFAFA",
                      borderWidth: 1,
                      borderColor: "#F4F4F5",
                      borderRadius: 12,
                      padding: 12,
                    }}
                  >
                    <View style={{ flexDirection: "row", gap: 8, alignItems: "center", marginBottom: 6 }}>
                      <TextInput
                        value={item.name}
                        onChangeText={(v) => updateItem(category.id, item.id, "name", v)}
                        placeholder="Ürün Adı"
                        style={{
                          flex: 1,
                          fontSize: 15,
                          fontWeight: "700",
                          color: "#1C1917",
                          paddingVertical: 4,
                        }}
                      />

                      <View style={{ flexDirection: "row", alignItems: "center", gap: 4 }}>
                        <TextInput
                          value={String(item.price)}
                          onChangeText={(v) => updateItem(category.id, item.id, "price", v)}
                          keyboardType="numeric"
                          placeholder="Fiyat"
                          style={{
                            fontSize: 15,
                            fontWeight: "800",
                            color: "#C8A96B",
                            backgroundColor: "#FFFFFF",
                            borderWidth: 1,
                            borderColor: "#E7E5E4",
                            borderRadius: 8,
                            paddingHorizontal: 8,
                            paddingVertical: 4,
                            minWidth: 64,
                            textAlign: "right",
                          }}
                        />
                        <Text style={{ fontSize: 14, fontWeight: "700", color: "#1C1917" }}>₺</Text>
                      </View>

                      <Pressable
                        onPress={() => deleteItem(category.id, item.id)}
                        style={{ padding: 4 }}
                      >
                        <Ionicons name="close-circle-outline" size={18} color="#9CA3AF" />
                      </Pressable>
                    </View>

                    <TextInput
                      value={item.description ?? ""}
                      onChangeText={(v) => updateItem(category.id, item.id, "description", v)}
                      placeholder="Açıklama (opsiyonel)"
                      style={{
                        fontSize: 12,
                        color: "#78716C",
                        paddingVertical: 2,
                      }}
                    />
                  </View>
                );
              })}

              <Pressable
                onPress={() => addItem(category.id)}
                style={{
                  paddingVertical: 10,
                  flexDirection: "row",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 6,
                  borderRadius: 8,
                  borderWidth: 1,
                  borderColor: "#E7E5E4",
                  borderStyle: "dashed",
                }}
              >
                <Ionicons name="add" size={16} color="#78716C" />
                <Text style={{ color: "#78716C", fontSize: 13, fontWeight: "600" }}>
                  Bu Kategoriye Ürün Ekle
                </Text>
              </Pressable>
            </View>
          </View>
        ))}

        {/* Add New Category */}
        {showAddCat ? (
          <View
            style={{
              backgroundColor: "#FFFFFF",
              borderRadius: 16,
              padding: 16,
              marginBottom: 20,
              borderWidth: 1,
              borderColor: "#C8A96B",
            }}
          >
            <Text style={{ fontSize: 15, fontWeight: "700", color: "#1C1917", marginBottom: 8 }}>
              Yeni Kategori Ekle
            </Text>
            <TextInput
              value={newCatName}
              onChangeText={setNewCatName}
              placeholder="Örn: Başlangıçlar"
              style={{
                borderWidth: 1,
                borderColor: "#E7E5E4",
                borderRadius: 8,
                padding: 10,
                fontSize: 14,
                marginBottom: 10,
              }}
            />
            <View style={{ flexDirection: "row", gap: 8, justifyContent: "flex-end" }}>
              <Pressable
                onPress={() => setShowAddCat(false)}
                style={{ paddingVertical: 8, paddingHorizontal: 14, borderRadius: 8 }}
              >
                <Text style={{ color: "#78716C", fontWeight: "600" }}>Vazgeç</Text>
              </Pressable>
              <Pressable
                onPress={addCategory}
                style={{
                  backgroundColor: "#1C1917",
                  paddingVertical: 8,
                  paddingHorizontal: 16,
                  borderRadius: 8,
                }}
              >
                <Text style={{ color: "#FFFFFF", fontWeight: "700" }}>Ekle</Text>
              </Pressable>
            </View>
          </View>
        ) : (
          <Pressable
            onPress={() => setShowAddCat(true)}
            style={{
              paddingVertical: 14,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
              borderRadius: 12,
              backgroundColor: "#FFFFFF",
              borderWidth: 1.5,
              borderColor: "#E7E5E4",
              marginBottom: 20,
            }}
          >
            <Ionicons name="add-circle-outline" size={18} color="#1C1917" />
            <Text style={{ color: "#1C1917", fontSize: 14, fontWeight: "700" }}>
              Yeni Kategori Ekle
            </Text>
          </Pressable>
        )}
      </ScrollView>

      {/* Fixed Bottom Action Bar */}
      <View
        style={{
          position: "absolute",
          bottom: 0,
          left: 0,
          right: 0,
          backgroundColor: "#FFFFFF",
          borderTopWidth: 1,
          borderTopColor: "#E7E5E4",
          padding: 16,
          paddingBottom: 28,
        }}
      >
        <Pressable
          onPress={onSaveAndContinue}
          disabled={saving}
          style={({ pressed }) => ({
            backgroundColor: "#1C1917",
            borderRadius: 14,
            paddingVertical: 16,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
            opacity: pressed || saving ? 0.85 : 1,
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 4 },
            shadowOpacity: 0.15,
            shadowRadius: 12,
            elevation: 4,
          })}
        >
          {saving ? (
            <ActivityIndicator color="#FFFFFF" />
          ) : (
            <>
              <Ionicons name="checkmark-circle-outline" size={20} color="#FFFFFF" />
              <Text style={{ color: "#FFFFFF", fontSize: 16, fontWeight: "700" }}>
                Menüyü Onayla ve Kaydet ({totalItems} Ürün)
              </Text>
            </>
          )}
        </Pressable>
      </View>
    </View>
  );
}
