import { OrderedListOutlined, FormOutlined } from '@ant-design/icons';
import { DeleteOutlined, LoadingOutlined, RollbackOutlined } from "@ant-design/icons/lib";
import { Alert, Button, Checkbox, Col, Layout, Modal, Row, Space, Spin, Table, Tabs, Tag } from 'antd';
import Column from "antd/es/table/Column";
import { IStudioOrderPart } from 'lemans-api/models/StudioOrder/studioOrder.types';
import { ConfirmationModal, DeleteButton, flash, InlineEdit } from 'lemans-common';
import { useTrigger } from 'lemans-common/libs/useToggle';
import { api, service, WithIntegrationProps } from 'lemans-dashboard-common';
import { permissionCheck } from 'lemans-uac';
import React from 'react';
import { prop } from 'ts-functional';
import { GoLiveColumn, PartBrandColumn, PartDetailsColumn, PartNCColumn, PartNonPunctuatedPartNumColumn, PartNVColumn, PartNYColumn, PartTagsColumn, PartTXColumn, PartVendorColumn, PartWIColumn } from '../../PartList/PartColumns/PartColumns.component';
import { PhotoReshootQueue } from "../../PhotoReshootQueue";
import { statusColor, statusTag } from "../studioOrder.helpers";
import { studioOrderUrl } from "../StudioOrderSearch/StudioOrderSearch.component";
import './StudioOrderDetails.styles.less';
import { StudioOrderDetailsProps } from './StudioOrderDetails.types';


type Props = WithIntegrationProps<StudioOrderDetailsProps>;
const TabPane = Tabs.TabPane;
const [CanView, CantView] = permissionCheck(['ds.studioOrder.view', 'ds.studioOrder.edit']);
const [CanEdit, CantEdit] = permissionCheck(['ds.studioOrder.edit']);


