import React, { Fragment, useState, useEffect, useLayoutEffect, useContext } from 'react';
import { ActivityIndicator, Text, View, FlatList, TouchableOpacity } from 'react-native';
import session from '~/Utils/session';
import fetchGet, { fetchPut, fetchPost, fetchDelete } from '~/Utils/fetch';
import { useToast, confirm } from '~/Components/UIControls/Message';
import Form from '~/Components/Form';
import Button from '~/Components/UIControls/Button';
import { Tab, TabItem, TabTitleGroup, TabHeader, TabContent, TabTitle } from '~/Components/UIControls/Tab';
import EmptyView from '~/Components/Listing/EmptyView';
import {
    Search,
    SearchIcon,
    Line,
    TextInput,
    checkFilter,
    filterValue,
    ListStyle,
    DetailIcon,
    RightArrow,
    CreateButton,
    SearchTitle,
} from '~/Components/Listing/Search';
import { useForm, Controller } from 'react-hook-form';
import { useAuth } from '~/Components/Hooks';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
import Input, { InputFilters } from '~/Components/UIControls/Input';
import { usePopup } from '~/Components/UIControls/Popup';
import { Util } from '~/Utils/utils';
import { ScrollView } from 'react-native-gesture-handler';
import moment from 'moment';

class Item extends React.PureComponent {
    render() {
        const { item, index, onSelect, onDelete, editable } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity
                onPress={onSelect}
                style={{
                    ...ListStyle.itemContainer,
                    borderTopWidth: 0,
                    backgroundColor: zebra ? '#fdfdfd' : '#fff',
                }}
            >
                <View style={{ flex: 1 }}>
                    <Text style={{ ...ListStyle.textLightGray }}>
                        {[item.FirstClassName, item.SecondClassName, item.ThirdClassName].filter((x) => x).join('>')}
                    </Text>
                    <Text style={{ ...ListStyle.text }}>{item.Name}</Text>
                    <Text style={{ ...ListStyle.textLightGray }}>
                        {item.Standard}/{item.Unit}
                    </Text>
                </View>
                <View style={{ width: 80 }}>
                    <Input
                        defaultValue={item.MaterialCount}
                        style={{ height: 25, borderRadius: 2, paddingLeft: 5, paddingRight: 5, minWidth: 50 }}
                        autosize={false}
                        onChangeText={(text) => {
                            item.MaterialCount = text;
                            console.log('change qty : ', item.MaterialCount);
                        }}
                        keyboardType="decimal-pad"
                        editable={editable}
                    />
                </View>
                {editable && (
                    <View style={{ width: 80 }}>
                        <Button iconFamily="AntDesign" iconName="delete" onPress={onDelete}>
                            삭제
                        </Button>
                    </View>
                )}
            </TouchableOpacity>
        );
    }
}

