import ProfileHeader from "@/components/common/ProfileHeader";
import Text from "@/components/common/Text";
import { FLEX } from "@/theme/mixins";
import { Ionicons } from "@expo/vector-icons";
import { router } from "expo-router";
import React, { useEffect, useState } from "react";
import { StyleSheet, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { changeNotifications, getProfile } from "../../services/user";

export default function SettingsScreen() {
  const [settings, setSettings] = useState({
    notification: true,
    speaker: true,
  });

  const [userData, setUserData] = useState(null);

  const getUsers = async () => {
    try {
      const response = await getProfile();
      if (response.success) {
        const userSettings = {
          notification: response?.data?.user?.notification === true,
          speaker: response?.data?.user?.speaker === true,
        };

        setSettings(userSettings);
        setUserData(response?.data?.user);
      }
    } catch (error) {
      console.error("Kullanıcılar yüklenirken hata:", error);
    }
  };

  useEffect(() => {
    getUsers();
  }, []);

  const handleBackPress = () => {
    router.push("/(tabs)/profile");
  };

  const toggleSetting = async (key) => {
    // Önce yeni değeri hesapla
    const newValue = !settings[key];

    // State'i güncelle
    setSettings((prev) => ({
      ...prev,
      [key]: newValue,
    }));

    // API'ye yeni değeri gönder
    const response = await changeNotifications({
      [key]: newValue,
    });

    if (response.success) {
      // Ayarlar başarıyla değiştirildi
    } else {
      // Hata durumunda state'i geri al
      setSettings((prev) => ({
        ...prev,
        [key]: !newValue,
      }));
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ProfileHeader
        pageTitle="Genel Ayarlar"
        showBackButton={true}
        showNotification={true}
        showUserInfo={false}
        onBackPress={handleBackPress}
      />

      <View style={styles.content}>
        <View style={styles.settingsContainer}>
          {/* Notifications Setting */}
          <View style={styles.settingRow}>
            <View style={styles.settingLeft}>
              <View style={styles.iconContainer}>
                <Ionicons
                  name="notifications-outline"
                  size={24}
                  color="#E50012"
                />
              </View>
              <Text style={styles.settingLabel}>Bildirimler</Text>
            </View>
            <TouchableOpacity
              style={[
                styles.toggle3D,
                settings.notification
                  ? styles.toggle3DActive
                  : styles.toggle3DInactive,
              ]}
              onPress={() => toggleSetting("notification")}
            >
              <Text
                style={[
                  styles.toggleText,
                  settings.notification
                    ? styles.toggleTextActive
                    : styles.toggleTextInactive,
                ]}
              >
                {settings.notification ? "AÇIK" : "KAPALI"}
              </Text>
            </TouchableOpacity>
          </View>

          {/* Speaker Setting */}
          <View style={[styles.settingRow, styles.lastSettingRow]}>
            <View style={styles.settingLeft}>
              <View style={styles.iconContainer}>
                <Ionicons
                  name="volume-high-outline"
                  size={24}
                  color="#E50012"
                />
              </View>
              <Text style={styles.settingLabel}>Hoparlör</Text>
            </View>
            <TouchableOpacity
              style={[
                styles.toggle3D,
                settings.speaker
                  ? styles.toggle3DActive
                  : styles.toggle3DInactive,
              ]}
              onPress={() => toggleSetting("speaker")}
            >
              <Text
                style={[
                  styles.toggleText,
                  settings.speaker
                    ? styles.toggleTextActive
                    : styles.toggleTextInactive,
                ]}
              >
                {settings.speaker ? "AÇIK" : "KAPALI"}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: "#F5F5F5",
  },
  content: {
    flex: 1,
    padding: 20,
  },
  settingsContainer: {
    backgroundColor: "#FFFFFF",
    borderRadius: 12,
    paddingVertical: 8,
  },
  settingRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingVertical: 20,
    paddingHorizontal: 16,
    borderBottomWidth: 1,
    borderBottomColor: "#F0F0F0",
  },
  lastSettingRow: {
    borderBottomWidth: 0,
  },
  settingLeft: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
  },
  iconContainer: {
    width: 40,
    height: 40,
    borderRadius: 8,
    backgroundColor: "#FFDCE1",
    alignItems: "center",
    justifyContent: "center",
    marginRight: 12,
  },
  settingLabel: {
    fontSize: 16,
    fontWeight: "500",
    color: "#333",
  },
  toggle3D: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 24,
    minWidth: 80,
    alignItems: "center",
    justifyContent: "center",
    borderWidth: 2,
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1,
    shadowRadius: 0,
    elevation: 4,
  },
  toggle3DActive: {
    backgroundColor: "#FF0025",
    borderColor: "#52000C",
    shadowColor: "#DB0020",
  },
  toggle3DInactive: {
    backgroundColor: "#FFFFFF",
    borderColor: "#E0E0E0",
    shadowColor: "#E0E0E0",
  },
  toggleText: {
    fontFamily: "Rubik",
    fontSize: 12,
    fontWeight: "700",
    lineHeight: 18,
  },
  toggleTextActive: {
    color: "#FFFFFF",
  },
  toggleTextInactive: {
    color: "#999999",
  },
});