export const StudioOrderDetailsComponent = (props: Props) => {

    const [selectedParts, setSelectedParts] = React.useState([] as IStudioOrderPart[]);
    const showSelections = Array.from(new Set(props.parts.map(prop("statusDescr")))).length > 1;
    const orderFinished = props.details.status === 'Finished';
    const orderOpen = props.details.status === 'Open' || props.details.status === null;
    const orderSubmitted = props.details.status === 'Submitted';
    const orderCompleted = props.details.status === 'Shoot Complete';
    const shootCompleteParts = props.parts.filter((x: any) => x.statusDescr === 'Shoot Complete');
    const submittedParts = props.parts.filter((x: any) => x.statusDescr === 'Submitted');
    const noPartsSelected = selectedParts.length === 0;
    const partsWithSubmittedNotSelected = selectedParts.some((x: any) => x.statusDescr !== 'Submitted');
    const hasAnyShootComplete = props.parts.some((x: any) => x.statusDescr === 'Shoot Complete');
    const partsWithShootCompleteNotSelected = selectedParts.some((x: any) => x.statusDescr !== 'Shoot Complete');

    const [refresh, setRefresh] = useTrigger();
    const [isModalVisible, setModalVisibility] = React.useState(false);
    const [showForm, setShowForm] = React.useState(false);
    const [isLoading, setIsLoading] = React.useState(false);
	const [isNoteModalVisible, setIsNoteModalVisible] = React.useState(false);
    const [warningText, setWarningText] = React.useState('');

    const toggleForm = () => {
        showForm ? props.goTo(studioOrderUrl(props.studioOrderId), false, true) : props.onAddPartsModalOpen();
        setShowForm(!showForm);
    };

	const toggleNoteModal = () => setIsNoteModalVisible(!isNoteModalVisible);
	
    const toggleModal = () => setModalVisibility(!isModalVisible);

    React.useEffect(() => {
        setIsLoading(true);
        setSelectedParts([]);
        props.onSearch();
        setIsLoading(false);
    }, [refresh, props.studioOrderId]);

    const rowSelection = {
        getCheckboxProps: (record: any) => ({
            disabled: record.statusDescr === 'Finished',
        }),
        onChange: (_: any, prts: IStudioOrderPart[]) => {
            setSelectedParts(prts);
        },
        selectedRowKeys: selectedParts.map(prop("partNumber")),
        ...(showSelections && {
            selections: [
                {
                    key: 'shootComplete',
                    onSelect: (_: any) => setSelectedParts(shootCompleteParts),
                    text: 'Shoot Complete Only',
                },
                {
                    key: 'submitted',
                    onSelect: (_: any) => setSelectedParts(submittedParts),
                    text: 'Submitted Only',
                }
            ]
        })
    };

    const statusRender = (_: any, studioOrder: IStudioOrderPart) => statusTag(studioOrder.statusDescr);

    const actionColumnRender = (_: any, studioOrderPart: IStudioOrderPart) => {
        return <>
            <CanEdit>
                {props.details.status === 'Open' &&
                    <DeleteButton onDelete={deleteStudioOrderPart(studioOrderPart)} title="Delete Part">
                        <DeleteOutlined />
                        <>Are you sure you want to delete the Part <b>{studioOrderPart.partNumber}</b>?</>
                    </DeleteButton>
                }
            </CanEdit>
        </>;
    };

    const bulkActionOnStudioOrder = (parts: string[], action: string, successMessage: string, statusId?: number, onSuccess?: any) => {
        props.setLoading(true);
        service.studioOrder.parts.create(props.details.studioOrderId, { parts, action, ...(statusId ? { statusId } : {}) }).then(setRefresh).then(() => {
            setSelectedParts([]);
            flash.success(successMessage);
            props.setLoading(false);
            if (onSuccess) {
                onSuccess()
            }
        }).catch((err:any) => {
            props.setLoading(false);
            api.handleError(err);
        });
    };

    const addPartsToOrder = (partsSelected: string[]): Promise<boolean> => {
        return new Promise((resolve, reject) => {
            service.studioOrder.parts.createWithoutResults(props.details.studioOrderId, { parts: partsSelected, action: 'create' })
            .then((res:any) => { 
                setRefresh();
                // special handling of messages for just this endpoint
                if (res.messages && res.messages.length > 0) {
                    let wText = warningText;
                    res.messages.map((resWarning:any) => {
                        // flash.error(resWarning.text);
                        wText += resWarning.text+`\n`;
                    })
                    setWarningText(wText);
                    console.log(warningText)
                    flash.error(warningText);
                } else {
                    flash.success(`${partsSelected.length} part${partsSelected.length !== 1 ? 's' : ''} added to order`);
                }
                resolve(true);
            })
            // .then(setRefresh)
            // .then((res:any) => {
            //     flash.success(`${partsSelected.length} part${partsSelected.length !== 1 ? 's' : ''} added to order`);
            //     resolve(true);
            // })
            .catch((err: any) => {
                reject(false);
                console.error('Error fetching data:', err);
                api.handleError(err);
            });
        });
    };

    const deletePartsOnOrder = () => {
        bulkActionOnStudioOrder(selectedParts.map(prop("partNumber")), 'delete', 'Parts deleted from order');
    };

    const deleteStudioOrderPart = (studioOrderPart: IStudioOrderPart) => () => {
        bulkActionOnStudioOrder([studioOrderPart.partNumber], 'delete', `Part ${studioOrderPart.punctuatedPartNumber} deleted from order`);
    };

    const submitOrder = () => {
        props.setLoading(true);
        service.studioOrder.parts.getByStudioOrderId(props.details.studioOrderId).then((parts: any) => {
            bulkActionOnStudioOrder(parts.map((part: any) => part.partNumber), 'update', 'Order Submitted', 14201, goToListPage);
        })
    };

    const completeOrder = () => {
        bulkActionOnStudioOrder(selectedParts.map(prop("partNumber")), 'update', 'Parts Completed', 14202);
    };

    const finishOrder = () => {
        bulkActionOnStudioOrder(selectedParts.map(prop("partNumber")), 'update', 'Parts Finished', 14203);
    };

    const onOtherWarehouseChange = (event: any) => {
        setIsLoading(true);
        service.studioOrder.update(props.details.studioOrderId, {"otherWarehouse": event.target.checked}).then(() => {
            flash.success('Studio Order Updated');
            props.onWarehouseUpdate({...props.details, otherWarehouse: event.target.checked});
        }).catch(api.handleError).finally(() => {
            setIsLoading(false);
        })
    };

    const goToListPage = () => { props.goTo('/digital-services/studio-orders', false, true) };

    const showTotal = (total: number, range: [number, number]) => <>{range[0]} - {range[1]} of {total}</>;

	const updateNotes = (studioOrderId: number) => (value: any) => {
        return service.studioOrder.update(studioOrderId, {note: value}).then(() => {
            flash.success('Notes Updated');
            props.onWarehouseUpdate({...props.details, note: value});
        }).catch(api.handleError);
	}

    return (
        <Layout>
            <Layout.Content>
                <CanView>
                    <Modal visible={showForm} width={"98%"} footer={null}
                        onCancel={toggleForm} title="Add Parts to Order" destroyOnClose={true}>
                        <PhotoReshootQueue asSelector studioOrderPartSearch={true} studioOrderPartSearchCallBack={addPartsToOrder} />
                    </Modal>
					<Modal 
						className='studio-order-notes-modal'
						visible={isNoteModalVisible} 
						footer={null} 
						onCancel={toggleNoteModal} 
						title="Notes" 
						destroyOnClose={true}
					>
						<InlineEdit.TextArea
							id="studio-notes"
							value={props.details.note}
							saveChanges={updateNotes(props.details.studioOrderId)}
						/>
					</Modal>
                    <Row style={{ padding: "4px" }}>
                        <Col xs={12}>
                            <h1>
                                <Button type="link" size="large" onClick={goToListPage}>Studio Orders</Button>/&nbsp;
                            {!props.details.studioOrderId && <><LoadingOutlined spin /> Loading...</>}
                                {props.details.studioOrderId ? props.details.studioOrderName : ''}
                                {props.details.status ? <Tag color={statusColor(props.details.status)} style={{ marginLeft: "4px", fontWeight: 1000, fontSize: "90%" }}>{props.details.status}</Tag> : ''}
                            </h1>
                        </Col>
                        <Col xs={12} style={{ textAlign: "right" }}>
                            <Space>
                                <Button type="dashed" onClick={goToListPage}><RollbackOutlined />Back to Orders</Button>
								<Button onClick={toggleNoteModal}><FormOutlined />Notes</Button>
                                {orderOpen &&
                                    <CanEdit>
                                        <Space>
                                            <Button type="primary" onClick={toggleForm}> Add Parts to Order</Button>
                                            <Button onClick={toggleModal} disabled={props.parts.length === 0} className={"submit-button"}> Submit Order</Button>
                                        </Space>
                                        <ConfirmationModal title="Submit Order" onOk={submitOrder} isVisible={isModalVisible} toggleVisibility={toggleModal}>
                                            Are you sure you want to submit Order <b>{props.details.studioOrderName}</b>?
                                        </ConfirmationModal>
                                    </CanEdit>
                                }
                            </Space>
                        </Col>
                    </Row>
                    <Row>
                        <Col xs={24} style={{ padding: "8px" }}>
                            <Spin size="large" tip="Loading order parts..." spinning={isLoading || props.isLoading}>
                                <Tabs
                                    size="small"
                                    defaultActiveKey="1"
                                    tabBarExtraContent={
                                        <>
                                            <CantEdit>
                                                <div style={{ padding: "4px" }}>
                                                    <Space>
                                                        <Checkbox checked={props.details.otherWarehouse} disabled={true}>Other Warehouse</Checkbox>
                                                    </Space>
                                                </div>
                                            </CantEdit>
                                            <CanEdit>
                                                <div style={{ padding: "4px" }}>
                                                    <Space>
                                                        <Checkbox disabled={!orderOpen} checked={props.details.otherWarehouse} onChange={onOtherWarehouseChange}/> Other Warehouse
                                                        {orderOpen &&
                                                            <Space>
                                                                <DeleteButton onDelete={deletePartsOnOrder}  disabled={noPartsSelected} title="Delete Part(s)">
                                                                    <>Delete Parts</>
                                                                    <>Are you sure you want to delete Selected Parts?</>
                                                                </DeleteButton>
                                                            </Space> }
                                                        {orderSubmitted &&
                                                            <Space>
                                                                <Button onClick={completeOrder} disabled={noPartsSelected || partsWithSubmittedNotSelected} className="complete-button"> Shoot Complete</Button>
                                                                {hasAnyShootComplete && <Button onClick={finishOrder} disabled={noPartsSelected || partsWithShootCompleteNotSelected} className="finish-button"> Finish</Button>}</Space>}
                                                        {orderCompleted && <Button onClick={finishOrder} disabled={noPartsSelected} className="finish-button"> Finish</Button>}
                                                    </Space>
                                                    </div>
                                            </CanEdit>
                                        </>
                                    }
                                    type={'card'}
                                >
                                    <TabPane tab={<span><OrderedListOutlined /> Details</span>} key="detail">
                                        <Table
                                            rowKey="partNumber"
                                            rowSelection={orderFinished ? undefined : rowSelection}
                                            dataSource={props.parts}
                                            size="middle"
                                            pagination={{showTotal, defaultPageSize: 20}}
                                        >
                                            <Table.Column title="WI" render={PartWIColumn} />
                                            <Table.Column title="NY" render={PartNYColumn} />
                                            <Table.Column title="TX" render={PartTXColumn} />
                                            <Table.Column title="NV" render={PartNVColumn} />
                                            <Table.Column title="NC" render={PartNCColumn} />
                                            <Table.Column title="Details" render={PartDetailsColumn} />
                                            <Table.Column title="Part Number" render={PartNonPunctuatedPartNumColumn} />
                                            <Table.Column title="Tags" render={PartTagsColumn} />
                                            <Table.Column title="Part Live Date" render={GoLiveColumn} />
                                            <Table.Column title="Vendor Details" render={PartVendorColumn} />
                                            <Table.Column title="Brand" render={PartBrandColumn} />
                                            <Table.Column key="reshootNote" dataIndex="reshootNote" title="Reshoot Notes" />
                                            <Table.Column key="studioNote" dataIndex="studioNote" title="Studio Notes" />
                                            <Table.Column title="Status" render={statusRender} />
                                            {orderOpen && <Column key="actions" title={"Actions"} render={actionColumnRender} />}
                                        </Table>
                                    </TabPane>
                                </Tabs>
                            </Spin>
                        </Col>
                    </Row>
                </CanView>
                <CantView>
                    <Alert type="error" message="You do not have permission to view Studio Order Details" />
                </CantView>
            </Layout.Content>
        </Layout>
    );
};
