// withHooks
import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibDialog } from 'esoftplay/cache/lib/dialog/import';
import { LibIcon } from 'esoftplay/cache/lib/icon/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibNavigation } from 'esoftplay/cache/lib/navigation/import';
import { LibPicture } from 'esoftplay/cache/lib/picture/import';
import { LibProgress } from 'esoftplay/cache/lib/progress/import';
import { LibStyle } from 'esoftplay/cache/lib/style/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { EventButton } from 'esoftplay/cache/event/button/import';
import { EventHeader } from 'esoftplay/cache/event/header/import';
import { EventInput_rectangle } from 'esoftplay/cache/event/input_rectangle/import';
import { EventMessage } from 'esoftplay/cache/event/message/import';
import { LibSlidingup } from 'esoftplay/cache/lib/slidingup/import';
import React, { useEffect, useRef } from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';


export interface EventCounter_report_detailArgs {

}
export interface EventCounter_report_detailProps {

}

export interface ReportDetailRenderDetail extends EventCounter_report_detailProps {
  data: any
  type: number
  date_end?: string
  date_start?: string
  onPressIncome: () => void
  onPressExpenditure: () => void

}

export function showValueExtention(type: number, value: any) {
  if (type == 1) {
    return LibUtils.number(value)
  } else {
    return LibUtils.money(value)
  }
}

function RenderDetail(props: ReportDetailRenderDetail) {
  const { data, type, date_end, date_start } = props
  let dateRange = LibUtils.moment(date_start).localeFormat("DD-MM-YYYY") == LibUtils.moment(date_end).localeFormat("DD-MM-YYYY") ? esp.lang("event/counter_report_detail", "today") : esp.lang("event/counter_report_detail", "date_start", LibUtils.moment(date_start).localeFormat("DD MMMM YYYY"))
  return (
    <View style={{ padding: 10, backgroundColor: LibStyle.colorBgGrey, borderRadius: 10, borderTopLeftRadius: 0, borderTopRightRadius: 0 }}>

      <View style={{ backgroundColor: "#fff", marginBottom: 10, borderRadius: 10, padding: 10, flex: 1, justifyContent: 'space-between' }}>
        <Text allowFontScaling={false} style={{ textAlign: 'left', flexWrap: 'wrap', fontSize: 12 }}>{esp.lang("event/counter_report_detail", "sell", dateRange)}</Text>
        <Text allowFontScaling={false} style={{ textAlign: 'left', marginTop: 10, fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 18, color: LibStyle.colorGreen }}>{showValueExtention(type, type == 1 ? data?.credit?.transaction?.total : data?.debit?.transaction?.total)}</Text>
      </View>

      <View style={{ backgroundColor: "#fff", borderRadius: 10, padding: 10, marginBottom: 10 }}>
        <Text allowFontScaling={false} style={{ textAlign: 'center', flexWrap: 'wrap', fontSize: 12 }}>{esp.lang("event/counter_report_detail", "total_withdraw")}</Text>
        <Text allowFontScaling={false} style={{ textAlign: 'center', marginTop: 10, fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 24, color: LibStyle.colorBrown }}>{showValueExtention(type, data?.total_withdrawal)}</Text>
      </View>

      <View style={{ flexDirection: 'row' }}>
        <View style={{ flex: 1, marginRight: 5, backgroundColor: "#fff", borderRadius: 10, padding: 10 }}>
          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center', marginBottom: 10 }}>
            <Text allowFontScaling={false} style={{ flex: 1, color: LibStyle.colorGreen, fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 14 }}>{type == 2 ? esp.lang("event/counter_report_detail", "income") : esp.lang("event/counter_report_detail", "ticket_add")}</Text>
            <TouchableOpacity onPress={props.onPressIncome} style={{ marginLeft: 10 }} >
              <LibIcon name='arrow-right-circle' color={LibStyle.colorBlue} size={18} />
            </TouchableOpacity>
          </View>

          <Text allowFontScaling={false} style={{ fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 16, color: "#000" }}>{showValueExtention(type, data?.debit?.total)}</Text>

        </View>

        <View style={{ flex: 1, marginLeft: 5, backgroundColor: "#fff", borderRadius: 10, padding: 10 }}>
          <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignContent: 'center', alignItems: 'center', marginBottom: 10 }}>
            <Text allowFontScaling={false} style={{ flex: 1, color: LibStyle.colorRed, fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 14 }}>{type == 2 ? esp.lang("event/counter_report_detail", "outcome") : esp.lang("event/counter_report_detail", "ticket_min")}</Text>
            <TouchableOpacity onPress={props.onPressExpenditure} style={{ marginLeft: 10 }}>
              <LibIcon name='arrow-right-circle' color={LibStyle.colorBlue} size={18} />
            </TouchableOpacity>
          </View>
          <Text allowFontScaling={false} style={{ fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 16, color: "#000" }}>{showValueExtention(type, data?.credit?.total)}</Text>
        </View>
      </View>

    </View>
  )
}

