import { useState } from "react";
import { router } from "expo-router";
import { ActivityIndicator, Pressable, ScrollView, Text, TextInput, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { api } from "@/lib/api";
import { setActiveRestaurant } from "@/lib/active-restaurant";
import { configurePurchases } from "@/lib/purchases";

interface CreateRestaurantResponse {
  restaurant: { id: string; slug: string };
  location: { id: string };
  menu: { id: string };
}

export default function OnboardingRestaurantStep() {
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [address, setAddress] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function onSubmit() {
    setError(null);
    setLoading(true);
    try {
      const { restaurant, location, menu } = await api.post<CreateRestaurantResponse>("/restaurants", {
        name,
        phone: phone || undefined,
        address: address || undefined,
      });

      await setActiveRestaurant({
        restaurantId: restaurant.id,
        locationId: location.id,
        menuId: menu.id,
        slug: restaurant.slug,
      });
      configurePurchases(restaurant.id);

      router.replace("/(onboarding)/scan");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Bir hata oluştu");
    } finally {
      setLoading(false);
    }
  }

  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 1 / 4 • RESTORAN BİLGİLERİ
          </Text>
        </View>

        <Text style={{ fontSize: 26, fontWeight: "800", color: "#1C1917", marginBottom: 6 }}>
          Restoran Bilgilerini Ekle
        </Text>
        <Text style={{ fontSize: 14, color: "#78716C", marginBottom: 28, lineHeight: 20 }}>
          Sadece isim zorunludur. Telefon ve adres bilgilerinizi daha sonra da düzenleyebilirsiniz.
        </Text>

        {error ? (
          <View
            style={{
              backgroundColor: "#FEF2F2",
              borderWidth: 1,
              borderColor: "#FCA5A5",
              borderRadius: 12,
              padding: 12,
              marginBottom: 16,
              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}

        {/* Restaurant Name */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            backgroundColor: "#FFFFFF",
            borderWidth: 1.5,
            borderColor: "#D6D3D1",
            borderRadius: 12,
            paddingHorizontal: 14,
            marginBottom: 12,
          }}
        >
          <Ionicons name="storefront-outline" size={18} color="#57534E" style={{ marginRight: 10 }} />
          <TextInput
            placeholder="Restoran adı (Örn: Kebapçı Ahmet)"
            placeholderTextColor="#57534E"
            value={name}
            onChangeText={setName}
            style={{ flex: 1, paddingVertical: 14, fontSize: 15, color: "#1C1917", fontWeight: "500" }}
          />
        </View>

        {/* Phone */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            backgroundColor: "#FFFFFF",
            borderWidth: 1.5,
            borderColor: "#D6D3D1",
            borderRadius: 12,
            paddingHorizontal: 14,
            marginBottom: 12,
          }}
        >
          <Ionicons name="call-outline" size={18} color="#57534E" style={{ marginRight: 10 }} />
          <TextInput
            placeholder="Telefon numarası (opsiyonel)"
            placeholderTextColor="#57534E"
            keyboardType="phone-pad"
            value={phone}
            onChangeText={setPhone}
            style={{ flex: 1, paddingVertical: 14, fontSize: 15, color: "#1C1917", fontWeight: "500" }}
          />
        </View>

        {/* Address */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            backgroundColor: "#FFFFFF",
            borderWidth: 1.5,
            borderColor: "#D6D3D1",
            borderRadius: 12,
            paddingHorizontal: 14,
            marginBottom: 24,
          }}
        >
          <Ionicons name="location-outline" size={18} color="#57534E" style={{ marginRight: 10 }} />
          <TextInput
            placeholder="Adres / Şehir (opsiyonel)"
            placeholderTextColor="#57534E"
            value={address}
            onChangeText={setAddress}
            style={{ flex: 1, paddingVertical: 14, fontSize: 15, color: "#1C1917", fontWeight: "500" }}
          />
        </View>

        {/* Submit */}
        <Pressable
          onPress={onSubmit}
          disabled={loading || !name.trim()}
          style={({ pressed }) => ({
            backgroundColor: "#1C1917",
            borderRadius: 12,
            padding: 16,
            flexDirection: "row",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
            opacity: loading || !name.trim() ? 0.6 : pressed ? 0.9 : 1,
            shadowColor: "#000",
            shadowOffset: { width: 0, height: 2 },
            shadowOpacity: 0.1,
            shadowRadius: 8,
            elevation: 3,
          })}
        >
          {loading ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <>
              <Text style={{ color: "#fff", fontWeight: "700", fontSize: 15 }}>Devam Et</Text>
              <Ionicons name="arrow-forward" size={16} color="#fff" />
            </>
          )}
        </Pressable>
      </View>
    </ScrollView>
  );
}
