import * as React from 'react';
import { Validation, ValidationState } from '../../models/Validation';
import { AddressModel } from '../../models/address';
import { Colors } from '../../models/colors';
import { AutoCompleteProps } from '../../containers/autocomplete/Autocomplete';
import { TooltipProps } from '../../containers/tooltip/Tooltip';
import { SecondaryButtonProps } from '../../containers/secondary-button/SecondaryButton';
import { ConfirmButtonProps } from '../../containers/confirm-button/ConfirmButton';
import { ModalProps } from '../../containers/modal/Modal';
import { CommonInputProps } from '../../containers/common-input/CommonInput';
import SecondaryButtonOne from '../../components/secondary-buttons/secondary-button-one/SecondaryButtonOne';
import ModalOne from '../../components/modals/modal-one/ModalOne';
import ModalTemplate from '../../templates/modal-template/ModalTemplate';
import ConfirmButtonOne from '../../components/confirm-buttons/confirm-button-one/ConfirmButtonOne';
import AddressList from './inner-comps/address-list/AddressList';
import ManuallyAddress from './inner-comps/manually-address/ManuallyAddress';
import Postcode from './inner-comps/postcode/Postcode';
import { Query } from '../../models/query';

const debounce = require('debounce');

interface AddressProps {
	palette?: Colors;
	validationState?: { [name: string]: Validation };
	notifyValidity?: (name: string, state: ValidationState, errorMessage?: string) => void;
	onChange?: (name: string, value: any) => void;
	autocomplete?: React.ReactElement<AutoCompleteProps>;
	automationName?: string;
	name: string;
	required?: boolean;
	tooltip?: React.ReactElement<TooltipProps>;
	tooltipContent?: string;
	lookupButton?: React.ReactElement<SecondaryButtonProps>;
	modalSubmitButton?: React.ReactElement<ConfirmButtonProps>;
	modalCancelButton?: React.ReactElement<SecondaryButtonProps>;
	modal?: React.ReactElement<ModalProps>;
	modalTemplate?: React.ReactElement<{}>;
	input?: React.ReactElement<CommonInputProps>;
	value?: AddressModel;
	setAddressOnStore?: (value: AddressModel) => void;
	translator?: Function;
	checkIfTranslateExist?: Function;
	query?: Query;
}

interface AddressState {
	postcodes: Array<{ label?: string; id?: number }>;
	selectedPostcode: { label?: string; id?: number };
	selectedAddressFromList: {
		record?: string;
		recordId?: string;
	};
	addressList: Array<{
		record?: string;
		recordId?: string;
	}>;
	[key: string]: any;
	notFoundClicked: boolean;
	showAddressInput: boolean;
	addressString: string;
}

class Address extends React.PureComponent<AddressProps, AddressState> {
	modal: any;

	constructor(props: AddressProps) {
		super(props);
		this.state = {
			postcodes: [],
			addressList: [],
			selectedAddressFromList: null,
			selectedPostcode: null,
			[this.props.name]: this.props.value || {},
			notFoundClicked: false,
			showAddressInput: false,
			addressString: null
		};
		this.onPostcodeChange = debounce(this.onPostcodeChange, 200);
	}

	clickLookUpAddressButton = () => {
		if (this.state.selectedPostcode) {
			console.log(this.state.selectedPostcode);
		} else {
			this.modal.open();
		}
	};

	onPostcodeClick = (postcode: { label: string; id: number }) => {
		this.setState(
			{
				selectedPostcode: postcode,
				[this.props.name]: Object.assign({}, this.state[this.props.name], {
					postcode: postcode.label
				})
			},
			this.clickLookUpAddressButton
		);
	};

	onPostcodeChange = (name: string, value: string) => {
		if (value.length >= 2) {
			// axios
			// 	.post('/address-lookup/postcode', { searchValue: value })
			// 	.then((response: AxiosResponse) => {
			// 		this.setState(state => {
			// 			return {
			// 				postcodes: response.data.data.items,
			// 				postcode: value,
			// 				[this.props.name]: Object.assign({}, state[this.props.name], {
			// 					postcode: value
			// 				})
			// 			};
			// 		});
			// 	})
			// 	.catch(() => {
			// 		this.setState(state => {
			// 			return {
			// 				postcodes: [],
			// 				[this.props.name]: Object.assign({}, state[this.props.name], {
			// 					postcode: value
			// 				})
			// 			};
			// 		});
			// 	});
			console.log(value);
		} else {
			this.setState(state => {
				return {
					postcodes: [],
					[this.props.name]: Object.assign({}, state[this.props.name], {
						postcode: value
					})
				};
			});
		}
		this.props.onChange(name, { title: value });
	};

