// withHooks
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';


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 { LibInput } from 'esoftplay/cache/lib/input/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 { LibScroll } from 'esoftplay/cache/lib/scroll/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 { LibToastProperty } from 'esoftplay/cache/lib/toast/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketButton } from 'esoftplay/cache/market/button/import';
import { MarketChip } from 'esoftplay/cache/market/chip/import';
import { MarketHeader } from 'esoftplay/cache/market/header/import';
import { MarketImage_picker } from 'esoftplay/cache/market/image_picker/import';
import { MarketInput_square } from 'esoftplay/cache/market/input_square/import';
import { MarketRating_input } from 'esoftplay/cache/market/rating_input/import';
import { MarketSection_menu } from 'esoftplay/cache/market/section_menu/import';

import React, { useRef } from 'react';
import { TouchableOpacity, View } from 'react-native';


export interface MarketProduct_review_sendArgs {
  products: any,
  data: any,
  ratingNumber: number
}
export interface MarketProduct_review_sendProps {

}

export default function m(props: MarketProduct_review_sendProps): any {
  const { products, data, ratingNumber } = LibNavigation.getArgsAll<any>(props)
  const [rating, setRating, getRating] = useSafeState(ratingNumber)
  const reviewText = useRef<LibInput>(null)
  const imagePicker = useRef<LibSlidingup>(null)
  let inputReview = useRef('').current
  const status = [esp.lang("market/product_review_send", "empty"), esp.lang("market/product_review_send", "very_bad"), esp.lang("market/product_review_send", "bad"), esp.lang("market/product_review_send", "standar"), esp.lang("market/product_review_send", "good1"), esp.lang("market/product_review_send", "very_good")]
  const imgWidth = (LibStyle.width - 64) / 4
  const [images, setImages, getImages] = useSafeState<any>([])
  const [loading, setLoading] = useSafeState<boolean>(false)

  const fast_review = [
    {
      text: esp.lang("market/product_review_send", "good")
    },
    {
      text: esp.lang("market/product_review_send", "oroginal")
    },
    {
      text: esp.lang("market/product_review_send", "guarantee")
    }
  ]

  function setReview(t: string) {
    if (inputReview.length < 1) {
      inputReview = t
    } else {
      inputReview = inputReview + ', ' + t
    }
    reviewText.current!.setText(inputReview)
  }

  function deleteImage(url: string): void {
    LibDialog.warningConfirm(esp.lang("market/product_review_send", "delete_title"), esp.lang("market/product_review_send", "delete_msg"), esp.lang("market/product_review_send", "delete_confirm"),
      () => {
        let _image = getImages().filter((item: any) => item != url)
        setImages(_image)
      }, esp.lang("market/product_review_send", "delete_cancel"),
      () => { })
  }

  function sendReview() {

    if (getRating() == 0) {
      LibToastProperty.show(esp.lang("market/product_review_send", "empty_rating"))
      return
    }

    let post = {
      product_id: products.product_id,
      price_id: products.price_id,
      review: reviewText.current!.getText() || '', //optional
      review_rating: getRating(),
      review_images: JSON.stringify(getImages()) //optional
    }
    esp.log(post);
    LibProgress.show(esp.lang("market/product_review_send", "review_wait"))
    setLoading(true)
    new LibCurl("shop/order_detail_review/" + data.sale_id, post,
      (res) => {
        esp.log(res);
        setLoading(false)
        LibProgress.hide()
        LibToastProperty.show(res)
        LibNavigation.back()
      }, (msg) => {
        esp.log(msg);
        LibToastProperty.show(msg?.message)
        setLoading(false)
        LibProgress.hide()
      }, 1
    )
  }

  return (
    <View style={{ flex: 1 }}>
      <MarketHeader
        title={data?.invoice_merchant || esp.lang("market/product_review_send", "header_title")} leftIcon={{
          name: "arrow-left", onPress: () => {
            LibDialog.warningConfirm(esp.lang("market/product_review_send", "back_title"), esp.lang("market/product_review_send", "back_msg"), esp.lang("market/product_review_send", "back_confirm"), () => { LibNavigation.back() }, esp.lang("market/product_review_send", "back_cancel"), () => { })
          }
        }}
      />
      <LibScroll>
        <View style={{ flexDirection: "row", margin: 17, marginBottom: 10 }} >
          <View style={{ width: 50, height: 50, borderRadius: 4, backgroundColor: "#f1f2f3" }}>
            <LibPicture source={{ uri: products?.product_image }} style={{ width: 50, height: 50, borderRadius: 5 }} resizeMode="cover" />
          </View>
          <View style={{ flex: 1, marginLeft: 10 }} >
            <LibTextstyle textStyle="callout" text={products?.product_name} />
            <LibTextstyle textStyle="callout" text={data?.invoice_merchant} style={{ color: "#999", fontSize: 12 }} />
          </View>
        </View>
        <View style={{ margin: 17, marginVertical: 10, padding: 10, backgroundColor: "#f8f8f8", borderRadius: 5 }} >
          <LibTextstyle text={status[rating]} textStyle="subhead" style={{ alignSelf: "center" }} />
          <MarketRating_input
            starSize={40}
            defValue={ratingNumber}
            onChangeRating={setRating}
            style={{ alignSelf: "center", paddingTop: 10 }} />
        </View>
        <MarketSection_menu smooth title={esp.lang("market/product_review_send", "add_images")} />
        <View style={{ flexDirection: "row", flexWrap: "wrap", marginLeft: 17, marginTop: 10 }} >
          <TouchableOpacity onPress={() => { imagePicker.current!.show() }} style={{ width: imgWidth, height: imgWidth, backgroundColor: LibStyle.colorGrey, marginRight: 10, marginBottom: 10, borderRadius: 5, alignItems: "center", justifyContent: "center" }}>
            <LibIcon name="image-plus" color={"#999"} size={30} />
          </TouchableOpacity>
          {
            LibUtils.checkUndefined(images, "0") && images.map((img: any, i: number) => (
              <TouchableOpacity key={i} onPress={() => deleteImage(img)} style={{ width: imgWidth, height: imgWidth, backgroundColor: LibStyle.colorGrey, marginRight: 10, marginBottom: 10, borderRadius: 5, alignItems: "center", justifyContent: "center" }}>
                <LibPicture source={{ uri: img }} style={{ width: imgWidth, height: imgWidth, borderRadius: 5 }} resizeMode="cover" />
                <View style={{ position: "absolute", top: 5, right: 5, width: 24, height: 24, borderRadius: 12, backgroundColor: "white", alignItems: "center", justifyContent: "center" }} >
                  <LibIcon name="trash-can-outline" color={LibStyle.colorRed} size={16} />
                </View>
              </TouchableOpacity>
            ))
          }
        </View>
        <MarketSection_menu smooth title={esp.lang("market/product_review_send", "add_rating")} />
        <MarketInput_square
          _ref={reviewText}
          defaultValue={inputReview}
          style={{ height: 100, textAlignVertical: "top" }}
          multiline
          placeholder={esp.lang("market/product_review_send", "placeholder_review")}
          onChangeText={(t) => { inputReview = t }} />
        <MarketSection_menu smooth title={esp.lang("market/product_review_send", "fast_rating")} />
        <View style={{ flexDirection: "row", flexWrap: "wrap", paddingHorizontal: 17 }} >
          {
            fast_review.map((rev: any, i: number) => (
              <MarketChip
                key={i}
                onTextSelect={(x) => { setReview(x) }}
                selected={false}
                text={rev.text} />
            ))
          }
        </View>
      </LibScroll>

      <MarketButton
        textStyle={{ color: 'white' }}
        text={esp.lang("market/product_review_send", "btn_send")}
        loading={loading}
        buttonStyle={{ margin: 10 }}
        onPress={sendReview} />

      <MarketImage_picker
        _ref={imagePicker}
        onFinish={(x) => {
          setImages([...images, x])
        }} />
    </View>
  )
}