import * as React from 'react';
import { Breadcrumb } from 'office-ui-fabric-react/lib/components/Breadcrumb/Breadcrumb';
import { ListView } from '../../../../Controls/ListView';
import { Command, OrganizationUnit, Position, User, Country } from '../../../../Models';
import { Panel } from 'office-ui-fabric-react/lib/components/Panel/Panel';
import { PanelType } from 'office-ui-fabric-react/lib/components/Panel/Panel.types';
import { PrimaryButton } from 'office-ui-fabric-react/lib/components/Button/PrimaryButton/PrimaryButton';
import { DefaultButton } from 'office-ui-fabric-react/lib/components/Button/DefaultButton/DefaultButton';
import { IColumn } from 'office-ui-fabric-react/lib/components/DetailsList/DetailsList.types';
import { FormattedMessage } from 'react-intl';
import { DocumentCard, TextField, IconButton, Dropdown, DetailsList, Label } from 'office-ui-fabric-react';
import { NewCommandBar } from 'src/Controls/NewCommandsBar';
import { UserService, SecurityService } from 'src/Services';

export interface IData {
    columns: IColumn[];
    items: Position[];
}
export class UsersList extends React.Component<any, any> {
    private _itemsService: UserService = new UserService();
    private _securityService: SecurityService = new SecurityService();

    constructor(props: any) {
        super(props);
        this.state = {
            showItemDetailsPanel: false,
            commands: new Array<Command>(),
            items: new Array<User>(),
            columns: new Array<IColumn>(),
            selectedItem: {},
            organizationUnits: new Array<OrganizationUnit>(),
            users: [],
            countries: [],
            adSearchedUsers: []
        };

        this.loadItems();
        this.loadColumns();
        this.loadCountries();
    }

