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 } from 'react-hook-form';
import { useAuth } from '~/Components/Hooks';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import { UploadFileType } from '~/Components/UIControls/UploadFile';
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, currentMaterialId } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity
                onPress={onSelect}
                style={{
                    ...ListStyle.itemContainer,
                    borderTopWidth: 0,
                    backgroundColor: currentMaterialId == item.MaterialId ? 'rgba(255,0,0,0.1)' : 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.MaterialName}</Text>
                    <Text style={{ ...ListStyle.textLightGray }}>{item.MaterialStandard}/{item.MaterialUnit}</Text>
                </View>
                <View style={{ width: 80 }}>
                    <Text>{item.MaterialCount}</Text>
                </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', []);

    const [loading, setLoading] = useState(false);
    const [data, setData] = useState({ PurchRequestDate: moment().format('YYYY-MM-DD') });
    const [materialList, setMaterialList] = useState([]);
    const { showMessage } = useToast();
    const { auth, userinfo, config } = useAuth(navigation);

    const currentMaterialId = id[2];

    const onProcess = () => {
        console.log('onProcess');
        onSave();
    };

    // mount
    useEffect(() => {
        navigation.setParams({
            onProcess: onProcess,
        });
        fetch();
    }, [editable]);

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

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

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

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

        if (action != Form.CREATE) {
            try {
                console.log('get - ', `api/MaterialOrderStatusByStored/${id[0]}/${id[1]}/${id[2]}`);
                const result = await fetchGet(`api/MaterialOrderStatusByStored/${id[0]}/${id[1]}/${id[2]}`);
                navigation.setParams({ readonly: result.ProgressId >= 2 });
                console.log('result', result);
                setData(result);
                setMaterialList(result.FmsMaterials);
                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) => {
        if (loading) {
            showMessage('저장중입니다. 잠시만기다려 주세요.');
            return;
        }

        confirm('저장', '정말 입고처리 하시겠습니까?', async () => {
            setLoading(true);
            try {
                const result = await fetchPost(`api/MaterialOrderStatusByStored/${id[0]}/${id[1]}/${id[2]}/${auth.Business}`, {});
                showMessage('입고되었습니다.');
                refreshList();
                navigation.pop();
            } catch (error) {
                showMessage(error.message);
            }
            setLoading(false);
        });
    };

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

                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.DatePicker
                                    date={data.OrderDate}
                                    onChange={(newDate) => setValue('OrderDate', newDate, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="OrderDate"
                                rule={{ required: '발주일자를 입력하세요.' }}
                                error={errors.Title}
                            />

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

                            <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.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}
                                        currentMaterialId={currentMaterialId}
                                        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);
    const handler = navigation.getParam('onProcess');

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`미입고현황`}
                main={false}
                buttons={
                    <Form.PrimaryButton onPress={handler} buttonStyle={{ backgroundColor: '#0EB118', borderColor: '#0EB118' }}>
                        입고
                    </Form.PrimaryButton>
                }
            />
        ),
    };
};

export default Screen;
