import React, { useState, useEffect } from 'react';
import {
  SafeAreaView,
  TextInput,
  View,
  Text,
  TouchableOpacity, Image,
  ScrollView,
  FlatList, Button
} from 'react-native';
import { useSelector } from 'react-redux';
import { useNavigation } from '@react-navigation/core';
import styles from './index.style';
import Header from '../../components/Header';
import IconMedlink from '../../components/IconMedlink';
import HeaderTitle from '../../components/HeaderTitle';
import { Data } from "../../model/product";
//-------------------------------------------------------------------
import axios from "axios";
import config from "../../configs"
import ItemCartProduct from '../../components/ItemCartProduct';
import { RootState } from '../../redux/reducers';

const App = () => {
  const navigation = useNavigation()
  const _renderHeaderLeft = () => {
    return (
      <IconMedlink />
    )
  }
  const _renderHeaderCenter = () => {
    return (
      <HeaderTitle title='Tạo đơn' />
    )
  }
  const _renderHeaderRight = () => {
    return (
      <TouchableOpacity>
        <Image style={styles.rightHeader}
          source={require('../../assets/icon/iconHeader/icon-scan-2.png')} />
      </TouchableOpacity>
    )
  }
  const _renderHeader = () => (
    <Header
      elementLeft={_renderHeaderLeft()}
      elementCenter={_renderHeaderCenter()}
      elementRight={_renderHeaderRight()}
    />
  )
  const _renderButtonAdd = () => (
    <TouchableOpacity style={styles.buttonAdd}
      onPress={() => navigation.navigate('HomeProductCreate')}
    >
      <Image style={styles.iconAdd}
        source={require('../../assets/icon/iconHome/icon-cart-2.jpg')} />
      <Text style={styles.textAdd}>Đơn hàng của bạn chưa có</Text>
      <Text style={styles.textAdd}>sản phẩm nào</Text>
    </TouchableOpacity>
  )
  /////////////////////////////////////////////////////////////////////////////
  const products = useSelector((state) => state.product)
  console.log('///////////////////////////////////////////////////////////////////////////////\n', products)
  const [product, setProduct] = useState(products)
  useEffect(() => {
    setProduct(products);
  }, [products]);
  //----------------------------------------------------------------------------------------
  const cartProducts = useSelector((state:RootState) => state.cart.products)
  console.log('CART: ', cartProducts)
  const sumCart = (product: Array<Data>) => {
    let sum = 0
    for (let i = 0; i <= product.length; i++) {
      let price = product[i].price
      let quantity = product[i].quantity
      sum += price * quantity
      console.log('Tong:', sum)
    }
    return sum
  }
  // const totalAmount = sumCart(cartProducts)
  // console.log('TONG: CART', totalAmount)

  const _renderCart = (product: Data) => {
    return (
      <View >
        <ItemCartProduct
          drg_drug_cd={product.drg_drug_cd}
          drg_drug_name={product.drg_drug_name}
          price={product.price}
          quantity={product.quantity}
        />
      </View>
    )
  }
  //----------------------------------------------------------------------------------------
  const [amount, setAmount] = useState(35264)
  const [amountPaid, setAmountPaid] = useState('0')
  const [amountVat, setAmountVat] = useState('')
  const [discount, setDiscount] = useState(0)
  const [note, setNote] = useState('')
  const [currentPaid, setCurrentPaid] = useState(0)
  const _renderBillDate = () => (
    <View style={styles.billDateContainer}>
      <View style={styles.lineContainer}>
        <Text>Ngày bán</Text>
        <View style={styles.lineLeftContainer}>
          <TextInput style={styles.input}
            placeholder='2021-07-05'
            placeholderTextColor='black' />
        </View>
      </View>
      <View style={styles.lineContainer}>
        <Text>Tổng tiền</Text>
        <Text>{`35264 VNĐ`}</Text>
      </View>
      <View style={styles.lineContainer}>
        <Text>VAT</Text>
        <View style={styles.lineLeftContainer}>
          <View></View>
          <TextInput style={styles.input} placeholder='10%' placeholderTextColor='black' />
        </View>
      </View>
      <View style={styles.lineContainer}>
        <Text>Giảm giá</Text>
        <View style={styles.lineLeftContainer}>
          <TextInput style={styles.input} placeholder='0' placeholderTextColor='black'
            onChangeText={(value) => { setAmount(Number(value)) }} />
          <TextInput style={styles.input} placeholder='VNĐ' placeholderTextColor='black' />
        </View>
      </View>
    </View>
  )
  //----------------------------------------------------------------------------------------

  //----------------------------------------------------------------------------------------

  const token = useSelector((state:RootState) => state.auth.token);
  console.log('BillToken: ', token)
  const submit = () => {
    console.log('Sending....')
    createInvoice()
  }
  const createInvoice = async () => {
    console.log('create....')
    const invoice = {
      'amount_debt': 0, 'currency': "VNĐ", 'customer_code': "", 'customer_id': 0, 'customer_name': "", 'customer_phone_no': "", 'discount_amount': 0,
      'discount_amount_inv': 0, 'discount_type': "VNĐ", 'ecoin_minus': 0, 'ecoin_plus': 0, 'img_url': "", 'invoice_type': 0, 'is_debit': false,
      'issue_datetime': "2021-07-05T15:45:16+07:00", 'pay_method': "CS", 'pay_reference': "\"\"", 'status': 2, 'vat': 10,
      //--------------------
      'amount': amount,
      'amount_paid': amount*1.1,
      'amount_vat': amount*0.1,
      'current_pay': 40000,
      'note': note,
    }
    const newProduct = {
      base_quantity: 1,
      discount: 0,
      discount_type: "VNĐ",
      discount_unit: 0,
      dosage: cartProducts.dosage,
      drg_drug_cd: cartProducts.drg_drug_cd,
      drg_drug_name: cartProducts.drg_drug_name,
      drug_id: cartProducts.drug_id,
      drug_unit_id: cartProducts.drug_unit_id,
      import_price: 0,
      inv_id: cartProducts.inv_id,
      lot: cartProducts.lot,
      price: cartProducts.price,
      promotion_flg: 0,
      quantity: 2,
      unit_id: 14,
      unit_name: "Viên"
    }
    console.log('function', cartProducts)
    const body = {
      'invoice': invoice,
      'products': cartProducts
    }
    console.log('function', body)
    const header = {
      headers: {
        'Authorization': token
      }
    }
    const baseURL = config.axiosConfig().baseURL
    try {
      const response = await axios.post(`${baseURL}/invoice`, body, header)
      // const totalDashboard = response.data
      // console.log('Data: ', response.data)
      // console.log('total: ', response.data.today_total_revenue)
      console.log(response)
      return response
    } catch (error) {
      if (axios.isAxiosError(error)) {
        handleAxiosError(error);
      } else {
        handleUnexpectedError(error);
      }
    }
  }
  const handleAxiosError = (error: object) => {
    console.log(error)
  }
  const handleUnexpectedError = (error: object) => {
    console.log(error)
  }
  //----------------------------------------------------------------------------------------
  const _renderCustomerInfo = () => (
    <View style={styles.customerContainer}>
      <Text>Khách hàng: Vãng lai</Text>
      <TouchableOpacity style={styles.buttonAddCustomer}>
        <Image
          source={require('../../assets/icon/iconHome/icon-customer.png')} />
        <Text style={{ color: 'blue' }}>  Thêm khách hàng</Text>
      </TouchableOpacity>
      <View style={styles.inputCustomerContainer}>
        <Text>Khách trả:</Text>
        <TextInput style={styles.inputCustomer}
          placeholder='0' placeholderTextColor='black'
          keyboardType='numeric'
          onChangeText={(value) => setCurrentPaid(Number(value))}
        ></TextInput>
      </View>
    </View>
  )
  const _renderNote = () => (
    <View style={styles.noteContainer} >
      <View style={styles.noteTitleContainer}>
        <Image
          source={require('../../assets/icon/iconHome/icon-customer.png')} />
        <Text style={{ color: 'blue' }}>  Ghi chú</Text>
      </View>
      <TextInput style={styles.input} onChangeText={(text) => setNote(text)} />
    </View>
  )
  return (
    <SafeAreaView >
      {_renderHeader()}
      <ScrollView style={styles.container}>
        {_renderButtonAdd()}
        <FlatList
          data={cartProducts}
          renderItem={({ item }) => _renderCart(item)}
          keyExtractor={(item) => item}
        />
        {_renderBillDate()}
        {_renderCustomerInfo()}
        {_renderNote()}
        <Button onPress={() => submit()} title='SEND'></Button>
      </ScrollView>
    </SafeAreaView>
  );
};
export default App;
