import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert, ScrollView, TouchableOpacity, Modal } from 'react-native';
import axios from 'axios';
import { Picker } from '@react-native-picker/picker';
import RadioForm from 'react-native-simple-radio-button';
import Toast from 'react-native-toast-message';
import DateTimePicker from '@react-native-community/datetimepicker';

const baseURL = 'http://192.168.8.101:5000/predict_order_date';
const endMyPoint = '/predict_order_date';

const plantTypes = [
  "Lemon Lime",
  "Enjoy",
  "Black Cardinal",
  "Marble Queen",
  "Livistonia"

]
const plantVarieties = [
  "philodreadon",
  "pothos"
]

const fertilizerTypes = [
  "Yaramila",
  "Foliar application k44",
  "Growemore k44"
]
const mediaGrowns =[
     "coir_cowdung",
     "coir_cowdung_coco_chips",
     "coir"
]
const currentGrowthCategories =
[
    "mature_well_grown",
    "medium_level_poorly_growing",
    "medium_level_well_growing",
    "recently_planted_poorly_growing",
    "recently_planted_well_growing",
    "small_level_poorly_growing",
    "small_level_well_growing"
]

const potTypes =
[
    "8cm_pot",
    "hanging_pot",
    "net_pot",
    "12cm_pot"
]

