import { View, Text, Alert, TouchableOpacity } from "react-native";

import TimeAgo from "@andordavoti/react-native-timeago";

import { router } from "expo-router";

import { styled } from "nativewind";

import utmObj from "utm-latlng";

type QueryItemProps = {
  name: string;
  volume: string;
  price: string;
  date: Date;
  storeKey: string;
  distance: Number;
  perFloz: Number;
};

export default function QueryItem(props: QueryItemProps) {
  const utm = new utmObj();

  const StyledText = styled(Text);
  const StyledTimeAgo = styled(TimeAgo);

  const distanceInMeters = Math.round(Number(props.distance));
  const distance =
    distanceInMeters > 1609
      ? `${Math.round(distanceInMeters / 1609)} mi.`
      : `${Math.round(distanceInMeters * 3.28084)} ft.`;

  const navToStore = async () => {
    const res = await fetch(
      `${process.env.EXPO_PUBLIC_BACKEND_URL}/?` +
        new URLSearchParams({
          storeKey: props.storeKey,
        })
    );
    if (!res.ok)
      return Alert.alert(
        "Error!",
        "Server error. Please report to ak95@riseup.net"
      );

    const json = await res.json();
    const { lat, lng } = utm.convertUtmToLatLng(
      json.easting,
      json.northing,
      json.zone,
      json.zoneLetter
    );
    router.push({
      pathname: "/store/[coords]",
      params: {
        coords: `${lng}+${lat}`,
      },
    });
  };

  return (
    <TouchableOpacity onPress={navToStore}>
      <View
        className="flex flex-row w-[100vw] p-2 justify-between items-center border-b dark:text-white dark:border-white"
        style={{ flex: 1 }}
      >
        <View className="flex justify-center items-start gap-2">
          <StyledText className="text-xl dark:text-white">
            {props.name} ({props.volume} fl. oz.)
          </StyledText>
          <View className="flex flex-row items-center items-center">
            <StyledText className="text-lg dark:text-white">
              ${props.price}&nbsp;
            </StyledText>
            <StyledText className="text-lg dark:text-white">
              (${props.perFloz}/fl. oz.)
            </StyledText>
          </View>
        </View>
        <View className="flex justify-center items-end gap-2">
          <StyledText className="text-xl dark:text-white">
            {distance} away
          </StyledText>
          <StyledTimeAgo
            dateTo={props.date}
            className="text-lg dark:text-white"
          />
        </View>
      </View>
    </TouchableOpacity>
  );
}
