import React from "react";
import { View, Dimensions } from "react-native";
import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import {
  BottomDropdown,
  MyTouchableOpacity,
  MyText,
  tw,
  theme,
} from "common-ui";
import { useAuth } from "@/src/contexts/AuthContext";
import { trpc } from "@/src/trpc-client";
import { useAddressStore } from "@/src/store/addressStore";

const { width: screenWidth } = Dimensions.get("window");

interface AddressSelectorProps {
  mode?: "home";
  deliveryTime?: string;
}

const AddressSelector: React.FC<AddressSelectorProps> = ({
  mode = "home",
  deliveryTime,
}) => {
  const { isAuthenticated } = useAuth();
  const { selectedAddressId, setSelectedAddressId } = useAddressStore();

  const { data: defaultAddressData } =
    trpc.user.address.getDefaultAddress.useQuery();
  const { data: addressesData } = trpc.user.address.getUserAddresses.useQuery(
    undefined,
    {
      enabled: isAuthenticated,
    }
  );

  const defaultAddress = defaultAddressData?.data;
  const addresses = addressesData?.data || [];

  // Transform addresses for dropdown
  const addressOptions = addresses.map((address) => ({
    label: `${address.name} - ${address.addressLine1}, ${address.city}`,
    value: address.id,
  }));

  const handleAddressChange = (
    value: string | number | string[] | number[]
  ) => {
    const addressId = value as number;
    setSelectedAddressId(addressId);
  };

  // Helper to get display parts
  const getDisplayParts = (displayText?: string) => {
    const fullText =
      displayText ||
      (defaultAddress
        ? `${defaultAddress.name} - ${defaultAddress.addressLine1}, ${defaultAddress.city}`
        : "");
    let name = defaultAddress ? defaultAddress.name : "Home";
    let address = defaultAddress
      ? `${defaultAddress.addressLine1}, ${defaultAddress.city}`
      : "Add your delivery address";

    if (fullText) {
      const parts = fullText.split(" - ");
      if (parts.length >= 1) name = parts[0];
      if (parts.length > 1) address = parts.slice(1).join(" - ");
    }
    return { name, address };
  };

  const { name: defaultName, address: defaultAddr } = getDisplayParts();

  if (!isAuthenticated) {
    // Static display for non-authenticated users (Home mode)
    return (
      <View style={[{ width: screenWidth * 0.65 }, tw`mr-4`]}>
        <View style={tw`flex-row items-center mb-1`}>
          <View style={tw`bg-white/20 p-1 rounded-full `}>
            <MaterialIcons
              name="location-pin"
              size={14}
              color={'#fff'}
            />
          </View>
          <View style={tw``}>
            <MyText
              style={tw`text-white text-xs font-bold uppercase tracking-widest`}
            >
              Delivery to {defaultName}
            </MyText>
            <MyText
              style={tw`text-white text-sm font-medium opacity-90`}
              numberOfLines={1}
            >
              {defaultAddr}
            </MyText>
          </View>
        </View>
      </View>
    );
  }

  return (
    <BottomDropdown
      style={{ width: screenWidth * 0.65 }}
      label="Select Delivery Address"
      value={selectedAddressId || defaultAddress?.id || ""}
      options={addressOptions}
      onValueChange={handleAddressChange}
      placeholder="Select delivery address"
      triggerComponent={({ onPress, displayText }) => {
        const { name, address } = getDisplayParts(displayText);

        // Home styling
        return (
          <MyTouchableOpacity
            style={tw`flex-1 mr-4`}
            onPress={onPress}
            activeOpacity={0.8}
          >
            <View style={tw`flex-row items-center mb-1`}>
              <View style={tw`bg-white/20 p-1 rounded-full mr-2`}>
                <MaterialIcons
                  name="location-pin"
                  size={18}
                  // color={theme.colors.gray900}
                  color={'#fff'}
                />
              </View>
              <View style={tw``}>
                <View style={tw`flex-row`}>
                  <MyText
                    numberOfLines={1}
                    style={tw`text-white text-xs font-bold uppercase tracking-widest`}
                  >
                    to {name}
                  </MyText>
                  {/* <MaterialIcons
                    name="keyboard-arrow-down"
                    size={14}
                    color={theme.colors.gray900}
                    style={tw`ml-1`}
                  /> */}
                </View>
                <MyText
                  style={tw`text-white text-sm font-medium opacity-90`}
                  numberOfLines={1}
                >
                  {address}
                </MyText>
              </View>
            </View>
          </MyTouchableOpacity>
        );
      }}
    />
  );
};

export default AddressSelector;