const shadeTypes =
[
    "70_shade_net",
    "60_shade_net"
]
const HeaderComponent = ({ onBack }) => {
  return (
    <View style={styles.headerContainer}>
      <TouchableOpacity onPress={onBack}>
        <Text style={styles.backButton}>←</Text>
      </TouchableOpacity>
      <Text style={styles.headerTitle}>Predict the Growth Duration</Text>
    </View>
  );
};
const PredictOrder = () => {
  const [plantType, setPlantType] = useState('');
  const [plantVariety, setPlantVariety] = useState('');
  const [fertilizerType, setFertilizerType] = useState('');
  const [fertilizerRatio, setFertilizerRatio] = useState('');
  const [growthDuration, setGrowthDuration] = useState('');
  const [mediaGrown, setMediaGrown] = useState('');
  const [currentGrowthCategory, setCurrentGrowthCategory] = useState('');
  const [currentPotType, setCurrentPotTypey] = useState('');
  const [currentShadeType, setCurrentShadeType] = useState('');
  const [fertilzerRatioError, setFertlizerRatioError] = useState('');
  const [growthDurationError,  setGrowthDurationError] = useState('');

  
  const [focusedInput, setFocusedInput] = useState('');
  const [showPredictionWidget, setShowPredictionWidget] = useState(false);
  const [predictedType, setPredictedOrderDuration] = useState('');
  const [predictionError, setPredictionError] = useState('');
  
  
 


  

  const validateFertlizerRatio = (value) => {
    if (isNaN(value) || value > 10) {
      setFertlizerRatioError('fertilizer should not exceed 10g.');
      return false;
    }
    setFertlizerRatioError('');
    return true;
  };

  const validateGrowthDuration = (value) => {
    if (isNaN(value) || value > 200) {
      setGrowthDurationError('Growth duration should not exceed 200 days.');
      return false;
    }
    setGrowthDurationError('');
    return true;
  };


  const isFormComplete = () => {
    return (
      plantType &&
      plantVariety &&
      fertilizerType &&
      fertilizerRatio &&
      growthDuration &&
      mediaGrown &&
      currentGrowthCategory &&
      currentPotType &&
      currentShadeType

    );
  };


  const handlePredictionGrowthDuration = async () => {
    console.log('Button Pressed!');




    try {
      // Parsing the data as per backend requirements
      const postData = {
        FERTILZER_RATIO: parseInt(fertilizerRatio, 10),
        GROWTH_DURATION: parseInt(growthDuration,10),
        MEDIA_GROWN: mediaGrown,
        CURRENT_GROWTH_CATEGORY: currentGrowthCategory,
        CURRENT_POT_TYPE: currentPotType,
        SHADE_TYPE: currentShadeType,
        
      };
      // Print out the postData object
      console.log("postData:", postData);

      // Updated Axios request with headers
      const response = await axios.post(baseURL, postData, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },

      });


      if (response.data) {
        if (response.data['Predicted Order Date']) {
          setPredictedOrderDuration(response.data['Predicted Order Date']);
          setShowPredictionWidget(true);
        } else if (response.data['error']) {
          setPredictionError(response.data['error']);
          Alert.alert("Prediction Error", predictionError);
        } else {
          Alert.alert("Error", "Received unexpected data from the server.");
        }
      }

    } catch (error) {
      console.log(error);
      Alert.alert("Error", error.message);

    }
  };


  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
      <HeaderComponent onBack={() => navigation.goBack()} />

      <View style={styles.formContainer}>
        <Text style={styles.inputTitle}>Select Plant Type</Text>
        <Picker style={styles.pickerContainer}
          selectedValue={plantType}
          onValueChange={value => setPlantType(value)}
        // style={styles.picker}
        >
          <Picker.Item label="Select the plant type" value="" color="#999" />
          {plantTypes.map(plant => (
            <Picker.Item key={plant} label={plant} value={plant} />
          ))}
        </Picker>
        <Text style={styles.inputTitle}>Select Plant Variety</Text>
        <Picker style={styles.pickerContainer}
          selectedValue={plantVariety}
          onValueChange={value => setPlantVariety(value)}
        // style={styles.picker}
        >
          <Picker.Item label="Select the plant variety" value="" color="#999" />
          {plantVarieties.map(variety => (
            <Picker.Item key={variety} label={variety} value={variety} />
          ))}
        </Picker>
        <Text style={styles.inputTitle}>Select fertilizer type applied</Text>
        <Picker style={styles.pickerContainer}
          selectedValue={fertilizerType}
          onValueChange={value => setFertilizerType(value)}
        // style={styles.picker}
        >
          <Picker.Item label="Select the plant type" value="" color="#999" />
          {fertilizerTypes.map(fertilzer => (
            <Picker.Item key={fertilzer} label={fertilzer} value={fertilzer} />
          ))}
        </Picker>
        <Text style={styles.inputTitle}>Fertilizer amount applied:</Text>

        <TextInput
          value={fertilizerRatio}
          onChangeText={(value) => {
            setFertilizerRatio(value);
            validateFertlizerRatio(value);
          }}
          style={[
            styles.input,
            focusedInput === 'fertilizerRatio' ? styles.inputFocused : {},
            fertilzerRatioError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="amount of fertlizer applied"
          onFocus={() => setFocusedInput('fertilizerRatio')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{fertilzerRatioError}</Text>

        <Text style={styles.inputTitle}>How long has the plant been growing?:</Text>

        <TextInput
          value={growthDuration}
          onChangeText={(value) => {
            setGrowthDuration(value);
            validateGrowthDuration(value);
          }}
          style={[
            styles.input,
            focusedInput === 'growthDuration' ? styles.inputFocused : {},
            growthDurationError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="the growth duration in days"
          onFocus={() => setFocusedInput('growthDuration')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{growthDurationError}</Text>

        <Text style={styles.inputTitle}>What is the media plant growing?</Text>
        <Picker style={styles.pickerContainer}
          selectedValue={mediaGrown}
          onValueChange={value => setMediaGrown(value)}
        // style={styles.picker}
        >
          <Picker.Item label="What is the media plant growing?" value="" color="#999" />
          {mediaGrowns.map(media => (
            <Picker.Item key={media} label={media} value={media} />
          ))}
        </Picker>

        <Text style={styles.inputTitle}> the current growing stage </Text>
        <Picker style={styles.pickerContainer}
          selectedValue={currentGrowthCategory}
          onValueChange={value => setCurrentGrowthCategory(value)}
        // style={styles.picker}
        >
          <Picker.Item label="the current growing stage" value="" color="#999" />
          {currentGrowthCategories.map(category => (
            <Picker.Item key={category} label={category} value={category} />
          ))}
        </Picker>

  

      </View>
      <View style={styles.formContainer}>
      <Text style={styles.inputTitle}> current pot type </Text>
        <Picker style={styles.pickerContainer}
          selectedValue={currentPotType}
          onValueChange={value => setCurrentPotTypey(value)}
        // style={styles.picker}
        >
          <Picker.Item label="current pot type" value="" color="#999" />
          {potTypes.map(pot => (
            <Picker.Item key={pot} label={pot} value={pot} />
          ))}
        </Picker>

        <Text style={styles.inputTitle}> current shade type provided </Text>
        <Picker style={styles.pickerContainer}
          selectedValue={currentShadeType}
          onValueChange={value => setCurrentShadeType(value)}
        // style={styles.picker}
        >
          <Picker.Item label="current shade type" value="" color="#999" />
          {shadeTypes.map(shade => (
            <Picker.Item key={shade} label={shade} value={shade} />
          ))}
        </Picker>


        <TouchableOpacity
          style={[styles.button, !isFormComplete() && styles.buttonDisabled]}
          onPress={handlePredictionGrowthDuration}
          disabled={!isFormComplete()}
        >
          <Text style={styles.buttonText}>Predict the duration to grow </Text>
        </TouchableOpacity>

      </View>
      {showPredictionWidget && (
        <Modal
          animationType="slide"
          transparent={true}
          visible={showPredictionWidget}
          onRequestClose={() => {
            setShowPredictionWidget(false);
          }}
        >
          <View style={styles.centeredView}>
            <View style={styles.modalView}>
              <Text style={styles.modalText}>Your plant will take about  : {predictedType}</Text>
              <Text style={styles.modalText}>to grow to the expected level of order. </Text>
              <TouchableOpacity
                style={{ ...styles.button, backgroundColor: '#90ee90' }}
                onPress={() => setShowPredictionWidget(false)}
              >
                
                <Text style={styles.textStyle}>Got It!</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>

      )}

    </ScrollView>
  );
};

const styles = StyleSheet.create({
  contentContainer: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  container: {
    flex: 1,
    padding: 10,
    backgroundColor: '#f4f4f4',
  },

  formContainer: {
    backgroundColor: 'white',
    padding: 20,
    borderRadius: 10,
    elevation: 4,
    width: '100%',
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
  },
  inputTitle: {
    fontSize: 16,
    color: '#7aae64',
    marginBottom: 5,
  },
  input: {
    borderWidth: 1,
    borderColor: 'darkgreen',
    padding: 10,
    fontSize: 16,
    borderRadius: 4,
    marginBottom: 20,
    backgroundColor: 'white',
  },
  inputFocused: {
    backgroundColor: '#f0fff0',
  },
  pickerContainer: {
    borderColor: 'black',
    borderWidth: 1,
    borderRadius: 5,
    // padding: 1,
    marginBottom: 10,
  },
  button: {
    backgroundColor: '#90EE90', // LightGreen
    padding: 10,
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
  },
  buttonText: {
    color: 'darkgreen',
    fontWeight: 'bold',
  },
  buttonDisabled: {
    backgroundColor: '#90EE90',
    opacity: 0.5,
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 1,
    backgroundColor: "#f0ffff",
    opacity: 0.8,
    borderColor: "#006400",
    borderRadius: 6,
    height: "100%",
    width: "100%",
    paddingLeft: 10

  },
  modalView: {
    margin: 20,
    backgroundColor: "#e0ffff",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: "40%",
      height: "60%"
    },
    shadowOpacity: 0.35,
    shadowRadius: 10,
    shadowColor: "#696969",
    elevation: 5
  },
  textStyle: {
    color: "#006400",
    fontWeight: "bold",
    textAlign: "center",
    fontFamily: 'sans-serif-medium',
    fontSize: 15
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
    fontFamily: 'sans-serif-medium',
    fontSize: 22,
    paddingBottom: 3,
    color: "#006400"


  },
  errorMessage: {
    color: '#dc143c',
    marginBottom: 20,
    fontWeight:"thin",
    fontSize: 10
  },
  errorInput: {
    borderColor: '#8b0000',
    backgroundColor: '#ffc0cb',
  },

  headerContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#7aae64',
    width: '100%',
    marginBottom: 2,
    height:80
    
  },
  backButton: {
    fontSize: 30,
    marginRight: 20,
    color: 'white',
  },
  headerTitle: {
    
    fontWeight: 'bold',
    color: 'black',
    textAlign:'center',
    textAlign: "center",
    fontFamily: 'sans-serif-medium',
    fontSize: 20,
    marginTop:5
  },

});

export default PredictOrder;
