import * as React from 'react';

import { Dropdown as FabricUiDropDown, IDropdownProps, IDropdownOption } from 'office-ui-fabric-react/lib/components/Dropdown';
import { BaseComponent } from 'office-ui-fabric-react/lib/Utilities';
import { RecordField } from 'src/Models';
import { RecordService } from '../../Services';
import Label from 'reactstrap/lib/Label';

interface IDropdownCustomProps extends IDropdownProps {
    field: RecordField;
}

export class Dropdown extends BaseComponent<IDropdownCustomProps, any> {

    private _recordService: RecordService = new RecordService();

    constructor(props: any) {
        super(props);
        this.state = {
            contactDetails: null
        }
    }

    private _showContactDetails(recordId: any) {
        if (this.props.field && this.props.field.id == 202) {
            this._recordService.getRecord(17, recordId).then(
                result => {
                    this.setState({ contactDetails: result });


                },
                error => {
                    alert(error);
                }
            );
        }
    }

    private onChanged(option: IDropdownOption, index?: number) {

        if (this.props.field && this.props.field.id == 202) {
            this._showContactDetails(option.key);
        }

        if (this.props.onChanged)
            this.props.onChanged(option, index);
    }

    public render(): JSX.Element {
        return (
            <div>
                <FabricUiDropDown
                    {...this.props}
                    onChanged={this.onChanged.bind(this)}>
                </FabricUiDropDown>
                {
                    this.props.field && this.props.field.id == 202 && this.state.contactDetails &&
                    <div style={{ margin: "10px -8px"}}>
                        {this.state.contactDetails.fields.map((field: RecordField) => {
                            if (field.id == 183 || field.id == 187 || field.id == 188)
                                return <div className="ms-Grid-col ms-sm12 ms-lg4" key={`form-field-${field.id}`}>
                                    <Label>{field.displayName}</Label>
                                    <div className="form-field-view">
                                        {field.data}
                                    </div>
                                </div>
                            else
                                return "";
                        })
                        }
                    </div>

                }
            </div>
        );
    }
}

