import { useCallback, useEffect, useRef, useState } from "react";
import { router, useFocusEffect } from "expo-router";
import {
  ActivityIndicator,
  Alert,
  Linking,
  Platform,
  Pressable,
  ScrollView,
  Text,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Ionicons } from "@expo/vector-icons";
import * as Haptics from "expo-haptics";
import { api } from "@/lib/api";
import { getActiveRestaurant, type ActiveRestaurant } from "@/lib/active-restaurant";
import { getPublicMenuUrl, getPublicMenuDisplayUrl } from "@/lib/urls";
import { configurePurchases, getCustomerInfo, isProActive } from "@/lib/purchases";
import { CategoryPillBar } from "@/components/menu/CategoryPillBar";
import { MenuItemCard, type MenuItemData } from "@/components/menu/MenuItemCard";
import { ItemDetailSheet } from "@/components/menu/ItemDetailSheet";
import { AddItemModal } from "@/components/menu/AddItemModal";
import { AddCategoryModal } from "@/components/menu/AddCategoryModal";
import { PublishActionBar } from "@/components/menu/PublishActionBar";
import { ThemeSelectorSheet } from "@/components/menu/ThemeSelectorSheet";

interface MenuCategoryRow {
  id: string;
  name: string;
  is_active: boolean;
  sort_order: number;
  menu_items: MenuItemData[];
}

interface MenuResponse {
  menu: { id: string; name: string; is_published: boolean };
  categories: MenuCategoryRow[];
}

