// withHooks
import { applyStyle } from 'esoftplay';

import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibInfinite } from 'esoftplay/cache/lib/infinite/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibScroll } from 'esoftplay/cache/lib/scroll/import';
import { LibSkeleton } from 'esoftplay/cache/lib/skeleton/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibTextstyle } from 'esoftplay/cache/lib/textstyle/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketEmpty } from 'esoftplay/cache/market/empty/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketOrder_item } from 'esoftplay/cache/market/order_item/import';
import { MarketOrder_status } from 'esoftplay/cache/market/order_status/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';
import esp from 'esoftplay/esp';

import moment from 'esoftplay/moment';
import useSafeState from 'esoftplay/state';
import { createTimeout } from 'esoftplay/timeout';
import React, { useEffect, useRef } from 'react';
import { Pressable, ScrollView, Text, TouchableOpacity, View } from 'react-native';

export interface MarketOrderArgs {
  status: number | string
}
export interface MarketOrderProps {

}

function Status(props: any) {
  const tabRef = useRef<LibScroll>(null)
  const allStatus = MarketOrder_status()
  const timeout = createTimeout()

  useEffect(() => {
    if (props.status != 1)
      timeout.set(() => {
        tabRef?.current?.scrollToIndex?.(allStatus.map((s) => s.code).indexOf(props.status) - 1)
        timeout.clear()
      }, 500);
  }, [])

  return (
    <View style={{ minHeight: 50 }} >
      <LibScroll
        ref={tabRef}
        initialNumToRender={20}
        horizontal
      >
        <View style={{ width: 10 }} />
        {
          allStatus.map((status: any, index: number) => (
            <TouchableOpacity
              key={index}
              onPress={() => props.onChangeStatus(status.code)}
              style={{ height: 32, marginVertical: 10, marginRight: 10, borderRadius: 20, backgroundColor: props.status == status.code ? MarketStyle.colorPrimaryMarket : 'transparent', borderColor: props.status == status.code ? 'transparent' : '#ccc', borderWidth: 1, paddingHorizontal: 17, justifyContent: 'center' }} >
              <LibTextstyle textStyle='footnote' text={status.text} style={{ color: props.status == status.code ? "white" : "#4E4E4E" }} />
            </TouchableOpacity>
          ))
        }
      </LibScroll>
      <MarketSection_menu size='line' />
    </View>
  )
}

