import { useRouter } from "expo-router"; // Keep this here
import { useCallback, useState } from "react";
import {
  ImageBackground,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { styles } from "./styles";

// Define your background image URI
const converterBgImage = {
  uri: "https://s1.qwant.com/thumbr/474x296/1/c/30947af0647acb7b3ef1eb2b5697b5dde49d5468269c918e41bb86286b007e/OIP.MpGUIDhV0CzgCK1mQYFbHQHaEo.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%2Fid%2FOIP.MpGUIDhV0CzgCK1mQYFbHQHaEo%3Fr%3D0%26pid%3DApi&q=0&b=1&p=0&a=0",
};

export default function CoordinateConverter() {
  const router = useRouter();

  const [overworldX, setOverworldX] = useState("");
  const [overworldZ, setOverworldZ] = useState("");
  const [netherX, setNetherX] = useState("");
  const [netherZ, setNetherZ] = useState("");

  const safeParseFloat = (value: string) => {
    const num = parseFloat(value);
    return isNaN(num) ? undefined : num;
  };

  const convertOWToNether = useCallback(
    (xStr: string, zStr: string) => {
      const x = safeParseFloat(xStr);
      const z = safeParseFloat(zStr);
      if (x !== undefined && z !== undefined) {
        setNetherX(Math.floor(x / 8).toString());
        setNetherZ(Math.floor(z / 8).toString());
      } else {
        setNetherX("");
        setNetherZ("");
      }
    },
    []
  );

  const convertNetherToOW = useCallback(
    (xStr: string, zStr: string) => {
      const x = safeParseFloat(xStr);
      const z = safeParseFloat(zStr);
      if (x !== undefined && z !== undefined) {
        setOverworldX(Math.floor(x * 8).toString());
        setOverworldZ(Math.floor(z * 8).toString());
      } else {
        setOverworldX("");
        setOverworldZ("");
      }
    },
    []
  );

  const handleOverworldXChange = useCallback(
    (text: string) => {
      setOverworldX(text);
      convertOWToNether(text, overworldZ);
    },
    [overworldZ, convertOWToNether]
  );

  const handleOverworldZChange = useCallback(
    (text: string) => {
      setOverworldZ(text);
      convertOWToNether(overworldX, text);
    },
    [overworldX, convertOWToNether]
  );

  const handleNetherXChange = useCallback(
    (text: string) => {
      setNetherX(text);
      convertNetherToOW(text, netherZ);
    },
    [netherZ, convertNetherToOW]
  );

  const handleNetherZChange = useCallback(
    (text: string) => {
      setNetherZ(text);
      convertNetherToOW(netherX, text);
    },
    [netherX, convertNetherToOW]
  );

  const handleClear = useCallback(() => {
    setOverworldX("");
    setOverworldZ("");
    setNetherX("");
    setNetherZ("");
  }, []);

  return (
    <View style={styles.converterScreenRoot}>
      <ImageBackground
        source={converterBgImage}
        style={styles.converterBackgroundImage}
        resizeMode="cover"
      >
        <View style={styles.converterBackgroundOverlay} />
      </ImageBackground>

      <SafeAreaView style={styles.converterContentWrapper}>
        <KeyboardAvoidingView
          style={styles.converterContainer}
          behavior={Platform.OS === "ios" ? "padding" : "height"}
        >
          <ScrollView contentContainerStyle={styles.converterScrollContent}>
            {/* Custom Back Button */}
            <TouchableOpacity
              onPress={() => router.back()}
              style={styles.backButton}
            >
              <Text style={styles.backButtonText}>← Go Back</Text>
            </TouchableOpacity>

            <Text style={styles.converterTitle}>Nether Portal Calculator</Text>

            {/* Overworld Row */}
            <View style={styles.dimensionContainer}>
              <Text style={styles.dimensionTitle}>Overworld</Text>
              <View style={styles.coordinatesRow}>
                <View style={styles.coordInputGroup}>
                  <Text style={styles.coordInputLabel}>X:</Text>
                  <TextInput
                    style={styles.coordTextInput}
                    keyboardType="numeric"
                    placeholder="0"
                    placeholderTextColor="#ccc"
                    value={overworldX}
                    onChangeText={handleOverworldXChange}
                  />
                </View>
                <View style={styles.coordInputGroup}>
                  <Text style={styles.coordInputLabel}>Z:</Text>
                  <TextInput
                    style={styles.coordTextInput}
                    keyboardType="numeric"
                    placeholder="0"
                    placeholderTextColor="#ccc"
                    value={overworldZ}
                    onChangeText={handleOverworldZChange}
                  />
                </View>
              </View>
            </View>

            {/* Nether Row */}
            <View style={styles.dimensionContainer}>
              <Text style={styles.dimensionTitle}>Nether</Text>
              <View style={styles.coordinatesRow}>
                <View style={styles.coordInputGroup}>
                  <Text style={styles.coordInputLabel}>X:</Text>
                  <TextInput
                    style={styles.coordTextInput}
                    keyboardType="numeric"
                    placeholder="0"
                    placeholderTextColor="#ccc"
                    value={netherX}
                    onChangeText={handleNetherXChange}
                  />
                </View>
                <View style={styles.coordInputGroup}>
                  <Text style={styles.coordInputLabel}>Z:</Text>
                  <TextInput
                    style={styles.coordTextInput}
                    keyboardType="numeric"
                    placeholder="0"
                    placeholderTextColor="#ccc"
                    value={netherZ}
                    onChangeText={handleNetherZChange}
                  />
                </View>
              </View>
            </View>

            <TouchableOpacity style={styles.clearButton} onPress={handleClear}>
              <Text style={styles.clearButtonText}>Clear All</Text>
            </TouchableOpacity>
          </ScrollView>
        </KeyboardAvoidingView>
      </SafeAreaView>
    </View>
  );
}