import React, { useCallback } from "react";
import { View, Text, TouchableOpacity, Linking, ViewStyle, Platform } from "react-native";
import { Icon, List, ActionSheet } from ".";
import { $Theme } from "./style";

type AddressProps = {
  address: string;
  phone: string;
  title: string;
  onClick?: (meta: AddressDataMeta) => void;
  location: {
    latitude: number;
    longitude: number;
  };
  style?: ViewStyle;
  OptionalComponent?: React.ComponentType<any> | React.ReactElement | null;
};
type AddressDataMeta = {
  coordinate: [number, number];
  title: string;
};

/**
 * 
 * @param 
 * OptionalComponent: could be any button like component, for example, copy
 * 
 * @returns 
 */
const Address: React.FC<AddressProps> = ({ address, title, phone, style, location, onClick, OptionalComponent }) => {
  const Dial = (phone: string) => {
    if (Platform.OS === "ios") {
      return Linking.openURL(`tel:${phone}`).then((r) => {});
    }
    ActionSheet.showActionSheetWithOptions(
      {
        options: [`拨打 ${phone}`, "Cancel"],
        cancelButtonIndex: 1,
      },
      (buttonIndex: any) => {
        if (buttonIndex === 0) {
          Linking.openURL(`tel:${phone}`).then((r) => {});
        }
      }
    );
  };
  const onViewMap = useCallback(() => {
    onClick &&
      onClick({
        coordinate: [location.longitude, location.latitude],
        title,
      });
  }, [location, title]);
    
  return (
    <List.Item style={[$Theme.flexRow, { flex: 1 }, style]}>
      <View style={[$Theme.flexRow, { flex: 1 }]}>
        <Icon name='location' style={{
          fontSize: 16,
          marginRight: 10
        }} />
        <View
          style={[$Theme.flexRowSpaceBetween, {
            flex: 1,
            borderRightWidth: 1,
            borderRightColor: $Theme.color_icon_base,
            marginRight: 10,
          }]}>
          <TouchableOpacity onPress={onViewMap} style={{ minWidth: '88%', maxWidth: '88%', }}>
            <Text numberOfLines={1}>地址：{address}</Text>
          </TouchableOpacity>
          {OptionalComponent}
        </View>
        <TouchableOpacity onPress={() => Dial(phone)}>
          <Icon name='phone' style={{
            fontSize: 24,
            color: $Theme.orange
          }} />
        </TouchableOpacity>
      </View>
    </List.Item>
  );
};
export default Address;
