import React, { useState } from "react";
import { Dialog, TextInput, useTheme, Button, Text, List, Portal } from "react-native-paper";
import { View, FlatList } from "react-native";
import Slider from "@react-native-community/slider";
import axios from "axios";
import * as Location from "expo-location";
import log from "@/util/log";

interface LocationScreenProps {
    visible: boolean;
    setChanged: (dataChanged: boolean) => void;
    currentTheme: string;
    onClose: () => void;
}

export const API_URL = process.env.EXPO_PUBLIC_API_URL;
const BUTTON_WIDTH = 260;

type Park = {
    Id: string;
    name: string;
    address: string;
    city: string;
    state: string;
    zip: string;
    location: {
        coordinates: [number, number];
    };
};

const LocationScreen: React.FC<LocationScreenProps> = ({ visible, currentTheme, setChanged, onClose }) => {
    const theme = useTheme();
    const [zip, setZip] = useState("");
    const [distance, setDistance] = useState(25);
    const [loading, setLoading] = useState(false);
    const [locLoading, setLocLoading] = useState(false);
    const [parks, setParks] = useState<Park[]>([]);
    const [hasSearched, setHasSearched] = useState(false);
    const [selectedPark, setSelectedPark] = useState<Park | null>(null);

    // Call the parks endpoint with coordinates
    const fetchNearbyParks = async (longitude: number, latitude: number) => {
        try {
            const response = await axios.post(API_URL + "/parkLookup", { "Lon": longitude, "Lat": latitude, "Dist": distance });
            log.error("Nearby Parks:", response.data);
            setParks(response.data);
        } catch (err) {
            log.error("Nearby Parks Error:", err);
            setParks([]);
        } finally {
            setHasSearched(true);
        }
    };

    // Zip code handler
    const handleSubmit = async () => {
        if (!zip) return;
        setLoading(true);
        try {
            const response = await axios.post(API_URL + "/zipLookup", { zip });
            log.error("Zip Lookup Response:", response.data);
            const longitude = response.data[0];
            const latitude = response.data[1];
            await fetchNearbyParks(longitude, latitude);
        } catch (err) {
            log.error(err);
        }
        setLoading(false);
    };

    // Geolocation handler
    const handleGetLocation = async () => {
        setLocLoading(true);
        try {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                log.error("Permission to access location was denied");
                setLocLoading(false);
                return;
            }
            let location = await Location.getCurrentPositionAsync({});
            const { longitude, latitude } = location.coords;
            log.error([longitude, latitude]);
            await fetchNearbyParks(longitude, latitude);
        } catch (err) {
            log.error("Location Error:", err);
        }
        setLocLoading(false);
    };

    // Render each park item
    const renderItem = ({ item }: { item: Park }) => (
        <List.Item
            title={item.name}
            description={
                `${item.address}\n${item.city}, ${item.state} ${item.zip}`
            }
            left={props => <List.Icon {...props} icon="paw" />}
            style={{
                backgroundColor: theme.colors.surface,
                borderRadius: 8,
                marginBottom: 8,
                elevation: 1,
            }}
            titleStyle={{ fontWeight: "bold" }}
            descriptionNumberOfLines={2}
            onPress={() => {
                setSelectedPark(item);
                setParks([]);
                setHasSearched(false);
            }}
        />
    );

    return (
        <Portal>
            <Dialog
                visible={visible}
                onDismiss={onClose}
                style={{ backgroundColor: theme.colors.background }}
            >
                <Dialog.Title style={{ color: theme.colors.primary, textAlign: 'center' }}>Location</Dialog.Title>
                <Dialog.Content style={{ maxHeight: 500, justifyContent: "center", alignItems: "center" }}>
                    <View style={{ alignItems: "center", width: "100%" }}>
                        {/* If a park is selected, show only that park info and change button */}
                        {selectedPark ? (
                            <View style={{ width: BUTTON_WIDTH, alignItems: "center" }}>
                                <List.Item
                                    title={selectedPark.name}
                                    description={
                                        `${selectedPark.address}\n${selectedPark.city}, ${selectedPark.state} ${selectedPark.zip}`
                                    }
                                    left={props => <List.Icon {...props} icon="paw" />}
                                    style={{
                                        backgroundColor: theme.colors.surface,
                                        borderRadius: 8,
                                        marginBottom: 8,
                                        elevation: 1,
                                        width: "100%"
                                    }}
                                    titleStyle={{ fontWeight: "bold" }}
                                    descriptionNumberOfLines={2}
                                />
                                <Button
                                    mode="outlined"
                                    onPress={() => {
                                        setSelectedPark(null);
                                        setParks([]);
                                        setHasSearched(false);
                                    }}
                                    style={{ marginTop: 16, width: "100%" }}
                                >
                                    Change Park
                                </Button>
                            </View>
                        ) : (
                            // Otherwise show location lookup tools and park list
                            <>
                                <Button
                                    mode="outlined"
                                    onPress={handleGetLocation}
                                    loading={locLoading}
                                    disabled={locLoading}
                                    style={{ marginBottom: 12, width: BUTTON_WIDTH }}
                                >
                                    Use My Location
                                </Button>
                                <Text style={{ marginBottom: 12, color: theme.colors.primary, fontWeight: "bold" }}>OR</Text>
                                <View style={{
                                    flexDirection: "row",
                                    alignItems: "center",
                                    width: BUTTON_WIDTH,
                                    justifyContent: "center",
                                    marginBottom: 4,
                                }}>
                                    <TextInput
                                        label="Enter Zip Code"
                                        mode="outlined"
                                        value={zip}
                                        onChangeText={setZip}
                                        style={{
                                            flex: 3,
                                            marginRight: 6,
                                            fontFamily: "SpaceReg",
                                            minWidth: 0,
                                        }}
                                        placeholderTextColor={theme.colors.primary}
                                        textColor={theme.colors.primary}
                                        theme={{ colors: { text: theme.colors.primary } }}
                                    />
                                    <Button
                                        mode="contained"
                                        onPress={handleSubmit}
                                        loading={loading}
                                        disabled={!zip || loading}
                                        style={{
                                            flex: 2,
                                            minWidth: 0,
                                            height: 50,
                                        }}
                                        contentStyle={{ height: 50 }}
                                    >
                                        Submit
                                    </Button>
                                </View>
                                <View style={{ width: BUTTON_WIDTH, marginTop: 10, alignItems: "center" }}>
                                    <Text style={{ color: theme.colors.primary, marginBottom: 2 }}>
                                        Distance: {distance} mile{distance !== 1 ? "s" : ""}
                                    </Text>
                                    <Slider
                                        style={{ width: "100%", height: 36 }}
                                        minimumValue={1}
                                        maximumValue={40}
                                        step={1}
                                        value={distance}
                                        onValueChange={setDistance}
                                        minimumTrackTintColor={theme.colors.primary}
                                        maximumTrackTintColor={theme.colors.onSurfaceDisabled || "#ccc"}
                                        thumbTintColor={theme.colors.primary}
                                    />
                                </View>
                                {/* Parks List */}
                                {hasSearched && (
                                    <View style={{ width: BUTTON_WIDTH, marginTop: 18, maxHeight: 200 }}>
                                        <Text style={{
                                            fontWeight: "bold",
                                            fontSize: 18,
                                            marginBottom: parks.length > 0 ? 8 : 2,
                                            color: theme.colors.primary
                                        }}>
                                            Nearby Dogparks
                                        </Text>
                                        {parks.length > 0 ? (
                                            <FlatList
                                                data={parks}
                                                keyExtractor={(item) => item.Id}
                                                renderItem={renderItem}
                                                showsVerticalScrollIndicator={false}
                                                style={{ maxHeight: 170 }}
                                            />
                                        ) : (
                                            <Text style={{ color: theme.colors.onSurface, textAlign: "center", marginTop: 12 }}>
                                                No parks found in range.
                                            </Text>
                                        )}
                                    </View>
                                )}
                            </>
                        )}
                    </View>
                </Dialog.Content>
            </Dialog>
        </Portal>
    );
};

export default LocationScreen;
