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({ ReleaseTypeId: 2 });
    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/MaterialRelease/${id[0]}/${id[1]}`);
                const result = await fetchGet(`api/MaterialRelease/${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;
        }
        for (var i = 0; i < materialList.length; i++) {
            materialList[i].StockCountByPoint = materialList[i].StockCount;
        }

        if (!form.AdjustmentTypeId) {
            showMessage('정산유형을 입력해주세요.');
            return;
        }

        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);
            try {
                if (action == Form.CREATE) {
                    const submit = {
                        ...form,
                        SiteId: siteId,
                        ReleaseDate: moment().format('YYYY-MM-DD'),
                        AdjustmentUserId: userinfo.UserId,
                        MaterialReleaseList: materialList,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPut('api/MaterialRelease', submit);
                    showMessage('저장되었습니다.');
                    refreshList();
                    navigation.pop();
                } else {
                    const submit = {
                        ...form,
                        SiteId: siteId,
                        AdjustmentUserId: userinfo.UserId,
                        ReleaseDate: data.ReleaseDate,
                        MaterialReleaseId: data.MaterialReleaseId,
                        MaterialReleaseList: materialList,
                    };
                    console.log('submit data', submit);
                    const result = await fetchPost(`api/MaterialRelease/${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/MaterialRelease/${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.Title>
                                    <Form.Label>출고구분</Form.Label>
                                </Form.Title>
                                <Text>조정출고</Text>
                            </Form.Field>
                            <Form.Regist editable={editable} name="ReleaseTypeId" value={data.ReleaseTypeId} />

                            <Form.Field>
                                <Form.Title>
                                    <Form.Label>정산유형</Form.Label>
                                </Form.Title>
                                <Form.EntitySelect
                                    entity="FmsMaterialCodeAdjustmentType"
                                    id="AdjustmentTypeId"
                                    defaultLabel="선택해주세요"
                                    selectedValue={data.AdjustmentTypeId}
                                    where={`AdjustmentTypeId <> 0`}
                                    editable={editable}
                                    onChange={(item) => {
                                        setValue('AdjustmentTypeId', item.value, true);
                                    }}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="AdjustmentTypeId" />

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

                            <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;
