import * as React from 'react';
import { Breadcrumb } from 'office-ui-fabric-react/lib/components/Breadcrumb/Breadcrumb';
import { ListView } from '../../../../Controls/ListView';
import { Command, OrganizationUnit, OrganizationUnitType } 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 { OrganizationService } from '../../../../Services';
import { FormattedMessage } from 'react-intl';
import { DocumentCard, TextField, Dropdown, IconButton, Label } from 'office-ui-fabric-react';
import { NewCommandBar } from 'src/Controls/NewCommandsBar';

export interface IData {
    columns: IColumn[];
    items: OrganizationUnit[];
}
export class OrganizationUnitList extends React.Component<any, any> {
    private _organizationsService: OrganizationService = new OrganizationService();

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

        this.loadOrganizationUnitTypes();
        this.loadColumns();
    }

    private loadColumns() {
        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,
            onRenderHeader: () => {
                debugger;
            }
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Short Name'></FormattedMessage>,
            fieldName: 'shortName',
            minWidth: 250,
            maxWidth: 350
        });
        this.state.columns.push({
            dataType: 'string',
            name: <FormattedMessage id='Type'></FormattedMessage>,
            fieldName: 'type',
            minWidth: 250,
            maxWidth: 350,
            onRender: (item?: OrganizationUnit, index?: number, column?: IColumn) => {
                let selectedType: OrganizationUnitType = { id: 0, name: "" };

                this.state.types.forEach((type: OrganizationUnitType) => {
                    if (item && type.id == item.type) {
                        selectedType = type;
                    }
                });

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

    private loadOrganizationUnitTypes() {
        this._organizationsService.getOrganizationUnitTypes().then(result => {
            this.setState({ types: result })
            this.loadItems();
        }, error => {
            alert(error.text());
        });
    }

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

            this.setState({ items: items })
            this.setState({ commands: this.getCommonCommands() });
        }, 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: "addOrganizationUnit",
                name: "Create Organization Unit",
                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: OrganizationUnit) {
        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: 'Organization Units', key: 'OrganizationUnits', href: "/organizationalUnits" }
                            ]}
                            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 Organization Unit" : "Add Organization Unit"}
                        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} 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} 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} value={this.state.selectedItem.shortName}
                                    onChange={this._changeShortName.bind(this)} label="Short Name"></TextField>
                            </div>
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <Label><FormattedMessage id="Type"></FormattedMessage> </Label>
                                <Dropdown
                                    selectedKey={this.state.selectedItem.type}
                                    onChanged={this._changeType.bind(this)}
                                    options={this.state.types.map((item: OrganizationUnitType) => {
                                        return { key: item.id, text: item.name }
                                    })}></Dropdown>
                            </div>
                            <div className={"ms-Grid-col ms-sm12 ms-lg12"}>
                                <Label><FormattedMessage id="Parent"></FormattedMessage> </Label>
                                <Dropdown onRenderTitle={this._onRenderFieldLabel}
                                    selectedKey={this.state.selectedItem.parentOrganizationUnitId}
                                    onChanged={this._changeParent.bind(this)}
                                    options={this.state.items.map((item: OrganizationUnit) => {
                                        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.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 _changeShortName(option: any, value: string) {
        var selectedItem = this.state.selectedItem;
        selectedItem.shortName = value;
        this.setState({ selectedItem: selectedItem })
    }

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

    private _changeType(option: any) {
        var selectedItem = this.state.selectedItem;
        selectedItem.type = 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._organizationsService.saveOrganization(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._organizationsService.deleteOrganization(this.state.selectedItem.id)
                .then(result => {
                    this.loadItems();
                }, error => {
                    alert(error.text());
                });
        }

    }

}
