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:5000predict_growth_monitoring';
const endMyPoint = '/predict_growth_monitoring';

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

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

const LeafColors = [
  "bright_yellow",
  "bright_yellow_to_lime_green",
  "lime_green_with_yellow_undertones",
  "variegated_patterns",
  "yellowish_green"
]
const HeaderComponent = ({ onBack }) => {
  return (
    <View style={styles.headerContainer}>
      <TouchableOpacity onPress={onBack}>
        <Text style={styles.backButton}>←</Text>
      </TouchableOpacity>
      <Text style={styles.headerTitle}>Monitor the plant's Growth</Text>
    </View>
  );
};
const MonitorGrowth = () => {
  const [plantType, setPlantType] = useState('');
  const [plantVariety, setPlantVariety] = useState('');
  const [characterLeaves, setCharacterLeaves] = useState('');
  const [averageCurrentHeight, setAverageCurrentHeight] = useState('');
  const [noOfBranches, setNoOfBranches] = useState('');
  const [plantedDate, setPlantedDate] = useState('');
  const [checkedDate, setCheckedDate] = useState('');
  const [currentLeafColour, setCurrentLeafColour] = useState('');
  const [containerSize, setContainerSize] = useState('');
  const [dominantBranch, setDominantBranch] = useState('');
  const [focusedInput, setFocusedInput] = useState('');
  const [showPredictionWidget, setShowPredictionWidget] = useState(false);
  const [predictedType, setPredictedType] = useState('');
  const [predictionError, setPredictionError] = useState('');
  const [characterLeavesError, setCharacterLeavesError] = useState('');
  const [averageCurrentHeightError, setAverageCurrentHeightError] = useState('');
  const [noOfBranchesError, setNoOfBranchesError] = useState('');
  const [plantedDateError, setPlantedDateError] = useState('');
  const [checkedDateError, setCheckedDateError] = useState('');


  const isValidDate = (date) => {
    // Regular expression to validate date in 'YYYY-MM-DD' format
    const regex = /^\d{4}-\d{2}-\d{2}$/;
    if (!regex.test(date)) return false;
    
    const d = new Date(date);
    const dNum = d.getTime();
    if(!dNum && dNum !== 0) return false; // NaN value, Invalid date
  
    return d.toISOString().slice(0,10) === date;
  }

  const validateCharacterLeaves = (value) => {
    if (isNaN(value) || value > 50 || value.includes('.')) {
      setCharacterLeavesError('Leaves must be a number not exceeding 50 and not a decimal.');
      return false;
    }
    setCharacterLeavesError('');
    return true;
  };

  const validateAverageCurrentHeight = (value) => {
    if (isNaN(value) || value > 50) {
      setAverageCurrentHeightError('Height should not exceed 50cm.');
      return false;
    }
    setAverageCurrentHeightError('');
    return true;
  };

  const validateNoOfBranches = (value) => {
    if (isNaN(value) || value > 10 || value.includes('.')) {
      setNoOfBranchesError('Branches should be a number not exceeding 10 and not a decimal.');
      return false;
    }
    setNoOfBranchesError('');
    return true;
  };


  const validatePlantedDate = (value) => {
    if (!isValidDate(value)) {
      setPlantedDateError('Date should be in format YYYY-MM-DD.');
      return false;
    } else {
      setPlantedDateError('');
      return true;
    }
  }
  
  const validateCheckedDate = (value) => {
    if (!isValidDate(value)) {
      setCheckedDateError('Date should be in format YYYY-MM-DD.');
      return false;
    } else {
      setCheckedDateError('');
      return true;
    }
  }
  // const validateLeafColour = (currentLeafColour) => {
  //   if (!currentLeafColour || currentLeafColour === 'default') {
  //     showErrorToast('Invalid Leaf Colour', 'Please select a  leaf colour');
  //     return false;
  //   }
  //   return true;
  // };

  // const validateContainerSize = (containerSize) => {
  //   if (!containerSize || containerSize === 'default') {
  //     showErrorToast('Invalid Container Size', 'Please select a container size');
  //     return false;
  //   }
  //   return true;
  // };

  // const validateDominantBranch = (dominantBranch) => {
  //   if (!dominantBranch || dominantBranch === 'default') {
  //     showErrorToast('Invalid Dominant Branch', 'Please select a dominant branch');
  //     return false;
  //   }
  //   return true;
  // };



  const isFormComplete = () => {
    return (
      plantType &&
      plantVariety &&
      characterLeaves &&
      averageCurrentHeight &&
      noOfBranches &&
      plantedDate &&
      checkedDate &&
      currentLeafColour &&
      containerSize &&
      dominantBranch
    );
  };


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




    try {
      // Parsing the data as per backend requirements
      const postData = {
        character_leaves: parseInt(characterLeaves, 10),
        average_current_height: parseFloat(averageCurrentHeight),
        no_of_branches: parseInt(noOfBranches, 10),
        planted_date: plantedDate,
        checked_date: checkedDate,
        current_leaf_colour: currentLeafColour,
        container_size: containerSize,
        dominant_branch: dominantBranch
      };
      // 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 Growth Category']) {
          setPredictedType(response.data['Predicted Growth Category']);
          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}>Character Leaves:</Text>

        <TextInput
          value={characterLeaves}
          onChangeText={(value) => {
            setCharacterLeaves(value);
            validateCharacterLeaves(value);
          }}
          style={[
            styles.input,
            focusedInput === 'characterLeaves' ? styles.inputFocused : {},
            characterLeavesError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="No of character leaves visible"
          onFocus={() => setFocusedInput('characterLeaves')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{characterLeavesError}</Text>


        


        <Text style={styles.inputTitle}>Average Current Height:</Text>
        
        <TextInput
          value={averageCurrentHeight}
          onChangeText={(value) => {
            setAverageCurrentHeight(value);
            validateAverageCurrentHeight(value);
          }}
          style={[
            styles.input,
            focusedInput === 'averageCurrentHeight' ? styles.inputFocused : {},
            averageCurrentHeightError ? styles.errorInput : {}
          ]}
          keyboardType="decimal-pad"
          placeholder="in centimeter"
          onFocus={() => setFocusedInput('averageCurrentHeight')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{averageCurrentHeightError}</Text>

        <Text style={styles.inputTitle}>No of Branches:</Text>

        <TextInput
          value={noOfBranches}
          onChangeText={(value) => {
            setNoOfBranches(value);
            validateNoOfBranches(value);
          }}
          style={[
            styles.input,
            focusedInput === 'noOfBranches' ? styles.inputFocused : {},
            noOfBranchesError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="No of branches can be seen"
          onFocus={() => setFocusedInput('noOfBranches')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{noOfBranchesError}</Text>

      </View>
      <View style={styles.formContainer}>
        <Text style={styles.inputTitle}>Planted Date:</Text>
        <TextInput
          value={plantedDate}
          onChangeText={(value) => {
            setPlantedDate(value);
            validatePlantedDate(value);
          }}
          style={[
            styles.input,
            focusedInput === 'plantedDate' ? styles.inputFocused : {},
            plantedDateError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="YYYY-MM-DD"
          onFocus={() => setFocusedInput('plantedDate')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{plantedDateError}</Text>
        
        <Text style={styles.inputTitle}>Checked Date:</Text>

        <TextInput
          value={checkedDate}
          onChangeText={(value) => {
            setCheckedDate(value);
            validateCheckedDate(value);
          }}
          style={[
            styles.input,
            focusedInput === 'checkedDate' ? styles.inputFocused : {},
            checkedDateError ? styles.errorInput : {}
          ]}
          keyboardType="numeric"
          placeholder="YYYY-MM-DD"
          onFocus={() => setFocusedInput('checkedDate')}
          onBlur={() => setFocusedInput('')}
        />
        <Text style={styles.errorMessage}>{checkedDateError}</Text>
       
        <Text style={styles.inputTitle}>Select the current leaf color:</Text>
        <Picker style={styles.pickerContainer}
          selectedValue={currentLeafColour}
          onValueChange={value => setCurrentLeafColour(value)}
        // style={styles.picker}
        >
          <Picker.Item label="Select the current leaf color" value="" color="#999" />
          {LeafColors.map(color => (
            <Picker.Item key={color} label={color} value={color} />
          ))}
        </Picker>
        {/* Radio buttons for Container Size */}
        <Text style={styles.inputTitle}>Visible Container Size:</Text>
        <RadioForm
          radio_props={[
            { label: 'Full not crowded', value: 'full_not_crowded' },
            { label: 'Full crowded', value: 'full_crowded' }
          ]}
          onPress={(value) => setContainerSize(value)}
          buttonColor={'darkgreen'}
          selectedButtonColor={'darkgreen'}
        />

        <Text style={styles.inputTitle}>Can you see a dominant Branch:</Text>
        {/* Radio buttons for Dominant Branch */}
        <RadioForm
          radio_props={[
            { label: 'Yes', value: 'yes' },
            { label: 'No', value: 'no' }
          ]}
          onPress={(value) => setDominantBranch(value)}
          buttonColor={'darkgreen'}
          selectedButtonColor={'darkgreen'}
        />


        <TouchableOpacity
          style={[styles.button, !isFormComplete() && styles.buttonDisabled]}
          onPress={handleGrowthMonitoring}
          
          disabled={!isFormComplete()}
        >
          <Text style={styles.buttonText}>Predict Current Growth State</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 is currently : {predictedType}</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: '#f5fffa',
  },
  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 MonitorGrowth;