const Screen = ({ navigation }) => {
    const action = navigation.getParam('action', Form.VIEW);
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const setEditable = (value) => {
        navigation.setParams({ editable: value });
    };
    const tab = navigation.getParam('tab', 'basic');
    const refreshList = navigation.getParam('refreshList', () => {});
    const siteId = navigation.getParam('siteId', '');
    const id = navigation.getParam('id', 0);

    const [loading, setLoading] = useState(false);
    const { auth, userinfo, config } = useAuth(navigation);
    const [data, setData] = useState({ OrderUserName: userinfo.Name });
    const [materialList, setMaterialList] = useState([]);
    const { showMessage } = useToast();

    // mount
    useEffect(() => {
        fetch();
    }, [editable]);

    // unmount
    useEffect(() => () => {}, []);

    // popup
    const { openPopup } = usePopup();

    // react hook form initialize
    const { register, setValue, handleSubmit, errors, control, getValues } = useForm();
    useLayoutEffect(() => {
        Form.setUseFormFunctions(register, setValue);
    }, [register]);

    // search
    const fetch = async () => {
        setLoading(true);

        if (action != Form.CREATE) {
            try {
                console.log('get - ', `api/MaterialPurchaseOrder/${id[0]}/${id[1]}`);
                const result = await fetchGet(`api/MaterialPurchaseOrder/${id[0]}/${id[1]}`);
                console.log('result', result);
                setData(result);
                setMaterialList(result.MaterialPurchaseOrderMaterial);
                Form.setFormData(result);
            } catch (error) {
                showMessage(error.message);
            }
        }
        setLoading(false);
    };

    // edit
    const onEdit = async () => {
        await fetch();
        setEditable(true);
    };

    // cancel edit
    const onCancelEdit = async () => {
        await fetch();
        setEditable(false);
    };

    // save
    const onSave = async (form) => {
        console.log('form', form);
        if (loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }

        if (!materialList.length) {
            showMessage('자재를 추가해주세요.');
            return;
        }

        if (!form.StoredDueDate) {
            showMessage('입고예정일을 입력해주세요.');
            return;
        }

        if (moment(form.StoredDueDate, 'YYYY-MM-DD').diff(form.OrderDate, 'YYYY-MM-DD') <= 0) {
            showMessage('입고예정일은 발주일 이후로 설정하시기 바랍니다.');
            return;
        }

        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            try {
                if (action == Form.CREATE) {
                    const submit = {
                        ...form,
                        SiteId: siteId,
                        OrderUserId: userinfo.UserId,
                        FmsMaterialPurchaseOrderMaterial: materialList,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPut('api/MaterialPurchaseOrder', submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    navigation.pop();
                } else {
                    const submit = {
                        ...form,
                        SiteId: siteId,
                        OrderUserId: userinfo.UserId,
                        PurchaseOrderId: data.PurchaseOrderId,
                        FmsMaterialPurchaseOrderMaterial: materialList,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPost(`api/MaterialPurchaseOrder/${id[0]}/${id[1]}`, submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    setEditable(false);
                }
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    // delete
    const onDelete = async () => {
        if (loading) {
            showMessage('처리중입니다. 잠시만기다려 주세요.');
            return;
        }
        confirm('삭제', '삭제하시겠습니까?', async () => {
            setLoading(true);
            try {
                await fetchDelete(`api/MaterialPurchaseOrder/${id[0]}/${id[1]}`);

                showMessage('삭제되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

    return (
        <BottomTabBarLayout>
            <Tab>
                <TabHeader>
                    <TabTitleGroup top={true}>
                        <TabTitle
                            onPress={() => {
                                navigation.setParams({ tab: 'basic' });
                            }}
                            active={tab == 'basic' ? true : false}
                            title="발주등록"
                        />
                        <TabTitle
                            onPress={() => {
                                navigation.setParams({ tab: 'detail' });
                            }}
                            active={tab == 'detail' ? true : false}
                            title="추가자재"
                        />
                    </TabTitleGroup>
                </TabHeader>
                <TabContent>
                    <TabItem active={tab == 'basic' ? true : false}>
                        <Form.Container
                            onSave={handleSubmit(onSave)}
                            onDelete={onDelete}
                            onEdit={onEdit}
                            onCancelEdit={onCancelEdit}
                            loading={loading}
                        >
                            <Form.Field>
                                <Form.Require>
                                    <Form.Label>업무분야</Form.Label>
                                </Form.Require>
                                <Form.EntitySelect
                                    entity="CmBusinessField"
                                    defaultLabel="업무분야"
                                    selectedValue={data.BusinessFieldId}
                                    selectedText={Util.get(data, 'CmBusinessField.Name')}
                                    editable={editable}
                                    auth={auth}
                                    useCheck={true}
                                    onChange={(item) => {
                                        setValue('BusinessFieldId', item.value, true);
                                    }}
                                />
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="BusinessFieldId"
                                rule={{ required: '업무분야를 선택하세요.' }}
                                error={errors.BusinessFieldId}
                            />

                            <Form.Field>
                                <Form.Require>
                                    <Form.Label>구매요청</Form.Label>
                                </Form.Require>
                                <Controller
                                    name="RequestTitle"
                                    as={<Form.Input placeholder="구매요청" defaultValue={data.RequestTitle} editable={false} />}
                                    control={control}
                                ></Controller>
                                {editable && (
                                    <Button
                                        iconFamily="AntDesign"
                                        iconName="check"
                                        style={{ width: 80 }}
                                        onPress={() => {
                                            openPopup(
                                                '/Popup/MaterialPurchaseRequest/Index',
                                                { siteId: userinfo.SiteId, userinfo: userinfo, auth: auth },
                                                (item) => {
                                                    console.log('item', item);
                                                    setValue('RequestTitle', item.Title);
                                                    setValue('PurchaseRequestId', item.PurchaseRequestId);
                                                },
                                            );
                                        }}
                                    >
                                        선택
                                    </Button>
                                )}
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="RequestTitle"
                                rule={{ required: '구매요청을 선택하세요.' }}
                                error={errors.RequestTitle}
                            />
                            <Form.Regist
                                editable={editable}
                                name="PurchaseRequestId"
                                rule={{ required: '구매요청을 선택하세요.' }}
                                error={errors.RequestTitle}
                            />

                            <Form.Field>
                                <Form.Title>
                                    <Form.Label>발주자명</Form.Label>
                                </Form.Title>
                                <Text>{data.OrderUserName}</Text>
                            </Form.Field>
                            <Form.Regist editable={editable} name="OrderUserId" value={data.OrderUserId} />

                            <Form.Field>
                                <Form.Title>
                                    <Form.Label>발주일자</Form.Label>
                                </Form.Title>
                                <Form.DatePicker
                                    date={data.OrderDate}
                                    onChange={(newDate) => setValue('OrderDate', newDate, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="OrderDate" />

                            <Form.Field>
                                <Form.Title>
                                    <Form.Label>입고예정일</Form.Label>
                                </Form.Title>
                                <Form.DatePicker
                                    date={data.StoredDueDate}
                                    onChange={(newDate) => setValue('StoredDueDate', newDate, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="StoredDueDate" />

                            <Form.Field>
                                <Form.Require>
                                    <Form.Label>발주제목</Form.Label>
                                </Form.Require>
                                <Form.Input
                                    placeholder="발주제목"
                                    defaultValue={data.Title}
                                    onChangeText={(text) => setValue('Title', text, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="Title"
                                rule={{ required: '발주제목을 입력하세요.' }}
                                error={errors.Title}
                            />

                            <Form.Field>
                                <Form.Title>
                                    <Form.Label>발주사유</Form.Label>
                                </Form.Title>
                                <Form.Input
                                    placeholder="발주사유"
                                    multiline={true}
                                    defaultValue={data.Reason}
                                    onChangeText={(text) => setValue('Reason', text, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="Reason" />

                            {/* hidden */}
                            <Form.Regist name="ApprovalUserId" value={userinfo.UserId} />
                            <Form.Regist name="PurchaseTypeId" value={2} />
                            <Form.Regist name="BusinessFieldId" value={userinfo.BusinessFieldId} />
                            <Form.Regist name="PurchaseHopeDate" value={data.PurchaseHopeDate} />
                            <Form.Regist name="RequestDate" value={data.RequestDate} />

                            <Form.Field style={{ height: 30 }}></Form.Field>
                        </Form.Container>
                    </TabItem>
                    <TabItem active={tab == 'detail' ? true : false}>
                        {editable && (
                            <View>
                                <Button
                                    iconFamily="AntDesign"
                                    iconName="plus"
                                    onPress={() => {
                                        openPopup('/Popup/Material/Index', { siteId: userinfo.SiteId }, (results) => {
                                            let newlist = results
                                                .filter((x) => materialList.findIndex((y) => y.MaterialId == x.MaterialId) < 0)
                                                .map((x) => {
                                                    x.MaterialCount = x.Qty;
                                                    return x;
                                                });
                                            setMaterialList([...newlist, ...materialList]);
                                        });
                                    }}
                                >
                                    추가
                                </Button>
                            </View>
                        )}
                        <FlatList
                            keyExtractor={(item, index) => '' + index}
                            data={materialList}
                            style={{ backgroundColor: '#f5f5f5', flex: 1 }}
                            renderItem={({ item, index }) => {
                                return (
                                    <Item
                                        item={item}
                                        index={index}
                                        editable={editable}
                                        onSelect={() => {}}
                                        onDelete={() => {
                                            setMaterialList(materialList.filter((i, idx) => idx != index));
                                        }}
                                    />
                                );
                            }}
                            ListEmptyComponent={<EmptyView />}
                        />
                    </TabItem>
                </TabContent>
            </Tab>
        </BottomTabBarLayout>
    );
};

Screen.navigationOptions = ({ navigation }) => {
    const action = navigation.getParam('action', Form.VIEW); // create, edit, view
    const editable = navigation.getParam('editable', action == Form.VIEW ? false : true);
    const { auth } = useAuth(navigation);

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`발주 정보`}
                main={false}
                buttons={
                    <Fragment>
                        {!editable && (
                            <Fragment>
                                {auth.Update && <Form.EditButton navigation={navigation} type="primary" />}
                                {auth.Delete && <Form.DeleteButton />}
                            </Fragment>
                        )}
                        {editable && (
                            <Fragment>
                                {auth.Update && <Form.SaveButton type="primary" />}
                                {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
