import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { Div, Button, Text, Tag, Toggle, Icon } from 'react-native-magnus';
import { ScrollView } from 'react-native-gesture-handler';
import { InputItem } from '@ant-design/react-native';

import { useRoute } from '@react-navigation/native';
import { useRequest, useToggle, useBoolean, useCreation } from '@umijs/hooks';
import useModel from 'flooks';
import AddressModel from './model'; // detail模块通用方法

import Header from '../../components/Header';

const AddressTag = new Map([
  ['HOME', { name: '家', key: 'HOME' }],
  ['COMPANY', { name: '公司', key: 'COMPANY' }],
  ['SCHOOL', { name: '学校', key: 'SCHOOL' }],
]);

export default function EditAddressScreen({ navigation }) {
  const route = useRoute();
  const { params } = route;

  const { id, locationInfo } = params || { id: 0 };

  const { saveAddress } = useModel(AddressModel, []);

  const [addressInfo, setaddressInfo] = React.useState({});

  const [phone, setphone] = React.useState('');
  const [name, setName] = React.useState('');
  const [addressName, setaddressName] = React.useState('');
  const [number, setnumber] = React.useState('');
  const isDefaultEvent = useBoolean();
  const [addressTag, setaddressTag] = React.useState('');
  const [longitude, setlongitude] = React.useState('');
  const [latitude, setlatitude] = React.useState('');

  const sexEvent = useToggle('先生', '女士');

  React.useEffect(() => {
    if (locationInfo) {
      const { poiaddress, poiname, latlng } = locationInfo;
      setaddressName(poiaddress + poiname);

      setlatitude(latlng.lat);
      setlongitude(latlng.lng);
    }
  }, [locationInfo]);

  const canSub = useCreation(() => {
    if (phone && name && addressName && number && longitude && latitude) {
      return true;
    } else {
      return false;
    }
  }, [
    phone,
    name,
    addressName,
    number,
    isDefaultEvent.state,
    sexEvent.state,
    addressTag,
    longitude,
    latitude,
  ]);

  useRequest(
    () => {
      if (id) {
        return `/address/get/${id}`;
      } else {
        return Promise.resolve(null);
      }
    },
    {
      refreshDeps: [id],
      onSuccess: (result) => {
        if (result) {
          setaddressInfo(result);
        } else {
          setaddressInfo({});
        }
      },
    }
  );

  React.useEffect(() => {
    if (addressInfo.id) {
      setName(addressInfo.name);
      setphone(addressInfo.phone);
      setaddressName(addressInfo.addressName);
      setnumber(addressInfo.number);
      isDefaultEvent.toggle(addressInfo.isDefault);
      setaddressTag(addressInfo.addressTag);
      setlatitude(addressInfo.latitude);
      setlongitude(addressInfo.longitude);
    }
  }, [addressInfo]);

  return (
    <>
      <Header title="编辑地址" noBack={false} />
      <ScrollView>
        <Div bg="white">
          <InputItem
            clear
            value={name}
            onChange={setName}
            placeholder="输入手机号"
            style={{ fontSize: 14 }}
          >
            <Text fontSize="xs" textAlign="left">
              姓名
            </Text>
          </InputItem>
          <Div row py={15}>
            <Button
              onPress={() => sexEvent.setLeft()}
              h={30}
              ml={63}
              w={40}
              fontSize="xs"
              bg={sexEvent.state === '先生' ? 'brand500' : 'gray200'}
              color={sexEvent.state === '先生' ? 'white' : 'gray600'}
            >
              先生
            </Button>
            <Button
              onPress={() => sexEvent.setRight()}
              h={30}
              w={40}
              ml={15}
              fontSize="xs"
              bg={sexEvent.state === '女士' ? 'brand500' : 'gray200'}
              color={sexEvent.state === '女士' ? 'white' : 'gray600'}
            >
              女士
            </Button>
          </Div>
          <InputItem
            clear
            type="phone"
            value={phone}
            onChange={setphone}
            placeholder="输入手机号"
            style={{ fontSize: 14 }}
          >
            <Text fontSize="xs" textAlign="left">
              手机号
            </Text>
          </InputItem>
          <Button
            bg="hide"
            block
            p={0}
            rounded="none"
            onPress={() =>
              navigation.navigate('SearchMap', {
                type: 'addAddress',
              })
            }
          >
            <Div
              flex={1}
              row
              py={15}
              ml={15}
              borderBottomWidth={1}
              borderColor="gray100"
              mr={0}
            >
              <Text fontSize="xs" w={71}>
                收货地址
              </Text>
              <Text color={addressName ? 'gray600' : 'gray300'} flex={1}>
                {addressName || '请选址收货地址'}
              </Text>
              <Icon mr={15} fontSize="sm" name="right" color="#000" />
            </Div>
          </Button>

          <InputItem
            clear
            value={number}
            onChange={setnumber}
            placeholder="请输入门牌号"
            style={{ fontSize: 14 }}
          >
            <Text fontSize="xs" textAlign="left">
              门牌号
            </Text>
          </InputItem>
          <Div row p={15} alignItems="center">
            <Text fontSize="xs" w={71} textAlign="left">
              标签
            </Text>

            {[...AddressTag.keys()].map((key) => {
              const isChoose = key === addressTag;
              return (
                <Tag
                  bg={isChoose ? 'brand500' : 'gray200'}
                  color={isChoose ? 'white' : ''}
                  fontSize="xs"
                  mr={10}
                  onPress={() => setaddressTag(key)}
                >
                  {AddressTag.get(key).name}
                </Tag>
              );
            })}
          </Div>
        </Div>
        <Div row alignItems="center" p={15}>
          <Toggle
            on={isDefaultEvent.state}
            onPress={() => isDefaultEvent.toggle()}
            bg="gray200"
            circleBg="brand500"
            activeBg="brand500"
            h={30}
            w={60}
          />
          <Text ml={15}>设为默认</Text>
        </Div>

        <Button
          disabled={!canSub}
          bg="brand500"
          m={20}
          block
          onPress={() => {
            saveAddress(
              id,
              name,
              sexEvent.state,
              phone,
              addressName,
              number,
              addressTag,
              isDefaultEvent.state,
              latitude,
              longitude
            ).then(() => {
              navigation.goBack();
            });
          }}
        >
          保存
        </Button>
      </ScrollView>
    </>
  );
}
