import React, { Fragment, useState, useEffect, useLayoutEffect, useRef } 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';
import Icon from '~/Components/UIControls/Icon';

const titleWidth = 100;

const Item = ({ item, index, onSelect, onDelete, editable, onChecked = () => {} }) => {
    const zebra = index % 2 == 0 ? true : false;
    const [checked, setChecked] = useState(false);

    return (
        <TouchableOpacity
            onPress={() => {
                setChecked(!checked);
                onChecked(item, !checked);
            }}
            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.MaterialName}</Text>
                <Text style={{ ...ListStyle.textLightGray }}>
                    {item.MaterialStandard}/{item.MaterialUnit}
                </Text>
            </View>
            {editable ? (
                <>
                    <View style={{ width: 150, display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                        <Input
                            defaultValue={item.StoredCount}
                            style={{ height: 25, borderRadius: 2, paddingLeft: 5, paddingRight: 5, flex: 1 }}
                            autosize={false}
                            onChangeText={(text) => {
                                item.StoredCount = text;
                                console.log('change qty : ', item.StoredCount);
                            }}
                            keyboardType="decimal-pad"
                            editable={editable}
                        />
                        <Text style={{ flex: 1 }}> / {item.PossibleStoredCount}</Text>
                    </View>
                    <View style={{ marginRight: 15 }}>
                        {checked ? (
                            <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-marked" size={25} color="#3b86ff" />
                        ) : (
                            <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-blank-outline" size={25} color="#3b86ff" />
                        )}
                    </View>
                </>
            ) : (
                <View style={{ marginRight: 15 }}>
                    <Text>발주수량 {item.MaterialCount}</Text>
                    <Text>입고수량 {item.StoredCount2}</Text>
                </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 checkedItems = useRef([]);

    const [loading, setLoading] = useState(false);
    const { auth, userinfo, config } = useAuth(navigation);
    const [data, setData] = useState({
        StoredDate: moment().format('YYYY-MM-DD HH:mm:ss'),
        FmsMaterialPurchaseOrder: {},
        FmsMaterialWarehouse: {},
    });
    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]);

    const onApproval = () => {
        setLoading(true);
        fetchGet(`/api/MaterialStored/ApprovalEach?siteId=${id[0]}&id=${id[1]}`)
            .then((data) => {
                setLoading(false);
                showMessage('승인되었습니다.');
                refreshList();
                navigation.pop();
            })
            .catch((e) => {
                setLoading(false);
                showMessage(e.message);
            });
        //e.preventDefault();
    };

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

        if (action != Form.CREATE) {
            try {
                console.log('get - ', `api/MaterialStored/${id[0]}/${id[1]}`);
                const result = await fetchGet(`api/MaterialStored/${id[0]}/${id[1]}`);
                console.log('result', result);
                setData(result);
                setMaterialList(result.FmsMaterials);
                Form.setFormData(result);
                if (result.ProgressId == 1) {
                    navigation.setParams({ readonly: false });
                }
                if (result.IsApproval == 0) {
                    navigation.setParams({ onApproval: onApproval });
                }
            } 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 (checkedItems.current.length == 0) {
            showMessage('입고하려는 자재를 선택하시기 바랍니다.');
            return;
        }
        if (checkedItems.current.filter((x) => x.PossibleStoredCount < x.StoredCount).length > 0) {
            showMessage('입고가능수량을 초과하였습니다.');
            return;
        }
        if (checkedItems.current.filter((x) => x.StoredCount <= 0).length > 0) {
            showMessage('입고수량은 최소1개 이상입니다.');
            return;
        }

        confirm('저장', '저장하시겠습니까?', async () => {
            setLoading(true);

            var checkedMaterialList = checkedItems.current;
            checkedMaterialList.forEach((item) => {
                item.StoredUserId = userinfo.UserId;
            });
            try {
                const submit = {
                    ...form,
                    SiteId: siteId,
                    ApprovalUserId: userinfo.UserId,
                    StoredUserId: userinfo.UserId,
                    MaterialStoredList: checkedMaterialList,
                };

                console.log('submit data', submit);
                const result = await fetchPut('api/MaterialStored', submit);
                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/MaterialStored/${id[0]}/${id[1]}`);

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

    const itemCheckedChange = (item, checked) => {
        if (checked) {
            const findIndex = checkedItems.current.indexOf(item);
            if (findIndex == -1) {
                checkedItems.current.push(item);
            } else {
                checkedItems.current[findIndex] = item;
            }
        } else {
            const index = checkedItems.current.indexOf(item);
            if (index != -1) {
                checkedItems.current.splice(index, 1);
            }
        }
        console.log(checkedItems.current);
    };

    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 style={{ width: titleWidth }}>
                                    <Form.Label>입고일</Form.Label>
                                </Form.Require>
                                <Form.Input value={moment(data.StoredDate).format('YYYY-MM-DD')} editable={false} />
                            </Form.Field>

                            <Form.Field>
                                <Form.Require style={{ width: titleWidth }}>
                                    <Form.Label>입고시간</Form.Label>
                                </Form.Require>
                                <Form.Input value={moment(data.StoredDate).format('HH:mm')} editable={false} />
                            </Form.Field>

                            <Form.Field>
                                <Form.Require style={{ width: titleWidth }}>
                                    <Form.Label>업무분야</Form.Label>
                                </Form.Require>
                                <Form.Input value={Util.get(data, 'CmBusinessField.Name')} editable={false} />
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="BusinessFieldId"
                                rule={{ required: '업무분야를 선택하세요.' }}
                                error={errors.BusinessFieldId}
                            />

                            <Form.Field>
                                <Form.Require style={{ width: titleWidth }}>
                                    <Form.Label>구매발주서</Form.Label>
                                </Form.Require>
                                <Controller
                                    name="OrderTitle"
                                    as={
                                        <Form.Input
                                            placeholder="구매발주서"
                                            defaultValue={data.FmsMaterialPurchaseOrder.Title}
                                            editable={false}
                                        />
                                    }
                                    control={control}
                                ></Controller>
                                {editable && (
                                    <Button
                                        iconFamily="AntDesign"
                                        iconName="check"
                                        style={{ width: 80 }}
                                        onPress={() => {
                                            openPopup(
                                                '/Popup/MaterialPurchaseOrder/Index',
                                                { siteId: userinfo.SiteId, userinfo: userinfo, auth: auth },
                                                (item) => {
                                                    console.log('item', item);
                                                    setValue('OrderTitle', item.Title);
                                                    setValue('PurchaseOrderId', item.PurchaseOrderId);
                                                    setValue('BusinessFieldId', item.BusinessFieldId);
                                                    Util.set(data, 'CmBusinessField.Name', item.BusinessFieldName);
                                                    item.MaterialPurchaseOrderMaterial.forEach((item) => {
                                                        item.MaterialName = item.Name;
                                                        item.MaterialStandard = item.Standard;
                                                        item.MaterialUnit = item.Unit;
                                                    });
                                                    setMaterialList(item.MaterialPurchaseOrderMaterial);
                                                },
                                            );
                                        }}
                                    >
                                        선택
                                    </Button>
                                )}
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="OrderTitle"
                                rule={{ required: '구매요청을 선택하세요.' }}
                                error={errors.OrderTitle}
                            />
                            <Form.Regist
                                editable={editable}
                                name="PurchaseOrderId"
                                rule={{ required: '구매요청을 선택하세요.' }}
                                error={errors.PurchaseOrderId}
                            />

                            <Form.Field>
                                <Form.Require style={{ width: titleWidth }}>
                                    <Form.Label>창고명칭</Form.Label>
                                </Form.Require>
                                <Form.EntitySelect
                                    entity="FmsMaterialWarehouse"
                                    id="WarehouseId"
                                    siteId={userinfo.SiteId}
                                    defaultLabel="창고명칭"
                                    selectedValue={data.WarehouseId}
                                    where={
                                        auth.Business
                                            ? `(BusinessFieldId=${userinfo.BusinessFieldId} OR BusinessFieldId IN (SELECT BusinessFieldId FROM CmBusinessField WHERE Name='공통'))`
                                            : ''
                                    }
                                    selectedText={data.FmsMaterialWarehouse.Name}
                                    editable={editable}
                                    useCheck={true}
                                    onChange={(item) => {
                                        setValue('WarehouseId', item.value, true);
                                    }}
                                />
                            </Form.Field>
                            <Form.Regist
                                editable={editable}
                                name="WarehouseId"
                                rule={{ required: '창고명칭을 선택하세요.' }}
                                error={errors.WarehouseId}
                            />

                            <Form.Field>
                                <Form.Title style={{ width: titleWidth }}>
                                    <Form.Label>자재위치</Form.Label>
                                </Form.Title>
                                <Form.Input
                                    placeholder="자재위치"
                                    defaultValue={data.LocationInWarehouse}
                                    onChangeText={(text) => setValue('LocationInWarehouse', text, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="LocationInWarehouse" />

                            <Form.Field>
                                <Form.Title style={{ width: titleWidth }}>
                                    <Form.Label>비고</Form.Label>
                                </Form.Title>
                                <Form.Input
                                    placeholder="비고"
                                    multiline={true}
                                    defaultValue={data.Note}
                                    onChangeText={(text) => setValue('Note', text, true)}
                                    editable={editable}
                                />
                            </Form.Field>
                            <Form.Regist editable={editable} name="Note" />

                            <Form.Field>
                                <Form.Title style={{ width: titleWidth }}>
                                    <Form.Label>{action == Form.CREATE ? '발주비고' : '구매사유'}</Form.Label>
                                </Form.Title>
                                <Text>{data.OrderReason}</Text>
                            </Form.Field>

                            <Form.Field style={{ height: 30 }}></Form.Field>
                        </Form.Container>
                    </TabItem>
                    <TabItem active={tab == 'detail' ? true : false}>
                        <FlatList
                            keyExtractor={(item, index) => '' + index}
                            data={materialList}
                            style={{ backgroundColor: '#f5f5f5', flex: 1 }}
                            renderItem={({ item, index }) => {
                                return !editable && item.StoredCount2 == 0 ? null : (
                                    <Item
                                        item={item}
                                        index={index}
                                        editable={editable}
                                        onChecked={itemCheckedChange}
                                        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 readonly = navigation.getParam('readonly', true);
    const handler = navigation.getParam('onApproval');

    return {
        header: () => (
            <Header
                navigation={navigation}
                title={`입고승인`}
                main={false}
                buttons={
                    <Fragment>
                        {!editable && (
                            <Fragment>
                                {auth.Update && handler && (
                                    <Form.PrimaryButton
                                        onPress={handler}
                                        buttonStyle={{ backgroundColor: '#0EB118', borderColor: '#0EB118' }}
                                    >
                                        승인
                                    </Form.PrimaryButton>
                                )}
                                {auth.Update && !readonly && <Form.EditButton navigation={navigation} type="primary" />}
                            </Fragment>
                        )}
                        {editable && (
                            <Fragment>
                                {auth.Update && <Form.SaveButton type="primary" />}
                                {action != Form.CREATE && auth.Update && <Form.CancelEditButton navigation={navigation} />}
                            </Fragment>
                        )}
                    </Fragment>
                }
            />
        ),
    };
};

export default Screen;
