import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {View, StyleSheet, Text, ScrollView, Image, TouchableOpacity} from 'react-native';
import { AppContainer } from '../container/container';
import themeColors from '../assets/colors';
import { AuctionBottomTab } from '../Navigations/AuctionBottomTab';
import { AppTextInput } from '../components/text_input.component';
import { AppButton } from '../components/button.component';
import { AppDatePicker } from '../components/datpicker.component';
import { MaterialIcons } from "@expo/vector-icons";
import Toast from 'react-native-root-toast';

const  UserAuctionCreateScreen =  ({route, navigation}) => {
  const [image, setImage] = useState('https://via.placeholder.com/50');
  const [auctionName, setAuctionName] = useState('');
  const [auctionPrice, setAuctionPrice] = useState('');
  const [expireDate, setExpireDate] = useState('');

  useEffect(() => {
    if (route.params === undefined) {
      setImage('https://via.placeholder.com/50')
    } else {
      setImage(route.params.image)
    }
  }, [])

  const itemNameChange = (itemName) => {
    setAuctionName(itemName);
  }

  const itemPriceChange = (itemPrice) => {
    setAuctionPrice(itemPrice);
  }

  const handleDateChange = (selectedDate) => {
    setExpireDate(selectedDate);
  }

  const handleSubmit = () => {
    let auctionObj = {
        name: auctionName,
        owner: "Pramodh Rajapakse",
        bids: [],
        starting_price: auctionPrice,
        expire_date: expireDate,
        images: [image]
    }

    axios.post("http://127.0.0.1:8085/auctions", auctionObj)
      .then( async function (response) {
        if (response.data.message === 'Created') {
          const successMsg = Toast.show('Your auction has been created successfully', {
            duration: Toast.durations.LONG,
          });
          setTimeout(function hideToast() {
            Toast.hide(successMsg);
          }, 1000);
          navigation.navigate('AuctionHomeScreen');
        } else {
          const errMsg = Toast.show('Auction Creation Failed', {
            duration: Toast.durations.LONG,
          });
          setTimeout(function hideToast() {
            Toast.hide(errMsg);
          }, 1000);
        }
      })
      .catch(function (error) {
        const errMsg = Toast.show('Auction Creation Failed', {
          duration: Toast.durations.LONG,
        });
        setTimeout(function hideToast() {
          Toast.hide(errMsg);
        }, 1000);
      });
  }

  return (
    <View style={styles.container}>
      <AppContainer>
        <View style={styles.header}>
          <Text style={styles.auctionHeading}>Create Auction</Text>
        </View>
        <ScrollView>
          <View>
            <AppTextInput placeholder='Enter item name' onChangeText={(val) => itemNameChange(val)}/>
            <AppTextInput placeholder='Enter item price' onChangeText={(val) => itemPriceChange(val)} keyboardType='numeric'/>
            <View style={styles.dateContainer}>
              <Text style={styles.label}>Expire Date</Text>
             <AppDatePicker onDateSelect={handleDateChange}/>
            </View>
            <Text style={styles.imgLabel}>Item Image</Text>
            <View style={styles.addImagewrapper}>
              <View style={styles.imageContainer}>
                <Image source={{
                  uri: image,
                }} style={styles.images}/>
              </View>
              <View style={styles.addImageBtnContainer}>
                <TouchableOpacity style={styles.addImageBtn} onPress={() => {navigation.navigate('AuctionCameraScreen')}}>
                  <MaterialIcons name="add-a-photo" size={24} color={themeColors.WHITE} />
                </TouchableOpacity>
              </View>
            </View>
            <AppButton label='Add Item' onPress={() => handleSubmit()}/>
          </View>
      </ScrollView>
      </AppContainer>
      <AuctionBottomTab/>
    </View>
  );
};
export default UserAuctionCreateScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 30,
    backgroundColor: '#ffffff'
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    height: 50
  },
  auctionHeading: {
    fontSize: 24,
    fontWeight: 'bold',
    color: themeColors.BLACK,
  },
  label: {
    flex: 1,
    fontSize: 16,
    fontWeight: '500',
    color: themeColors.BLACK,
    alignSelf: 'center'
  },
  imgLabel: {
    flex: 1,
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 10,
    color: themeColors.BLACK,
  },
  dateContainer: {
    flex: 1,
    flexDirection: 'row',
    marginTop: 20,
    marginBottom: 40
  },
  addBtn:{
    alignItems: "center",
    padding: 8,
    backgroundColor: themeColors.BLACK,
    borderRadius: 20,
    shadowColor: 'rgba(0,0,0, .4)',
    shadowOffset: { height: 2, width: 1 },
    shadowOpacity: 1,
    shadowRadius: 1,
    elevation: 2,
    height: 33
  },
  addImagewrapper : {
    height: 100,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 20
  },
  images: {
    width: 100,
    height: 100,
    borderRadius: 10,
    resizeMode: 'contain'
  },
  imageContainer: {
    height: 50,
    marginRight: 50,
    borderRadius: 50,
  },
  addImageBtnContainer: {
    width: 50,
    height: 50,
    borderRadius: 50
  },
  addImageBtn: {
    width: 50,
    height: 50,
    borderRadius: 50,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: themeColors.BLACK
  },
})