import React, { useEffect, useState } from "react";
import {
  DeviceEventEmitter,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Modal,
  TextInput,
  Alert,
} from "react-native";
import {
  createDrawerNavigator,
} from "@react-navigation/drawer";
import { connect } from "react-redux";
import ClassSchedule from "../../screens/class_schedule";
import FilterDate from '../../screens/class_schedule/filter_date';
import * as ScreenName from "../ScreenNames";
import CustomDrawerContent from "./itemDrawer";
import R from "../../assets/R";
import FilterWeek from "../../screens/class_schedule/filter_week";
import Filter3Date from "../../screens/class_schedule/filter_3_date";

const Drawer = createDrawerNavigator();
const IconMenu = R.images.icMenu;
const ArrowLeft = R.images.icBack;
const IconSearch = R.images.icSearch;

const DrawerNavigatorView = (props) => {
  const [reload, setReload] = useState(false);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [searchModalVisible, setSearchModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');

  const HeaderBackButton = ({ onPress, canGoBack }) => (
    <TouchableOpacity
      style={styles.headerBackButton}
      onPress={onPress}
    >
      <ArrowLeft fill={'white'}/>
    </TouchableOpacity>
  );

  useEffect(() => {
    const setLanguageListener = DeviceEventEmitter.addListener(
      "setLanguage",
      (value) => {
        setReload((prev) => !prev);
      }
    );

    const dateChangeListener = DeviceEventEmitter.addListener(
      "onDateChange",
      (date) => {
        setCurrentDate(new Date(date));
      }
    );

    const updateHeaderMonthListener = DeviceEventEmitter.addListener(
      "updateHeaderMonth",
      (monthIndex) => {
        const newDate = new Date(currentDate);
        newDate.setMonth(monthIndex);
        setCurrentDate(newDate);
      }
    );

    return () => {
      setLanguageListener.remove();
      dateChangeListener.remove();
      updateHeaderMonthListener.remove();
    };
  }, [currentDate]);

  const MenuButton = ({ onPress }) => (
    <TouchableOpacity style={styles.menuButton} onPress={onPress}>
      <IconMenu width={24} height={24} stroke={R.colors.white}/>
    </TouchableOpacity>
  );

  const HeaderTitle = ({ navigation, route }) => {
    const getHeaderTitle = () => {
      if (route.name === ScreenName.FILTERDATE) {
        return `Tháng ${currentDate.getMonth() + 1}`;
      }
        if (route.name === ScreenName.FILTER3DATE) {
        return `Tháng ${currentDate.getMonth() + 1}`;
      }
        if (route.name === ScreenName.FILTERWEEK) {
        return `Tháng ${currentDate.getMonth() + 1}`;
      }
      
 


      return '';
    };

    return (
      <TouchableOpacity style={styles.headerTitleButton}>
        <Text style={styles.headerTitleText}>
          {getHeaderTitle()}
        </Text>
      </TouchableOpacity>
    );
  };

  const handleSearchPress = () => {
    setSearchModalVisible(true);
  };

  const handleSearchSubmit = () => {
    if (searchText.trim()) {
      // Emit event để các screen khác có thể lắng nghe và xử lý tìm kiếm
      DeviceEventEmitter.emit('onScheduleSearch', { 
        searchText: searchText.trim(),
        currentScreen: 'schedule'
      });
      
      setSearchModalVisible(false);
      setSearchText('');
      
      Alert.alert('Tìm kiếm', `Đang tìm kiếm: "${searchText.trim()}"`);
    } else {
      Alert.alert('Thông báo', 'Vui lòng nhập từ khóa tìm kiếm');
    }
  };

  const handleSearchCancel = () => {
    setSearchModalVisible(false);
    setSearchText('');
  };

  return (
    <>
      <Drawer.Navigator
        drawerContent={(drawerProps) => <CustomDrawerContent {...drawerProps} />}
        initialRouteName={ScreenName.FILTERMONTH}
        screenOptions={({ navigation, route }) => ({
          headerLeft: () => (
            <View style={styles.headerLeftContainer}>
              <HeaderBackButton
                onPress={() => {
                  if (navigation.canGoBack()) {
                    navigation.pop();
                  } else {
                    navigation.toggleDrawer();
                  }
                }}
                canGoBack={navigation.canGoBack()}
              />
              <MenuButton
                onPress={() => {
                  navigation.toggleDrawer();
                }}
              />
            </View>
          ),

          headerTitle: () => (
            <View style={styles.headerTitleContainer}>
              <HeaderTitle navigation={navigation} route={route} />
            </View>
          ),

          headerRight: () => (
            <View style={styles.headerRightContainer}>
              <TouchableOpacity 
                style={styles.searchButton}
                onPress={handleSearchPress}
              >
                <IconSearch stroke={R.colors.white} width={24} height={24} />
              </TouchableOpacity>
              <View style={styles.avatarButton} />
            </View>
          ),

          headerStyle: {
            backgroundColor: R.colors.main,
          },
        })}
      >
        <Drawer.Screen
          name={ScreenName.FILTERMONTH} 
          component={ClassSchedule}
          options={{
            drawerLabel: () => null,
            drawerIcon: () => null,
            drawerItemStyle: { height: 0 },
          }}
        />
        <Drawer.Screen
          name={ScreenName.FILTER3DATE}
          component={Filter3Date}
          options={{
            drawerLabel: () => null,
            drawerIcon: () => null,
            drawerItemStyle: { height: 0 },
          }}
        />
        <Drawer.Screen
          name={ScreenName.FILTERDATE}
          component={FilterDate}
          options={{
            drawerItemStyle: { height: 0 },
          }}
        />
        <Drawer.Screen
          name={ScreenName.FILTERWEEK}
          component={FilterWeek}
          options={{
            drawerItemStyle: { height: 0 },
          }}
        />
      </Drawer.Navigator>

      {/* Search Modal */}
      <Modal
        visible={searchModalVisible}
        transparent={true}
        animationType="fade"
        onRequestClose={handleSearchCancel}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Tìm kiếm lịch</Text>
            
            <TextInput
              style={styles.searchInput}
              value={searchText}
              onChangeText={setSearchText}
              placeholder="Nhập từ khóa tìm kiếm..."
              placeholderTextColor={R.colors.gray150}
              autoFocus={true}
              returnKeyType="search"
              onSubmitEditing={handleSearchSubmit}
            />
            
            <View style={styles.modalButtonContainer}>
              <TouchableOpacity 
                style={styles.cancelButton} 
                onPress={handleSearchCancel}
              >
                <Text style={styles.cancelButtonText}>Hủy</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                style={styles.searchButtonModal} 
                onPress={handleSearchSubmit}
              >
                <Text style={styles.searchButtonText}>Tìm kiếm</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </>
  );
};

const mapStateToProps = (state) => ({
  user: state.userReducer,
});

const styles = StyleSheet.create({
  headerBackButton: {
    marginLeft:15
  },
  menuButton: {
    marginLeft: 15,
    
  },
  headerLeftContainer: {
    flexDirection: "row",
    alignItems: "center",
  },
  headerRightContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginRight: 15,
  },
  searchButton: {
    padding: 10,
    marginRight: 10,
  },
  avatarButton: {
    width: 25,
    height: 25,
    borderRadius: 30,
    backgroundColor: R.colors.white,
  },
  headerTitleButton: {
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
  },
  headerTitleText: {
    fontSize: R.fontsize.fontsSize14,
    color: R.colors.white,
    fontFamily: R.fonts.InterMedium,
    fontWeight: '600',
  },
  headerTitleContainer: {
    flexDirection: 'row',
  },
  icon: {
    width: 20,
    height: 20,
  },
  iconSearch: {
    width: 20,
    height: 20,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: R.colors.white,
    borderRadius: 10,
    padding: 20,
    width: '80%',
  },
  modalTitle: {
    fontSize: R.fontsize.fontsSize12,
    color: R.colors.black,
    fontFamily: R.fonts.InterMedium,
    fontWeight: '600',
    marginBottom: 10,
  },
  searchInput: {
    height: 40,
    borderColor: R.colors.gray150,
    borderWidth: 1,
    paddingHorizontal: 10,
    paddingVertical: 5,
    marginBottom: 10,
  },
  modalButtonContainer: {
    flexDirection: 'row',
    justifyContent:'flex-end'
  },
  cancelButton: {
    backgroundColor: R.colors.orange,
    borderRadius: 5,
    marginRight: 10,
    height:30,
    width:80,
    alignItems:'center',
    justifyContent:'center',
  },
  cancelButtonText: {
    fontSize: R.fontsize.fontsSize12,
    color: R.colors.white,
    fontFamily: R.fonts.InterMedium,
  },
  searchButtonModal: {
    backgroundColor: R.colors.main,
    borderRadius: 5,
    height:30,
    width:80,
    alignItems:'center',
    justifyContent:'center',
  },
  searchButtonText: {
    fontSize: R.fontsize.fontsSize12,
    color: R.colors.white,
    fontFamily: R.fonts.InterMedium
  },
});

export default connect(mapStateToProps, {})(DrawerNavigatorView);