    private loadColumns() {
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='UserName'></FormattedMessage>,
            fieldName: 'username',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Arabic Display Name'></FormattedMessage>,
            fieldName: 'name_Ar',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='English Display Name'></FormattedMessage>,
            fieldName: 'name_En',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Email'></FormattedMessage>,
            fieldName: 'email',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Phone Number'></FormattedMessage>,
            fieldName: 'phoneNumber',
            minWidth: 250,
            maxWidth: 350
        });
    }

    private loadItems() {
        this._itemsService.listUsers().then(result => {
            console.log(result);
            this.setState({ items: result })
            this.setState({ commands: this.getCommonCommands() });
        }, error => {
            alert(error.text());
        });
    }

    private loadCountries() {
        this._itemsService.listCountries().then(result => {

            this.setState({ countries: result })
        }, error => {
            alert(error.text());
        });
    }


    private getCommonCommands(): any[] {
        let commands = new Array<any>();
        commands.push(
            {
                key: "addItem",
                name: "Create User Account",
                iconProps: {
                    iconName: "Add"
                },
                onClick: this.addItem.bind(this)

            });

        return commands;
    }

    private getItemCommands(): any[] {
        let commands = this.getCommonCommands();
        commands.push(
            {
                key: "edit",
                name: "Edit",
                iconProps: {
                    iconName: "Edit"
                },
                onClick: this.editItem.bind(this)
            },
            {
                key: "removeUser",
                name: "Remove",
                iconProps: {
                    iconName: "Delete"
                },
                onClick: this.deleteItem.bind(this)
            }
        );

        return commands;
    }

    private selectedItemChanged(item: User) {
        if (!item)
            return;

        this.setState({ selectedItem: JSON.parse(JSON.stringify(item)), commands: this.getItemCommands() })
    }

    private _onRenderItem = (item: any): JSX.Element | null => {
        return <FormattedMessage id={item.text} />;
    }

    private _onReadnderHader = (item: any): JSX.Element | null => {
        return (
            <div className="ms-Panel-commands" data-is-visible="true">
                <div className="ms-Panel-navigation navigation_1033a520">
                    <h2 className="panel-header-text "><FormattedMessage id={item.headerText} /></h2>
                    <IconButton className="ms-Panel-closeButton ms-PanelAction-close custom" onClick={item.onDismissed.bind(this)}
                        iconProps={{ iconName: 'ChromeClose', style: { fontSize: 12 } }}></IconButton>
                </div>
            </div>
            // <div className="panel-header-text "><FormattedMessage id={item.headerText} /></div>
        )
    }

    private _onRenderFieldLabel = (item: any): JSX.Element | null => {
        return (
            <Label><FormattedMessage id={item.label}></FormattedMessage></Label>
            // <div className="panel-header-text "><FormattedMessage id={item.headerText} /></div>
        )
    }

    public render(): JSX.Element {

        let  adUserColumns:any=[
            {
                key: 'name',
                name: <FormattedMessage id='Name'></FormattedMessage>,
                fieldName: 'name',
                minWidth: 0,
                maxWidth: 0
            },
            {
                key: 'email',
                name: <FormattedMessage id='Email'></FormattedMessage>,
                fieldName: 'email',
                minWidth: 0,
                maxWidth: 0
            },
            {
                key: 'actions',
                name: '',
                fieldName: 'actions',
                minWidth: 0,
                maxWidth: 0,
                onRender: (item?: any, index?: number, column?: IColumn) => {
                    if (item)
                        return <PrimaryButton onClick={this.addAdUser.bind(this, item.username)}>Add</PrimaryButton>
                    return "";
                }
            }
        ];

        return (
            <div className="ms-Grid-row">
                <div className="ms-Grid-col ms-sm12">
                    <div className="breadcrumb-container">
                        <i className={'fal fa-users'} />
                        <Breadcrumb
                            items={[
                                { text: 'User Accounts', key: 'Users', href: "/userAccounts" }
                            ]}
                            ariaLabel={'Website breadcrumb'}
                            onRenderItem={this._onRenderItem}
                        />
                    </div>


                    <div className={"ms-Grid-col ms-sm12 ms-md12 ms-lg12"}>
                        <DocumentCard className="w-100p layout-card">
                            <div>
                                <NewCommandBar Commands={this.state.commands} />
                            </div>
                            <div>
                                <ListView
                                    selectionModeType={true}
                                    Items={this.state.items}
                                    SelectedItemChanged={this.selectedItemChanged.bind(this)}
                                    Columns={this.state.columns} />
                            </div>
                        </DocumentCard>
                    </div>


                    <Panel
                        className="panelStyle"
                        isOpen={this.state.showItemDetailsPanel}
                        onDismissed={this.closeItemDetailsPanel.bind(this)}
                        type={PanelType.medium}
                        onRenderFooter={this.renderItemDetailsPanelFooterContent.bind(this)}
                        headerText={this.state.selectedItem.id ? "Edit User Account" : "Add User Account"}
                        headerClassName="panelHeaderStyle"
                        hasCloseButton={false}
                        onRenderHeader={this._onReadnderHader}
                        isFooterAtBottom={true}
                    >
                        <div className="ms-Grid-row ">
                            {!this.state.selectedItem.id &&
                                <div>
                                    <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                        <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.userName} onChange={this._changeUserName.bind(this)}
                                            label="Search by User Name"></TextField>
                                        <PrimaryButton style={{ marginTop: '10px', float: 'right' }} onClick={this.searchByUserName.bind(this)}>
                                            <FormattedMessage id="Search"></FormattedMessage>
                                    </PrimaryButton>
                                    </div>
                                    {
                                        this.state.adSearchedUsers && this.state.adSearchedUsers.length > 0 &&
                                        <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                            <DetailsList items={this.state.adSearchedUsers}
                                                columns={adUserColumns}></DetailsList>
                                        </div>
                                    }

                                </div>
                            }
                            {!this.state.selectedItem.id && false &&
                                <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                    <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} type='password' value={this.state.selectedItem.password} onChange={this._changePassword.bind(this)}
                                        label="Password"></TextField>
                                </div>
                            }
                            {!this.state.selectedItem.id && false &&
                                <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                    <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} type='password' value={this.state.selectedItem.confirmPassword} onChange={this._changeConfirmPassword.bind(this)}
                                        label="Confirm Password"></TextField>
                                </div>
                            }
                            {!this.state.selectedItem.id && false &&
                                <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                    <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.email} onChange={this._changeEmail.bind(this)}
                                        label="Email"></TextField>
                                </div>
                            }
                            {!this.state.selectedItem.id && false &&
                                <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                    <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.confirmEmail} onChange={this._changeConfirmEmail.bind(this)}
                                        label="Confirm Email"></TextField>
                                </div>
                            }
                            {this.state.selectedItem.id &&
                                <div>
                                    <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                        <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.name_Ar} onChange={this._changeArabicDisplayName.bind(this)}
                                            label="Arabic Display Name"></TextField>
                                    </div>
                                    <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                        <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.name_En} onChange={this._changeEnglishDisplayName.bind(this)}
                                            label="English Display Name"></TextField>
                                    </div>

                                    <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                        <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.phoneNumber} onChange={this._changePhoneNumber.bind(this)}
                                            label="Phone Number"></TextField>
                                    </div>
                                    <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                    <Label><FormattedMessage id='Country'></FormattedMessage></Label>
                                        <Dropdown
                                            selectedKey={this.state.selectedItem.countryId}
                                            onChanged={this._changeCountry.bind(this)}
                                            options={this.state.countries.map((item: Country) => {
                                                return { key: item.id, text: item.name }
                                            })}></Dropdown>
                                    </div>
                                </div>
                            }
                        </div>
                    </Panel>

                </div>
            </div>
        );
    }

    private renderItemDetailsPanelFooterContent = (): JSX.Element => {
        if (!this.state.selectedItem.id) {
            return <div></div>;
        }
        return (
            <div className="sticky-footer-btns" >
                <PrimaryButton className="panel-footer-btn" onClick={this.saveItem.bind(this)}>
                    <FormattedMessage id="Save"></FormattedMessage>
                    </PrimaryButton>
                <DefaultButton className="panel-footer-btn" onClick={this.closeItemDetailsPanel.bind(this)}>
                    <FormattedMessage id="Cancel"></FormattedMessage>
                    </DefaultButton>
            </div>
        );
    };

    private _changeArabicDisplayName(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.name_Ar = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeEnglishDisplayName(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.name_En = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeEmail(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.email = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeConfirmEmail(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.confirmEmail = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changePhoneNumber(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.phoneNumber = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeUserName(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.userName = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changePassword(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.password = value;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeConfirmPassword(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.confirmPassword = value;
        this.setState({ selectedItem: selectedItem })
    }

    private searchByUserName() {

        if (this.state.selectedItem.userName) {
            this._itemsService.searchUsers(this.state.selectedItem.userName).then(result => {
                console.log(result);
                this.setState({ adSearchedUsers: result });
            }, error => {
                alert(error.text());
            });
        }
    }

    _changeCountry(option: any) {
        var selectedItem = this.state.selectedItem;
        selectedItem.countryId = option.key;
        this.setState({ selectedItem: selectedItem })
    }

    private addItem() {
        this.setState({ showItemDetailsPanel: true, selectedItem: {} });
    }

    private editItem() {
        this.setState({ showItemDetailsPanel: true });
    }

    private saveItem() {
        if (this.state.selectedItem && this.state.selectedItem.id) {
            this._itemsService.saveUser(this.state.selectedItem).then(result => {
                console.log(result);
                this.loadItems();
                this.closeItemDetailsPanel();
            }, error => {
                alert(error.text());
            });
        }
        else {
            this._securityService.register(this.state.selectedItem).then(result => {
                console.log(result);
                this.loadItems();
                this.closeItemDetailsPanel();
            }, error => {
                alert(error.text());
            });
        }
    }

    private addAdUser(username: string) {
        this._securityService.register({
            username: username
        }).then(result => {
            console.log(result);
            this.loadItems();
            this.closeItemDetailsPanel();
        }, error => {
            alert(error.response.data[0]);
        });
    }

    private closeItemDetailsPanel() {
        this.setState({ showItemDetailsPanel: false });
    }

    private deleteItem() {

        if (this.state.selectedItem && this.state.selectedItem.id) {
            this._itemsService.deleteUser(this.state.selectedItem.id)
                .then(result => {
                    this.loadItems();
                }, error => {
                    alert(error.text());
                });
        }

    }

}
