import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import Styled from 'styled-components/native';
import {
    Search,
    SearchIcon,
    Line,
    TextInput,
    checkFilter,
    filterValue,
    ListStyle,
    DetailIcon,
    RightArrow,
    CreateButton,
    SearchBoxIcon,
    DefaultButton,
    PrimaryButton,
    SearchTitle,
} from '~/Components/Listing/Search';
import Checkbox from '~/Components/UIControls/Checkbox';
import Theme from '~/Themes';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import session from '~/Utils/session';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import EmptyView from '~/Components/Listing/EmptyView';
import EntitySelect from '~/Components/EntitySelect';
import { useToast } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { useLayoutAction, PopupLayout } from '~/Components/Layouts/PopupLayout';

const style = StyleSheet.create({
    container: { flexDirection: 'column' },
    header: { padding: 15, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'center' },
    headerBadge: {
        width: 63,
        height: 35,
        borderRadius: 63,
        borderStyle: 'solid',
        borderWidth: 1,
        borderColor: '#0b83e6',
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerBadgeText: { color: '#0b83e6', fontSize: 14, textAlign: 'center' },
    headerCategory: { fontSize: 16, color: '#9aa3ac' },
    headerName: { fontSize: 16, color: '#000' },
    headerDetail: { marginLeft: 15, flexDirection: 'column', flex: 1 },
    headerExtraContainer: { flexDirection: 'row' },
    headerExtra: { color: '#b9bac4', fontSize: 14 },
    stock: { paddingHorizontal: 15, paddingVertical: 8, backgroundColor: '#f8fcff', flexDirection: 'row' },
    stockLabel: { color: '#9aa3ac', fontSize: 16, fontFamily: Theme.Fonts.Regular },
    stockValue: { fontWeight: '500', fontSize: 16, fontFamily: Theme.Fonts.Regular },
});

// list item
class Item extends React.PureComponent {
    render() {
        const { item, index, onPress = () => {} } = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity
                onPress={onPress}
                style={{
                    marginBottom: 10,
                    borderTopWidth: 1,
                    borderTopColor: '#e9e9e9',
                    backgroundColor: zebra ? '#fdfdfd' : '#fff',
                }}
            >
                <View style={style.container}>
                    <View style={style.header}>
                        <View style={style.headerBadge}>
                            <Text style={style.headerBadgeText}>{item.BusinessFieldName}</Text>
                        </View>
                        <View style={style.headerDetail}>
                            <Text style={style.headerCategory}>{item.ProgressName}</Text>
                            <Text style={style.headerName}>{item.Title}</Text>
                            <View style={style.headerExtraContainer}>
                                <Text style={{ ...style.headerExtra, marginRight: 'auto' }}>{item.RequestUserName}</Text>
                                <Text style={{ ...style.headerExtra, marginLeft: 'auto' }}>
                                    {Util.toDateString(item.PurchaseHopeDate, '', '.')}
                                </Text>
                            </View>
                        </View>
                    </View>
                    <View style={style.stock} style={{ display: 'none' }}>
                        <Text style={{ ...style.stockLabel, marginRight: 9 }}>승인자</Text>
                        <Text style={{ ...style.stockValue, marginRight: 'auto' }}>{item.ApprovalUserName}</Text>
                        <Text style={{ ...style.stockLabel, marginLeft: 'auto' }}>승인일</Text>
                        <Text style={{ ...style.stockValue, marginLeft: 9 }}>{Util.toDateString(item.ApprovalDate)}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

// list and search
export default Popup = ({ siteId = 0, userinfo, auth, popup = DefaultAction }) => {
    const [filters, setFilters] = useState({ 'Material.IsUse_eq': { field: 'Material.IsUse', op: 'eq', value: true } });
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { showMessage } = useToast();
    const [searchForm, setSearchForm] = useState({
        FirstClassId: '',
        SecondClassId: '',
        ThirdClassId: '',
        BusinessFieldId: '',
    });
    const isUseItems = useRef([
        { label: '사용', value: true },
        { label: '미사용', value: false },
    ]);

    const apiUrl = `api/MaterialPurchaseRequest?siteId=${userinfo.SiteId}&businessAuth=${auth.Business}&progressId=2`;

    // search events...
    const start = () => {
        setRefreshing(true);
    };
    const success = (data, append) => {
        pages.current = data.pages;
        //console.log(data);

        if (append && page > 1) {
            setList(list.concat(data.list));
        } else {
            setList(data.list);
        }
        setRefreshing(false);
    };
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    };

    const refreshList = () => {
        setPage('refresh-' + Math.random());
    };

    const actionHandler = (action, parameter = {}) => {
        const actions = {
            close: () => {
                console.log('close...');
                popup.close();
            },
            addSelected: () => {
                popup.select([]);
            },
        };
        actions[action]();
    };

    return (
        <PopupLayout title="구매발주선택" header={Header} actionHandler={actionHandler}>
            <SearchListContainer>
                <SearchList
                    page={page}
                    pages={pages.current}
                    setPage={setPage}
                    refreshing={refreshing}
                    data={list}
                    style={{ backgroundColor: '#f5f5f5' }}
                    renderItem={({ item, index }) => {
                        return (
                            <Item
                                item={item}
                                index={index}
                                onPress={() => {
                                    popup.select(item);
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search
                id="materialstock"
                api={apiUrl}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'RequestDate', order: 'desc' }}
                onStart={start}
                onSuccess={success}
                onFailure={fail}
            >
                <>
                    <SearchTitle title="업무분야" />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="CmBusinessField"
                        defaultLabel="업무분야"
                        useCheck={true}
                        auth={auth}
                        onChange={(item) => {
                            setSearchForm({
                                ...searchForm,
                                BusinessFieldId: item.value,
                            });
                            filterValue([filters, setFilters], 'Material.BusinessFieldId', item.value, 'eq');
                        }}
                        auth={auth}
                    />

                    <SearchTitle title="진행상태" />
                    <EntitySelect
                        style={{ marginBottom: 20 }}
                        entity="FmsMaterialCodeProgress"
                        id="ProgressId"
                        defaultLabel="진행상태"
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'ProgressId', item.value, 'eq');
                        }}
                    />

                    <SearchTitle title="제목" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="제목"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Title', value, 'cn')}
                    />

                    <SearchTitle title="자재명" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="자재명"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Material.Name', value, 'cn')}
                    />

                    <SearchTitle title="신청일" />
                    <DateTimePicker
                        style={{ marginBottom: 5 }}
                        placeholder="부터"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'RequestDate', Util.toDateString(newDate), 'ge');
                        }}
                    />
                    <DateTimePicker
                        style={{ marginBottom: 20 }}
                        placeholder="까지"
                        useClear={true}
                        onChange={(newDate) => {
                            filterValue([filters, setFilters], 'RequestDate', Util.toDateString(newDate), 'le');
                        }}
                    />

                    <SearchTitle title="규격" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="규격"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Material.Standard', value, 'cn')}
                    />
                </>
            </Search>
        </PopupLayout>
    );
};

const Header = () => {
    const { callAction } = useLayoutAction();

    return (
        <Fragment>
            {/**
            <PrimaryButton
                onPress={() => {
                    callAction('addSelected');
                }}
            >
                선택추가
            </PrimaryButton>
            **/}
            <DefaultButton
                onPress={() => {
                    callAction('close');
                }}
            >
                닫기
            </DefaultButton>
            <SearchBoxIcon style={{ marginLeft: 5 }} id="material-popup" />
        </Fragment>
    );
};