export default function m(props: MarketOrderProps): any {
  const statusCode = LibUtils.getArgs(props, 'status', 1)
  const [status, setStatus] = useSafeState(statusCode)
  const statusRef = useRef<LibSlidingup>(null)
  const allStatus = MarketOrder_status()
  const [code, setCode] = useSafeState(statusCode)

  const [selectedFilter, setSelectedFilter] = useSafeState({ id: 1, title: esp.lang("market/order", "all_date") })
  const [selectedDate, setSelectedDate] = useSafeState({ date_start: '', date_end: '', id: 1, title: esp.lang("market/order", "all_date") })
  const [selectedDateRange, setSelectedDateRange] = useSafeState({ date_start: moment().localeFormat("YYYY-MM-DD"), date_end: moment().localeFormat("YYYY-MM-DD") })

  const dialogFilterDate = useRef<LibSlidingup>(null)

  let filterDate = [
    {
      id: 1,
      title: esp.lang("market/order", "all_date"),
    },
    {
      id: 2,
      title: esp.lang("market/order", "90days"),
    },
    {
      id: 3,
      title: esp.lang("market/order", "30days"),
    },
    {
      id: 4,
      title: esp.lang("market/order", "select_date"),
    },
  ]

  function buildUrl(url: string) {
    if (status != '') {
      url += url.includes('?') ? '&' : '?'
      url += 'status=' + status
    }
    return url
  }

  function renderItem(item: any, index: number) {
    return (
      <MarketOrder_item {...item} key={index} />
    )
  }

  function renderError(e: string) {
    return (
      <MarketEmpty msg={e} />
    )
  }

  return (
    <View style={{ flex: 1 }} >
      <MarketHeader
        leftIcon={{ name: "close", onPress: () => LibNavigation.back() }}
        title={esp.lang("market/order", "header_title")}
        subtitle={esp.lang("market/order", "header_sub")}
      />
      {
        esp.isDebug('filter_order_status') ?
          <View style={{ minHeight: 50 }} >
            <LibScroll
              initialNumToRender={20}
              horizontal
            >
              <View style={{ width: 10 }} />
              <Pressable
                onPress={() => { statusRef.current?.show() }}
                style={applyStyle({ height: 30, marginVertical: 10, marginRight: 10, borderRadius: 12, backgroundColor: 'white', borderColor: '#ccc', borderWidth: 1, paddingHorizontal: 10, justifyContent: 'center', flexDirection: 'row', alignItems: 'center' })} >
                <LibTextstyle textStyle='footnote' text={allStatus[allStatus.findIndex((x) => String(x.code) == status)]?.text || esp.lang("market/order", "all_status")} style={applyStyle({ fontSize: 11, color: "#4E4E4E", marginRight: 5 })} />
                <LibIcon name='chevron-down' style={applyStyle({ color: "#4E4E4E" })} />
              </Pressable>
              <Pressable
                onPress={() => { dialogFilterDate?.current?.show() }}
                style={applyStyle({ height: 30, marginVertical: 10, marginRight: 10, borderRadius: 12, backgroundColor: 'white', borderColor: '#ccc', borderWidth: 1, paddingHorizontal: 10, justifyContent: 'center', flexDirection: 'row', alignItems: 'center' })} >
                <LibTextstyle textStyle='footnote' text={selectedDate.id == 4 ? LibUtils.getDateRange(selectedDate?.date_start, selectedDate?.date_end) : selectedDate?.title} style={applyStyle({ fontSize: 11, color: "#4E4E4E", marginRight: 5 })} />
                <LibIcon name='calendar' size={14} style={applyStyle({ color: "#4E4E4E" })} />
              </Pressable>

            </LibScroll>
            <MarketSection_menu size='line' />
          </View>
          :
          <Status status={status} onChangeStatus={setStatus} />
      }
      <LibInfinite
        isDebug={1}
        key={status}
        keyExtractor={(item, i) => i.toString()}
        url={buildUrl('shop/order')}
        errorView={renderError}
        renderItem={renderItem}
        LoadingView={
          <LibSkeleton backgroundStyle={applyStyle({ height: LibStyle.height })}>
            {
              [1, 1, 1].map((x: any, i: number) => (
                <View key={i}>
                  <View style={applyStyle({ marginHorizontal: 15 })}>
                    <View style={applyStyle({ height: 15, width: '40%', borderRadius: 10, backgroundColor: 'white', marginVertical: 10 })} />
                    <View style={applyStyle({ height: 1, backgroundColor: 'white' })} />
                    <View style={applyStyle({ flexDirection: 'row', alignItems: 'center', marginTop: 10 })}>
                      <View style={applyStyle({ width: 25, height: 25, borderRadius: 4, backgroundColor: 'white' })} />
                      <View style={applyStyle({ width: '30%', height: 15, backgroundColor: 'white', borderRadius: 10, marginLeft: 10 })} />
                    </View>
                    <View style={applyStyle({ flexDirection: 'row', marginTop: 20, borderBottomWidth: 0.5, paddingBottom: 10 })}>
                      <View style={applyStyle({ height: 55, width: 55, borderRadius: 4, backgroundColor: 'white' })} />
                      <View style={applyStyle({ marginLeft: 10, flex: 1 })}>
                        <View style={applyStyle({ width: '40%', height: 18, backgroundColor: 'white', borderRadius: 10, marginBottom: 10 })} />
                        <View style={applyStyle({ width: '40%', height: 15, backgroundColor: 'white', borderRadius: 10 })} />
                      </View>
                    </View>
                    <View style={applyStyle({ flexDirection: 'row', justifyContent: 'space-between', marginTop: 10, borderBottomWidth: 0.5, paddingBottom: 10 })}>
                      <View style={applyStyle({ width: '30%', height: 15, backgroundColor: 'white', borderRadius: 10 })} />
                      <View style={applyStyle({ width: '30%', height: 15, backgroundColor: 'white', borderRadius: 10 })} />
                    </View>
                  </View>
                  <View style={applyStyle({ height: 17, backgroundColor: 'white', marginTop: 17 })} />
                </View>
              ))
            }
          </LibSkeleton>
        }
      />

      <LibSlidingup ref={statusRef} onChangeShow={(s) => { if (!s) setCode(status) }} >
        <View style={applyStyle({ backgroundColor: 'white', paddingHorizontal: 17, borderTopLeftRadius: 10, borderTopRightRadius: 10, maxHeight: LibStyle.height * 0.9 })}>
          <View style={applyStyle({ flexDirection: 'row', alignItems: 'center', marginTop: 15 })}>
            <Pressable onPress={() => { statusRef.current?.hide() }} style={applyStyle({ marginRight: 10 })} >
              <LibIcon name='close' />
            </Pressable>
            <LibTextstyle textStyle='footnote' text={esp.lang("market/order", "transaction_status")} style={applyStyle({ fontWeight: 'bold', fontSize: 14, color: "#4E4E4E" })} />
          </View>
          <ScrollView>
            <Pressable onPress={() => { setCode('') }} style={applyStyle({ flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#e6e6e6', paddingVertical: 12 })}>
              <LibTextstyle textStyle='footnote' text={esp.lang("market/order", "all_transaction")} style={applyStyle({ flex: 1, fontWeight: 'bold', fontSize: 12, color: "#4E4E4E" })} />
              <LibIcon.Ionicons name={code == '' ? 'radio-button-on' : 'radio-button-off'} color={code == '' ? MarketStyle.colorPrimaryMarket : '#4E4E4E'} />
            </Pressable>
            {
              allStatus.map((x: any, i: number) => (
                <Pressable key={i} onPress={() => setCode(String(x.code))} style={applyStyle({ flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: '#e6e6e6', paddingVertical: 12 })}>
                  <LibTextstyle textStyle='footnote' text={x.text} style={applyStyle({ flex: 1, fontWeight: 'bold', fontSize: 12, color: "#4E4E4E" })} />
                  <LibIcon.Ionicons name={String(x.code) == code ? 'radio-button-on' : 'radio-button-off'} color={String(x.code) == code ? MarketStyle.colorPrimaryMarket : '#4E4E4E'} />
                </Pressable>
              ))
            }
          </ScrollView>
          <MarketButton text={esp.lang("market/order", "apply")} buttonStyle={applyStyle({ marginVertical: 15 })} textStyle={applyStyle({ fontSize: 14 })} onPress={() => { setStatus(code); statusRef.current?.hide() }} />
        </View>
      </LibSlidingup>
      <LibSlidingup ref={dialogFilterDate} onChangeShow={(s) => { if (!s) setSelectedFilter(selectedDate) }} >
        <View style={{ backgroundColor: '#f6f6f6', borderTopRightRadius: 10, borderTopLeftRadius: 10, paddingBottom: 15 }}>
          <View style={applyStyle({ flexDirection: 'row', alignItems: 'center', marginTop: 15, paddingHorizontal: 15 })}>
            <Pressable onPress={() => { statusRef.current?.hide() }} style={applyStyle({ marginRight: 10 })} >
              <LibIcon name='close' />
            </Pressable>
            <LibTextstyle textStyle='footnote' text={esp.lang("market/order", "select_date1")} style={applyStyle({ fontWeight: 'bold', fontSize: 14, color: "#4E4E4E" })} />
          </View>

          <MarketSection_menu size="line" />
          {
            filterDate?.map((item: any, i: number) => {
              return (
                <Pressable onPress={() => {
                  setSelectedFilter(item)
                }} key={i} style={{ padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
                  <LibTextstyle textStyle='footnote' text={item?.title} style={applyStyle({ flex: 1, fontWeight: 'bold', fontSize: 12, color: "#4E4E4E" })} />
                  <LibIcon.Ionicons name={selectedFilter?.id == item.id ? 'radio-button-on' : 'radio-button-off'} color={selectedFilter?.id == item.id ? MarketStyle.colorPrimaryMarket : "#4E4E4E"} />
                </Pressable>
              )
            })
          }
          {
            selectedFilter?.id == 4 &&
            <Pressable onPress={() => {
              LibNavigation.navigateForResult('market/date_range_picker', { minDate: moment().add(-5, 'years').localeFormat('YYYY-MM-DD'), maxDate: new Date() }).then((item) => {
                setSelectedDateRange(item)
              })
            }} style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
              <View style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>Mulai Dari</Text>
                <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{moment(selectedDateRange?.date_start).localeFormat("DD MMM YYYY")}</Text>
              </View>
              <View style={{ flex: 1, padding: 10, paddingHorizontal: 20, borderBottomWidth: 1, borderBottomColor: '#e9ecef', }}>
                <Text allowFontScaling={false} style={{ fontFamily: "Arial", fontSize: 12, fontWeight: "normal", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>Sampai</Text>
                <Text allowFontScaling={false} style={{ marginTop: 4, fontFamily: "Arial", fontSize: 14, fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#4a4a4a" }}>{moment(selectedDateRange?.date_end).localeFormat("DD MMM YYYY")}</Text>
              </View>
            </Pressable>
          }
          <MarketButton text={esp.lang("market/order", "apply")} buttonStyle={applyStyle({ marginHorizontal: 15, marginTop: 15 })} textStyle={applyStyle({ fontSize: 14 })} onPress={() => {
            if (selectedFilter.id == 1) {
              setSelectedDate({ date_start: '', date_end: '', ...selectedFilter })
              dialogFilterDate.current?.hide()
            } else if (selectedFilter.id == 2) {
              setSelectedDate({ date_start: moment().add(-90, 'days').localeFormat('YYYY-MM-DD'), date_end: moment().localeFormat("YYYY-MM-DD"), ...selectedFilter })
              dialogFilterDate.current?.hide()
            } else if (selectedFilter.id == 3) {
              setSelectedDate({ date_start: moment().add(-30, 'days').localeFormat("YYYY-MM-DD"), date_end: moment().localeFormat("YYYY-MM-DD"), ...selectedFilter })
              dialogFilterDate.current?.hide()
            } else if (selectedFilter.id == 4) {
              setSelectedDate({ ...selectedDateRange, ...selectedFilter })
              dialogFilterDate.current?.hide()
            } else {
              setSelectedDate({ date_start: moment().localeFormat("YYYY-MM-DD"), date_end: moment().localeFormat("YYYY-MM-DD"), ...selectedFilter })
            }
          }} />
        </View>
      </LibSlidingup>
    </View>
  )
}