export default function MenuEditorScreen() {
  const insets = useSafeAreaInsets();
  const scrollViewRef = useRef<ScrollView>(null);
  const categoryPositionsRef = useRef<Record<string, number>>({});

  const [active, setActive] = useState<ActiveRestaurant | null>(null);
  const [menu, setMenu] = useState<MenuResponse["menu"] | null>(null);
  const [categories, setCategories] = useState<MenuCategoryRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [activeCategoryId, setActiveCategoryId] = useState<string | null>(null);

  // Modals state
  const [editingItem, setEditingItem] = useState<MenuItemData | null>(null);
  const [addItemCategoryId, setAddItemCategoryId] = useState<string | null>(null);
  const [addCategoryVisible, setAddCategoryVisible] = useState(false);
  const [categoryToRename, setCategoryToRename] = useState<MenuCategoryRow | null>(null);
  const [themeSheetVisible, setThemeSheetVisible] = useState(false);

  const load = useCallback(async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    try {
      const cached = await getActiveRestaurant();
      if (!cached) {
        router.replace("/(onboarding)/restaurant");
        return;
      }
      setActive(cached);
      configurePurchases(cached.restaurantId);

      const data = await api.get<MenuResponse>(`/menus/${cached.menuId}`);
      setMenu(data.menu);
      const fetchedCats = (data.categories || []).map((c) => ({
        ...c,
        menu_items: (c.menu_items || []).map((item) => ({
          id: item.id,
          name: item.name,
          description: item.description ?? null,
          price: item.price,
          is_active: item.is_active ?? true,
        })),
      }));
      setCategories(fetchedCats);
      if (fetchedCats.length > 0 && !activeCategoryId) {
        setActiveCategoryId(fetchedCats[0].id);
      }
    } catch (err) {
      Alert.alert("Hata", err instanceof Error ? err.message : "Menü yüklenemedi.");
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [activeCategoryId]);

  useEffect(() => {
    load();
  }, [load]);

  useFocusEffect(
    useCallback(() => {
      load();
    }, [load]),
  );

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

  // Category selection & scroll jumping
  function scrollToCategory(categoryId: string) {
    setActiveCategoryId(categoryId);
    const posY = categoryPositionsRef.current[categoryId];
    if (posY !== undefined && scrollViewRef.current) {
      scrollViewRef.current.scrollTo({ y: Math.max(0, posY - 70), animated: true });
    }
  }

  // Add Category
  async function handleAddCategory(name: string) {
    if (!active) return;
    const category = await api.post<MenuCategoryRow>(`/menus/${active.menuId}/categories`, {
      name,
      sortOrder: categories.length,
    });
    setCategories((prev) => [...prev, { ...category, menu_items: [] }]);
    setActiveCategoryId(category.id);
  }

  // Rename Category
  async function handleRenameCategory(name: string) {
    if (!categoryToRename) return;
    await api.patch(`/menu-categories/${categoryToRename.id}`, { name });
    setCategories((prev) =>
      prev.map((c) => (c.id === categoryToRename.id ? { ...c, name } : c)),
    );
    setCategoryToRename(null);
  }

  // Delete Category
  function confirmDeleteCategory(category: MenuCategoryRow) {
    Alert.alert(
      "Kategoriyi Sil",
      `"${category.name}" kategorisi ve içindeki tüm ürünler silinecek. Emin misiniz?`,
      [
        { text: "Vazgeç", style: "cancel" },
        {
          text: "Sil",
          style: "destructive",
          onPress: async () => {
            try {
              await api.delete(`/menu-categories/${category.id}`);
              setCategories((prev) => prev.filter((c) => c.id !== category.id));
              Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning).catch(() => {});
            } catch (err) {
              Alert.alert("Hata", err instanceof Error ? err.message : "Kategori silinemedi.");
            }
          },
        },
      ],
    );
  }

  // Add Item
  async function handleAddItem(
    categoryId: string,
    name: string,
    price: number,
    description?: string,
    imageUrl?: string,
  ) {
    const newItem = await api.post<MenuItemData>(`/menu-categories/${categoryId}/items`, {
      name,
      price,
      description: description || null,
      imageUrl: imageUrl || null,
    });
    setCategories((prev) =>
      prev.map((c) =>
        c.id === categoryId
          ? { ...c, menu_items: [...c.menu_items, { ...newItem, is_active: true }] }
          : c,
      ),
    );
  }

  // Toggle Item Availability (86 / In Stock)
  async function handleToggleItemActive(categoryId: string, itemId: string, isActive: boolean) {
    // Optimistic update
    setCategories((prev) =>
      prev.map((c) =>
        c.id === categoryId
          ? {
              ...c,
              menu_items: c.menu_items.map((i) =>
                i.id === itemId ? { ...i, is_active: isActive } : i,
              ),
            }
          : c,
      ),
    );

    try {
      await api.patch(`/menu-items/${itemId}`, { isActive });
    } catch (err) {
      // Revert if error
      setCategories((prev) =>
        prev.map((c) =>
          c.id === categoryId
            ? {
                ...c,
                menu_items: c.menu_items.map((i) =>
                  i.id === itemId ? { ...i, is_active: !isActive } : i,
                ),
              }
            : c,
        ),
      );
      Alert.alert("Hata", "Ürün durumu güncellenemedi.");
    }
  }

  // Save Item Details
  async function handleSaveItemDetails(updatedItem: MenuItemData) {
    await api.patch(`/menu-items/${updatedItem.id}`, {
      name: updatedItem.name,
      price: updatedItem.price,
      description: updatedItem.description || null,
      imageUrl: updatedItem.image_url ?? null,
      isActive: updatedItem.is_active,
    });

    setCategories((prev) =>
      prev.map((cat) => ({
        ...cat,
        menu_items: cat.menu_items.map((i) =>
          i.id === updatedItem.id ? updatedItem : i,
        ),
      })),
    );
  }

  // Delete Item
  async function handleDeleteItem(itemId: string) {
    await api.delete(`/menu-items/${itemId}`);
    setCategories((prev) =>
      prev.map((cat) => ({
        ...cat,
        menu_items: cat.menu_items.filter((i) => i.id !== itemId),
      })),
    );
  }

  // Publish
  async function onPublish() {
    if (!active) return;

    // Publishing (and re-publishing after a lapsed subscription — PRD §15)
    // requires an active Pro entitlement or trial. RevenueCat's SDK starts
    // the trial automatically on first purchase if the customer is eligible.
    try {
      const info = await getCustomerInfo();
      if (!isProActive(info)) {
        Alert.alert(
          "Menünüzü yayınlamak için abone olun",
          "7 gün ücretsiz deneyin, istediğiniz zaman iptal edin.",
          [
            { text: "Vazgeç", style: "cancel" },
            { text: "Devam Et", onPress: () => router.push("/account/subscription") },
          ],
        );
        return;
      }
    } catch (err) {
      Alert.alert("Hata", err instanceof Error ? err.message : "Abonelik durumu kontrol edilemedi.");
      return;
    }

    setPublishing(true);
    try {
      await api.post(`/menus/${active.menuId}/publish`);
      setMenu((prev) => (prev ? { ...prev, is_published: true } : prev));
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {});
      Alert.alert(
        "Menünüz Yayında! 🎉",
        `Menünüz ${getPublicMenuUrl(active.slug)} adresinde güncellendi.`,
        [
          { text: "Kapat", style: "cancel" },
          { text: "QR Kodu Görüntüle", onPress: () => router.push("/menu/qr") },
        ],
      );
    } catch (err) {
      Alert.alert("Hata", err instanceof Error ? err.message : "Yayınlanamadı.");
    } finally {
      setPublishing(false);
    }
  }

  if (loading) {
    return (
      <View style={{ flex: 1, backgroundColor: "#FAF8F5", alignItems: "center", justifyContent: "center" }}>
        <ActivityIndicator size="large" color="#C8A96B" />
        <Text style={{ marginTop: 12, color: "#78716C", fontSize: 14, fontWeight: "600" }}>
          Menü yükleniyor...
        </Text>
      </View>
    );
  }

  const isPublished = menu?.is_published ?? false;

  return (
    <View style={{ flex: 1, backgroundColor: "#FAF8F5" }}>
      {/* Top Header */}
      <View
        style={{
          paddingTop: Math.max(insets.top, 16),
          paddingHorizontal: 20,
          paddingBottom: 12,
          backgroundColor: "#FFFFFF",
          borderBottomWidth: 1,
          borderBottomColor: "#E7E5E4",
        }}
      >
        <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
          <View style={{ flex: 1, marginRight: 12 }}>
            <Text numberOfLines={1} style={{ fontSize: 22, fontWeight: "800", color: "#1C1917" }}>
              {menu?.name ?? (active?.slug ? `${active.slug} Menüsü` : "Menü")}
            </Text>
            <Text style={{ fontSize: 12, color: "#78716C", marginTop: 2 }}>
              {active?.slug ? getPublicMenuDisplayUrl(active.slug) : "Menü Yönetimi"}
            </Text>
          </View>

          {/* Status Badge & QR shortcut */}
          <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
                gap: 6,
                backgroundColor: isPublished ? "#ECFDF5" : "#F5F5F4",
                paddingHorizontal: 10,
                paddingVertical: 5,
                borderRadius: 12,
                borderWidth: 1,
                borderColor: isPublished ? "#A7F3D0" : "#E7E5E4",
              }}
            >
              <View
                style={{
                  width: 7,
                  height: 7,
                  borderRadius: 4,
                  backgroundColor: isPublished ? "#059669" : "#A8A29E",
                }}
              />
              <Text
                style={{
                  fontSize: 12,
                  fontWeight: "700",
                  color: isPublished ? "#059669" : "#78716C",
                }}
              >
                {isPublished ? "Yayında" : "Taslak"}
              </Text>
            </View>

            <Pressable
              onPress={() => setThemeSheetVisible(true)}
              style={{
                width: 36,
                height: 36,
                borderRadius: 18,
                backgroundColor: "#FDF8F0",
                alignItems: "center",
                justifyContent: "center",
                borderWidth: 1,
                borderColor: "rgba(200, 169, 107, 0.5)",
              }}
              accessibilityLabel="Şablon & Tema Seç"
            >
              <Ionicons name="color-palette-outline" size={18} color="#926E27" />
            </Pressable>

            <Pressable
              onPress={() => router.push("/menu/qr")}
              style={{
                width: 36,
                height: 36,
                borderRadius: 18,
                backgroundColor: "#F5F5F4",
                alignItems: "center",
                justifyContent: "center",
                borderWidth: 1,
                borderColor: "#E7E5E4",
              }}
              accessibilityLabel="QR Kod"
            >
              <Ionicons name="qr-code-outline" size={18} color="#1C1917" />
            </Pressable>

            <Pressable
              onPress={() => router.push("/account")}
              style={{
                width: 36,
                height: 36,
                borderRadius: 18,
                backgroundColor: "#FAF8F5",
                alignItems: "center",
                justifyContent: "center",
                borderWidth: 1,
                borderColor: "rgba(200, 169, 107, 0.4)",
              }}
              accessibilityLabel="Hesabım & Ayarlar"
            >
              <Ionicons name="person-outline" size={18} color="#C8A96B" />
            </Pressable>
          </View>
        </View>
      </View>

      {/* Category Pill Bar */}
      <CategoryPillBar
        categories={categories.map((c) => ({
          id: c.id,
          name: c.name,
          count: c.menu_items.length,
        }))}
        activeCategoryId={activeCategoryId}
        onSelectCategory={scrollToCategory}
        onAddCategoryPress={() => setAddCategoryVisible(true)}
      />

      {/* Main Content Area */}
      <ScrollView
        ref={scrollViewRef}
        style={{ flex: 1 }}
        contentContainerStyle={{ padding: 16, paddingBottom: 110 }}
        showsVerticalScrollIndicator={false}
      >
        {/* AI Scanner Banner */}
        <Pressable
          onPress={() => {
            Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
            router.push("/(onboarding)/scan");
          }}
          style={({ pressed }) => ({
            backgroundColor: "#FBF7EE",
            borderWidth: 1.5,
            borderColor: "rgba(200, 169, 107, 0.4)",
            borderRadius: 16,
            padding: 16,
            marginBottom: 20,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "space-between",
            opacity: pressed ? 0.88 : 1,
            shadowColor: "#C8A96B",
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.1,
            shadowRadius: 8,
          })}
        >
          <View style={{ flexDirection: "row", alignItems: "center", gap: 12, flex: 1 }}>
            <View
              style={{
                width: 44,
                height: 44,
                borderRadius: 12,
                backgroundColor: "#F3EDE2",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <Ionicons name="sparkles" size={22} color="#926E27" />
            </View>
            <View style={{ flex: 1 }}>
              <Text style={{ fontSize: 15, fontWeight: "700", color: "#1C1917" }}>
                AI ile Menü Fotoğrafı Tara
              </Text>
              <Text style={{ fontSize: 12, color: "#78716C", marginTop: 2 }}>
                Fotoğraftan otomatik ürün & kategori ekle
              </Text>
            </View>
          </View>
          <Ionicons name="arrow-forward" size={18} color="#C8A96B" />
        </Pressable>

        {/* Empty State when no categories exist */}
        {categories.length === 0 ? (
          <View
            style={{
              backgroundColor: "#FFFFFF",
              borderRadius: 20,
              padding: 32,
              alignItems: "center",
              borderWidth: 1,
              borderColor: "#E7E5E4",
              marginTop: 10,
            }}
          >
            <View
              style={{
                width: 64,
                height: 64,
                borderRadius: 32,
                backgroundColor: "#F5F5F4",
                alignItems: "center",
                justifyContent: "center",
                marginBottom: 16,
              }}
            >
              <Ionicons name="restaurant-outline" size={30} color="#78716C" />
            </View>
            <Text style={{ fontSize: 18, fontWeight: "700", color: "#1C1917", marginBottom: 6 }}>
              Menünüz Henüz Boş
            </Text>
            <Text style={{ fontSize: 13, color: "#78716C", textAlign: "center", marginBottom: 20 }}>
              Menü fotoğrafınızı tarayarak saniyeler içinde otomatik doldurabilir veya manuel olarak kategori ekleyebilirsiniz.
            </Text>
            
            <View style={{ width: "100%", gap: 10 }}>
              <Pressable
                onPress={() => router.push("/(onboarding)/scan")}
                style={{
                  backgroundColor: "#1C1917",
                  paddingVertical: 14,
                  borderRadius: 12,
                  alignItems: "center",
                }}
              >
                <Text style={{ color: "#FFFFFF", fontWeight: "700", fontSize: 14 }}>
                  ✨ Fotoğraf Çek / Tara
                </Text>
              </Pressable>

              <Pressable
                onPress={() => setAddCategoryVisible(true)}
                style={{
                  backgroundColor: "#F5F5F4",
                  paddingVertical: 14,
                  borderRadius: 12,
                  alignItems: "center",
                  borderWidth: 1,
                  borderColor: "#E7E5E4",
                }}
              >
                <Text style={{ color: "#1C1917", fontWeight: "700", fontSize: 14 }}>
                  + Manuel Kategori Ekle
                </Text>
              </Pressable>
            </View>
          </View>
        ) : null}

        {/* Categories and Items */}
        {categories.map((category) => (
          <View
            key={category.id}
            onLayout={(event) => {
              const layout = event.nativeEvent.layout;
              categoryPositionsRef.current[category.id] = layout.y;
            }}
            style={{
              backgroundColor: "#FFFFFF",
              borderRadius: 18,
              padding: 16,
              marginBottom: 18,
              borderWidth: 1,
              borderColor: "#E7E5E4",
              shadowColor: "#000",
              shadowOffset: { width: 0, height: 1 },
              shadowOpacity: 0.03,
              shadowRadius: 6,
            }}
          >
            {/* Category Header */}
            <View
              style={{
                flexDirection: "row",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: 14,
                paddingBottom: 12,
                borderBottomWidth: 1,
                borderBottomColor: "#F5F5F4",
              }}
            >
              <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flex: 1 }}>
                <Text style={{ fontSize: 18, fontWeight: "800", color: "#1C1917" }}>
                  {category.name}
                </Text>
                <View
                  style={{
                    backgroundColor: "#F5F5F4",
                    paddingHorizontal: 8,
                    paddingVertical: 2,
                    borderRadius: 10,
                  }}
                >
                  <Text style={{ fontSize: 12, fontWeight: "700", color: "#78716C" }}>
                    {category.menu_items.length}
                  </Text>
                </View>
              </View>

              {/* Category Actions */}
              <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
                <Pressable
                  onPress={() => {
                    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
                    setAddItemCategoryId(category.id);
                  }}
                  style={({ pressed }) => ({
                    flexDirection: "row",
                    alignItems: "center",
                    gap: 4,
                    backgroundColor: "#F3EDE2",
                    paddingVertical: 6,
                    paddingHorizontal: 10,
                    borderRadius: 8,
                    opacity: pressed ? 0.8 : 1,
                  })}
                >
                  <Ionicons name="add" size={16} color="#926E27" />
                  <Text style={{ fontSize: 12, fontWeight: "700", color: "#926E27" }}>
                    Ürün Ekle
                  </Text>
                </Pressable>

                <Pressable
                  onPress={() => setCategoryToRename(category)}
                  style={{ padding: 6, borderRadius: 6 }}
                >
                  <Ionicons name="pencil-outline" size={16} color="#78716C" />
                </Pressable>

                <Pressable
                  onPress={() => confirmDeleteCategory(category)}
                  style={{ padding: 6, borderRadius: 6 }}
                >
                  <Ionicons name="trash-outline" size={16} color="#DC2626" />
                </Pressable>
              </View>
            </View>

            {/* Category Items */}
            {category.menu_items.length === 0 ? (
              <Pressable
                onPress={() => setAddItemCategoryId(category.id)}
                style={{
                  paddingVertical: 20,
                  alignItems: "center",
                  borderRadius: 12,
                  borderWidth: 1,
                  borderColor: "#E7E5E4",
                  borderStyle: "dashed",
                  backgroundColor: "#FAFAFA",
                }}
              >
                <Ionicons name="add-circle-outline" size={24} color="#A8A29E" />
                <Text style={{ color: "#78716C", fontSize: 13, fontWeight: "600", marginTop: 4 }}>
                  Bu kategoriye ilk ürünü ekleyin
                </Text>
              </Pressable>
            ) : (
              category.menu_items.map((item) => (
                <MenuItemCard
                  key={item.id}
                  item={item}
                  onPress={() => setEditingItem(item)}
                  onToggleActive={(isActive) =>
                    handleToggleItemActive(category.id, item.id, isActive)
                  }
                />
              ))
            )}
          </View>
        ))}

        {/* Add Another Category Button */}
        {categories.length > 0 ? (
          <Pressable
            onPress={() => setAddCategoryVisible(true)}
            style={({ pressed }) => ({
              paddingVertical: 14,
              alignItems: "center",
              borderRadius: 14,
              backgroundColor: "#FFFFFF",
              borderWidth: 1.5,
              borderColor: "#E7E5E4",
              borderStyle: "dashed",
              marginBottom: 16,
              opacity: pressed ? 0.85 : 1,
            })}
          >
            <Text style={{ color: "#1C1917", fontSize: 14, fontWeight: "700" }}>
              + Yeni Kategori Ekle
            </Text>
          </Pressable>
        ) : null}
      </ScrollView>

      {/* Fixed Bottom Action Bar */}
      <PublishActionBar
        isPublished={isPublished}
        totalItems={totalItems}
        totalCategories={categories.length}
        publishing={publishing}
        onPublish={onPublish}
        onPreview={() => {
          if (active?.slug) {
            const url = getPublicMenuUrl(active.slug);
            Linking.openURL(url).catch(() => {
              Alert.alert("Önizleme Linki", url);
            });
          } else {
            router.push("/menu/qr");
          }
        }}
        onShowQr={() => router.push("/menu/qr")}
      />

      {/* Item Detail Sheet */}
      <ItemDetailSheet
        item={editingItem}
        visible={!!editingItem}
        onClose={() => setEditingItem(null)}
        onSave={handleSaveItemDetails}
        onDelete={handleDeleteItem}
      />

      {/* Add Item Modal */}
      {addItemCategoryId ? (
        <AddItemModal
          visible={!!addItemCategoryId}
          categoryId={addItemCategoryId}
          categoryName={
            categories.find((c) => c.id === addItemCategoryId)?.name ?? "Kategori"
          }
          onClose={() => setAddItemCategoryId(null)}
          onAdd={handleAddItem}
        />
      ) : null}

      {/* Add Category Modal */}
      <AddCategoryModal
        visible={addCategoryVisible}
        onClose={() => setAddCategoryVisible(false)}
        onSubmit={handleAddCategory}
      />

      {/* Rename Category Modal */}
      {categoryToRename ? (
        <AddCategoryModal
          visible={!!categoryToRename}
          initialName={categoryToRename.name}
          isEditing
          onClose={() => setCategoryToRename(null)}
          onSubmit={handleRenameCategory}
        />
      ) : null}

      {/* Theme Selector Sheet */}
      <ThemeSelectorSheet
        visible={themeSheetVisible}
        restaurantId={active?.restaurantId ?? ""}
        restaurantSlug={active?.slug}
        onClose={() => setThemeSheetVisible(false)}
      />
    </View>
  );
}
