import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';
import countriesISO from 'i18n-iso-countries';
import langZh from 'i18n-iso-countries/langs/zh.json';
import Form from '../form';
import Input from '../input';
import Select from '../select';

import Modal, { ModalProps } from '../modal';
import countries from './countries';
import Row from '../row';
import Col from '../col';

countriesISO.registerLocale(langZh);

interface State {
  code: string;
  name: string;
}
interface Country {
  code: string;
  name: string;
  states: State[];
}

export interface AddressProps {
  firstName?: string;
  lastName?: string;
  address1?: string;
  address2?: string;
  city?: string;
  country?: string;
  province?: string;
  zip?: string | number;
  phone?: string | number;
}

export interface AddressModalProps extends Omit<ModalProps, 'children' | 'onOk'> {
  /** 额外的 FormItem */
  extraItem?: React.ReactNode;

  /** 值 */
  value?: AddressProps;

  /** 更新事件 */
  onChange?: (values: AddressProps) => void;
  onOk?: (values: AddressProps) => void;
}

const AddressModal: FC<AddressModalProps> = ({
  extraItem,
  title,
  visible,
  value,
  onOk,
  onChange,
  ...rest
}) => {
  const [form] = Form.useForm();

  // 选择国家代码，用于计算获取国家下面的省 / 州
  const [selectCountryCode, setSelectCountryCode] = useState<string>();

  // 获取国家下面的省 / 州
  const states: State[] | undefined = useMemo(
    () => (countries as Country[]).find((item: Country) => item.code === selectCountryCode)?.states,
    [selectCountryCode],
  );

  // 弹窗点击确认时将填写的信息丢出去
  const handleOk = useCallback(async () => {
    if (form) {
      const values = await form.validateFields();

      onOk?.({
        ...values,
        province: values?.province || null,
      });
    }
  }, [form, onOk]);

  // 传进来的数据进行初始化设置
  useEffect(() => {
    if (visible) {
      if (form) {
        form.resetFields();

        if (value) {
          form.setFieldsValue(value);

          setSelectCountryCode(value?.country);
        } else {
          setSelectCountryCode('');
        }
      }
    }
  }, [value, visible, form]);

  return (
    <Modal width={576} visible={visible} title={title || '编辑地址'} {...rest} onOk={handleOk}>
      <Form
        form={form}
        layout="vertical"
        onValuesChange={values => {
          onChange?.({
            ...values,
            province: values?.province || null,
          });
        }}
      >
        <Row gutter={20}>
          <Col span={12}>
            <Form.Item
              rules={[
                { required: true, pattern: /^(?!(\s+$))/, message: '该项为必填项，输入空格无效' },
              ]}
              label="名字"
              name="lastName"
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="姓氏"
              name="firstName"
              rules={[
                { required: true, pattern: /^(?!(\s+$))/, message: '该项为必填项，输入空格无效' },
              ]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="address1"
          label="地址"
          rules={[
            { required: true, pattern: /^(?!(\s+$))/, message: '该项为必填项，输入空格无效' },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item name="address2" label="公寓、房间号等">
          <Input />
        </Form.Item>

        <Row gutter={20}>
          <Col span={states?.length ? 6 : 8}>
            <Form.Item
              name="city"
              label="城市"
              rules={[
                { required: true, pattern: /^(?!(\s+$))/, message: '该项为必填项，输入空格无效' },
              ]}
            >
              <Input />
            </Form.Item>
          </Col>

          <Col span={states?.length ? 6 : 8}>
            <Form.Item
              name="country"
              label="国家/地区"
              rules={[{ required: true, message: '请选择国家/地区' }]}
            >
              <Select
                onChange={val => {
                  setSelectCountryCode(val as string);
                }}
                options={(countries as Country[]).map(country => ({
                  label: countriesISO.getName(country.code, 'zh'),
                  value: country.code,
                }))}
              />
            </Form.Item>
          </Col>

          {states?.length ? (
            <Col span={6}>
              <Form.Item
                initialValue={states[0].code}
                name="province"
                label="省/州"
                rules={[
                  { required: true, pattern: /^(?!(\s+$))/, message: '该项为必填项，输入空格无效' },
                ]}
              >
                <Select
                  options={states?.map(state => ({ label: state.name, value: state.code }))}
                />
              </Form.Item>
            </Col>
          ) : null}

          <Col span={states?.length ? 6 : 8}>
            <Form.Item
              name="zip"
              label="邮政编码"
              rules={[
                {
                  required: true,
                  pattern: /^(?!(\s+$))/,
                  message: '该项为必填项，输入空格无效',
                },
              ]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="联系电话"
          name="phone"
          style={{ marginBottom: extraItem ? undefined : 0 }}
        >
          <Input />
        </Form.Item>

        {extraItem}
      </Form>
    </Modal>
  );
};

export default AddressModal;
