import { View, ScrollView, StyleSheet } from "react-native";
import { useEffect } from "react";
import {useTheme, Text, Card, ActivityIndicator} from "react-native-paper";
import { useLocalSearchParams } from "expo-router";
import useLocationStore from "@/locationStore";

export default function Location() {
  const theme = useTheme();
  const { id } = useLocalSearchParams();
  const getLocation = useLocationStore((state) => state.getLocation);
  const fetchLocations = useLocationStore((state) => state.fetchLocations);
  const loading = useLocationStore((state) => state.loading);

  const location = getLocation(id);

  useEffect(() => {
    if (!location && !loading) {
      fetchLocations();
    }
  }, [location, loading, fetchLocations]);

  if (loading) {
    return (
        <View style={[styles.container, {backgroundColor: theme.colors.background}]}>
          <ActivityIndicator size="large" color={theme.colors.primary}/>
        </View>
    );
  }

  if (!location) {
    return (
        <View style={styles.container}>
          <Text style={styles.text}>Brak lokalizacji - {id}</Text>
        </View>
    );
  }


  return (
    <View style={[styles.container, {backgroundColor: theme.colors.background}]}>
      <ScrollView>
        <Card style={{ margin: 10 }}>
          <Card.Cover
            style={{ marginBottom: 10 }}
            source={location.imageSource}
          />
          <Card.Content style={{ marginBottom: 10 }}>
            <Text variant="headlineLarge" style={{ marginBottom: 10 }}>
              {location.name}
            </Text>
            <Text variant="headlineLarge" style={{ marginBottom: 10 }}>
              Opis:
            </Text>
            <Text variant="bodyMedium">{location.description}</Text>
          </Card.Content>

          <Card.Content>
            <Text variant="headlineLarge" style={{ marginBottom: 10 }}>
              Statystyki:
            </Text>
            <Text variant="bodyMedium" style={{ marginBottom: 10 }}>
              Powierzchnia: {location.area} km²
            </Text>
            <Text variant="bodyMedium" style={{ marginBottom: 10 }}>
              Ludność: {location.population} osób
            </Text>
            <Text variant="bodyMedium" style={{ marginBottom: 10 }}>
              Współrzedne geograficzne: {location.latitude}, {location.longitude}
            </Text>
          </Card.Content>
        </Card>
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#25292e",
    justifyContent: "center",
  },
  text: {
    color: "#fff",
  },
});