export default function m(props: EventCounter_report_detailProps): any {
  const { url } = LibNavigation.getArgsAll(props)
  const [result, setResult] = useSafeState<any>()
  const [error, setError] = useSafeState<any>()
  const dialogNotes = useRef<LibSlidingup>(null)
  const inputNotes = useRef<EventInput_rectangle>(null)

  useEffect(() => {
    loadData()
  }, [])

  function loadData() {
    new LibCurl(url, null, (res, msg) => {
      setResult(res)
    }, (error) => {
      setError(error)
    }, 1)
  }
  
  function confirmReport(url: string, event_id: any, user_id: any) {
    LibDialog.confirm(esp.lang("event/counter_report_detail", "report_title"), esp.lang("event/counter_report_detail", "report_msg"), esp.lang("event/counter_report_detail", "report_confirm"), () => {
      LibProgress.show(esp.lang("event/counter_report_detail", "report_wait"))
      let post = {
        event_id: event_id,
        user_id: user_id,
        notes: inputNotes.current?.getText()
      }
      new LibCurl(url, post, (res, msg) => {
        LibProgress.hide()
        LibNavigation.back()
      }, (error) => {
        LibDialog.warning(esp.lang("event/counter_report_detail", "report_failed"), error?.message)
        LibProgress.hide()
      }, 1)
    }, esp.lang("event/counter_report_detail", "report_cancel"), () => {

    })
  }

  if (!result) {
    return <LibLoading />
  }

  if (error) {
    return (
      <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
        <EventHeader title={esp.lang("event/counter_report_detail", "header_error")} />
        <EventMessage message={error?.message} />
      </View>
    )
  }

  return (
    <View style={{ flex: 1, backgroundColor: LibStyle.colorBgGrey }}>
      <EventHeader title={esp.lang("event/counter_report_detail", "header_title")} subtitle={esp.lang("event/counter_report_detail", "header_subtitle", result?.user?.name)} />
      <ScrollView>
        <View style={{ backgroundColor: '#fff', padding: 10, margin: 15, borderRadius: 10, ...LibStyle.elevation(2) }}>
          <View style={{ flexDirection: 'row', marginBottom: 10, justifyContent: 'space-between', alignContent: 'center', alignItems: 'center' }}>
            <View style={{ flexDirection: 'row', alignContent: 'center', alignItems: 'center' }}>
              <View style={{ height: 50, width: 50, borderRadius: 10, backgroundColor: '#fff', ...LibStyle.elevation(10) }}>
                <LibPicture source={{ uri: result?.user?.image }} style={{ height: 50, width: 50, borderRadius: 10 }} />
              </View>
              <View style={{ marginLeft: 10, marginRight: 15, }}>
                <Text allowFontScaling={false} style={{ fontFamily: 'SFProText', fontWeight: 'bold', fontSize: 16, flexWrap: 'wrap' }}>{result?.user?.name}</Text>
                <Text allowFontScaling={false} style={{ fontFamily: 'SFProText', fontWeight: 'normal', color: '#CECED3', fontSize: 12, flexWrap: 'wrap' }}>{result?.user?.email}</Text>
              </View>
            </View>
          </View>

          <View style={{ flexDirection: 'row', borderRadius: 5, borderBottomLeftRadius: 0, borderBottomRightRadius: 0, padding: 10, paddingBottom: 5, overflow: 'hidden', backgroundColor: LibStyle.colorBgGrey }}>
            <Text allowFontScaling={false} style={{ alignSelf: 'center', textAlign: 'center', fontFamily: "Arial", fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#000" }}>{esp.lang("event/counter_report_detail", "money")}</Text>
          </View>

          <RenderDetail
            data={result?.money}
            date_end={result?.date_end}
            date_start={result?.date_start}
            type={2}
            onPressExpenditure={() => {
              LibNavigation.navigate('event/counter_report_breakdown', { data: result?.money?.credit, type: 2 })
            }}
            onPressIncome={() => {
              LibNavigation.navigate('event/counter_report_breakdown', { data: result?.money?.debit, type: 2 })
            }}
          />

          {
            result?.tickets?.length > 0 && result?.tickets?.map((item: any, i: number) => {
              return (
                <>
                  <View style={{ marginTop: 15, flexDirection: 'row', borderRadius: 5, borderBottomLeftRadius: 0, borderBottomRightRadius: 0, padding: 10, paddingBottom: 5, overflow: 'hidden', backgroundColor: LibStyle.colorBgGrey }}>
                    <Text allowFontScaling={false} style={{ alignSelf: 'center', textAlign: 'center', fontFamily: "Arial", fontWeight: "bold", fontStyle: "normal", letterSpacing: 0, color: "#000" }}>{item.title}</Text>
                  </View>
                  <RenderDetail
                    data={item}
                    date_end={result?.date_end}
                    date_start={result?.date_start}
                    type={1}
                    onPressExpenditure={() => {
                      LibNavigation.navigate('event/counter_report_breakdown', { data: item?.credit, type: 1 })
                    }}
                    onPressIncome={() => {
                      LibNavigation.navigate('event/counter_report_breakdown', { data: item?.debit, type: 1 })
                    }}
                  />
                </>
              )
            })
          }

        </View>

      </ScrollView>
      <View style={{ padding: 10 }}>
        <EventButton label={esp.lang("event/counter_report_detail", "send_daily_report")} onPress={() => {
          // confirmReport(result?.url_confirm, result?.event_id, result?.user_id)
          dialogNotes.current?.show()
        }} backgroundColor={LibStyle.colorPrimary} fontColor='#000' />
      </View>

      {/* dialog notes */}
      <LibSlidingup ref={dialogNotes}>
        <View style={{ backgroundColor: '#f6f6f6', borderTopRightRadius: 20, borderTopLeftRadius: 20, paddingHorizontal: 19, }}>
          <Text allowFontScaling={false} style={{ marginTop: 26, marginBottom: 23, fontFamily: "Arial", fontSize: 16, fontWeight: "bold", fontStyle: "normal", lineHeight: 22, letterSpacing: 0, textAlign: "center", color: "#34495e" }}>{esp.lang("event/counter_report_detail", "notes")}</Text>

          <EventInput_rectangle
            ref={inputNotes}
            keyboardType="default"
            returnKeyType="go"
            placeholder={esp.lang("cashier/invoice", "label_note")}
            maxLength={150}
            onSubmitEditing={() => {
              // inputNotes.current?.blur()
              // dialogUser.current?.show()
            }}
            inputStyle={{ marginTop: 10, height: 70, textAlignVertical: 'top' }} style={{ height: 70, textAlignVertical: 'top', borderRadius: 4 }} multiline />

          <EventButton label={esp.lang("event/counter_report_detail", "send")} onPress={() => {
            confirmReport(result?.url_confirm, result?.event_id, result?.user_id)
          }} backgroundColor={LibStyle.colorPrimary} fontColor='#000' style={{ marginTop: 25, marginBottom: 20 }} />

        </View>
      </LibSlidingup>

    </View>
  )
}