import * as React from 'react';
import { Breadcrumb } from 'office-ui-fabric-react/lib/components/Breadcrumb/Breadcrumb';
import { ListView } from '../../../../Controls';
import { Command, OrganizationUnit, Position } 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, Dropdown, IconButton, Label } from 'office-ui-fabric-react';
import { NewCommandBar } from 'src/Controls/NewCommandsBar';
import { PositionService, OrganizationService, UserService } from 'src/Services';
import PositionType from 'src/Enums/PositionType';

export interface IData {
    columns: IColumn[];
    items: Position[];
}
export class PositionsList extends React.Component<any, any> {
    private _itemsService: PositionService = new PositionService();
    private _organizationsService: OrganizationService = new OrganizationService();
    private _userService: UserService = new UserService();

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

        this.loadItems();
        this.loadOrganizationUnits();
        this.loadUsers();
        this.loadColumns();
    }

    private loadColumns() {
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Arabic Display Name'></FormattedMessage>,
            fieldName: 'displayName_Ar',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='English Display Name'></FormattedMessage>,
            fieldName: 'displayName_En',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Type'></FormattedMessage>,
            fieldName: 'positionType',
            minWidth: 250,
            maxWidth: 350,
            onRender: (item?: Position, index?: number, column?: IColumn) => {

                if (item && item.positionType == PositionType.Manager)
                    return "Manager"

                if (item && item.positionType == PositionType.Employee)
                    return "Employee"

                if (item && item.positionType == PositionType.Deputy)
                    return "Deputy"
                return "";
            }
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Organization Unit'></FormattedMessage>,
            fieldName: 'organizationUnit',
            minWidth: 250,
            maxWidth: 350,
            onRender: (item?: Position, index?: number, column?: IColumn) => {

                if (item && item.organizationUnit)
                    return item.organizationUnit.name;

                return "";
            }
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Assigned User'></FormattedMessage>,
            fieldName: 'userDisplayName',
            minWidth: 250,
            maxWidth: 350
        });
    }

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

    private loadUsers() {
        this._userService.listUsers().then(result => {
            console.log(result);
            this.setState({ users: result })
        }, error => {
            alert(error.text());
        });
    }

    private loadOrganizationUnits() {
        this._organizationsService.listOrganizations().then(result => {
            let items = this.makeItems1D(result, undefined);
            console.log(items);

            this.setState({ organizationUnits: items })
        }, error => {
            alert(error.text());
        });
    }

    private makeItems1D(items: OrganizationUnit[] | null, parent: OrganizationUnit | undefined) {
        let orgs: Array<OrganizationUnit> = new Array<OrganizationUnit>();

        if (items)
            items.forEach((item: OrganizationUnit) => {
                orgs.push(item);

                orgs = orgs.concat(this.makeItems1D(item.organizationUnits, item));
            })

        return orgs;
    }

    private getCommonCommands(): any[] {
        let commands = new Array<any>();
        commands.push(
            {
                key: "addItem",
                name: "Create Position",
                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: Position) {
        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 {
        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: 'Positions', key: 'Positions', href: "/positions" }
                            ]}
                            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 Position" : "Add Position"}
                        headerClassName="panelHeaderStyle"
                        hasCloseButton={false}
                        onRenderHeader={this._onReadnderHader}
                        isFooterAtBottom={true}
                    >
                        <div className="ms-Grid-row ">
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <TextField onRenderLabel={this._onRenderFieldLabel.bind(this)} value={this.state.selectedItem.displayName_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.displayName_En} onChange={this._changeEnglishDisplayName.bind(this)}
                                    label="English Display Name"></TextField>
                            </div>
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <Label><FormattedMessage id='Type'></FormattedMessage></Label>
                                <Dropdown
                                    selectedKey={this.state.selectedItem.positionType}
                                    onChanged={this._changeType.bind(this)}
                                    options={[
                                        { key: 0, text: "Manager" },
                                        { key: 1, text: "Deputy" },
                                        { key: 2, text: "Employee" }]}></Dropdown>
                            </div>
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <Label><FormattedMessage id='Organization Unit'></FormattedMessage></Label>
                                <Dropdown
                                    selectedKey={this.state.selectedItem.organizationUnitId}
                                    onChanged={this._changeOrganizationUnit.bind(this)}
                                    options={this.state.organizationUnits.map((item: OrganizationUnit) => {
                                        return { key: item.id, text: item.name }
                                    })}></Dropdown>
                            </div>
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <Label><FormattedMessage id='Assigned User'></FormattedMessage></Label>
                                <Dropdown
                                    selectedKey={this.state.selectedItem.userId}
                                    onChanged={this._changeUser.bind(this)}
                                    options={this.state.users.map((item: any) => {
                                        return { key: item.id, text: item.name }
                                    })}></Dropdown>
                            </div>
                        </div>
                    </Panel>

                </div>
            </div>
        );
    }

    private renderItemDetailsPanelFooterContent = (): JSX.Element => {
        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.displayName_Ar = value;
        this.setState({ selectedItem: selectedItem })
    }

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

    private _changeOrganizationUnit(option: any) {
        var selectedItem = this.state.selectedItem;
        selectedItem.organizationUnitId = option.key;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeUser(option: any) {
        var selectedItem = this.state.selectedItem;
        selectedItem.userId = option.key;
        this.setState({ selectedItem: selectedItem })
    }

    private _changeType(option: any) {
        var selectedItem = this.state.selectedItem;
        selectedItem.positionType = 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._itemsService.savePosition(this.state.selectedItem).then(result => {
                console.log(result);
                this.loadItems();
                this.closeItemDetailsPanel();
            }, error => {
                alert(error.text());
            });
        }
    }

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

    private deleteItem() {

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

    }

}