	onAddressClick = (address: { record: string; recordId: string }) => {};

	setAddressOnStore = () => {
		if (this.props.setAddressOnStore) {
			this.props.setAddressOnStore(this.state[this.props.name]);
		} else {
			this.props.onChange(this.props.name, this.state[this.props.name]);
		}
		this.modal.close();
		this.setState(state => {
			const address = state[this.props.name];
			return {
				showAddressInput: !!address,
				addressString: address
					? [
							address.addressLine1,
							address.addressLine2,
							address.addressLine3,
							address.town,
							address.country,
							address.postcode
					  ]
							.filter(x => x)
							.join(', ')
					: ''
			};
		});
	};

	saveAddressOnState = (name: string, value: AddressModel) => {
		this.setState({
			[name]: value
		});
	};

	clickClearButton = () => {
		this.setState(
			{
				showAddressInput: false,
				addressString: null,
				[this.props.name]: null,
				selectedPostcode: { label: '' }
			},
			() => {
				this.setAddressOnStore();
				this.onPostcodeChange('postcode', '');
			}
		);
	};

	render() {
		const modalCancelButton = React.cloneElement(
			this.props.modalCancelButton || <SecondaryButtonOne />,
			this.state.addressList.length && !this.state.notFoundClicked
				? {
						text: `addressListModal.notFound`,
						automationName: `${this.props.name}.notFound`,
						palette: this.props.palette,
						onClick: () => {
							this.setState({ notFoundClicked: true });
						},
						translator: this.props.translator
				  }
				: {
						text: `manualAddressModal.cancel`,
						automationName: `${this.props.name}.cancel`,
						palette: this.props.palette,
						onClick: () => {
							if (this.modal) {
								this.setState({ notFoundClicked: false, [this.props.name]: {} });
								this.modal.close();
								return;
							}
							return false;
						},
						translator: this.props.translator
				  }
		);
		let modal = React.cloneElement(
			this.props.modal || <ModalOne />,
			{
				onRef: (ref: any) => (this.modal = ref),
				palette: this.props.palette,
				title:
					this.state.addressList.length && !this.state.notFoundClicked
						? 'addressListModal.title'
						: 'manualAddressModal.title',
				translator: this.props.translator
			},
			<ModalTemplate
				name="modal-template"
				application={this.state}
				onSubmit={this.setAddressOnStore}
				moreButtons={[modalCancelButton]}
				submitButton={
					this.props.modalSubmitButton || (
						<ConfirmButtonOne
							text="manualAddressModal.confirm"
							automationName="manualAddressModal.confirm"
							translator={this.props.translator}
						/>
					)
				}
				palette={this.props.palette}
				onChange={this.saveAddressOnState}
			>
				{this.state.addressList.length && !this.state.notFoundClicked ? (
					<AddressList
						palette={this.props.palette}
						list={this.state.addressList}
						selectedAddressFromList={this.state.selectedAddressFromList}
						onAddressClick={this.onAddressClick}
					/>
				) : (
					<ManuallyAddress name={this.props.name} />
				)}
			</ModalTemplate>
		);

		return (
			<React.Fragment>
				<Postcode
					palette={this.props.palette}
					name={this.props.name}
					required={this.props.required}
					autocomplete={this.props.autocomplete}
					tooltip={this.props.tooltip}
					notifyValidity={this.props.notifyValidity}
					lookupButton={this.props.lookupButton}
					postcodes={this.state.postcodes}
					selectedPostcode={this.state.selectedPostcode}
					clickLookUpAddressButton={this.clickLookUpAddressButton}
					optionClick={this.onPostcodeClick}
					onChange={this.onPostcodeChange}
					showAddressInput={this.state.showAddressInput}
					addressString={this.state.addressString}
					clickClearButton={this.clickClearButton}
					translator={this.props.translator}
					checkIfTranslateExist={this.props.checkIfTranslateExist}
					query={this.props.query}
				/>
				{modal}
			</React.Fragment>
		);
	}
}

export default Address;
