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 FilterDateView from '../../screens/class_schedule/filterday';
import * as ScreenName from "../ScreenNames";
import CustomDrawerContent from "./itemDrawer";
import R from "../../assets/R";
import FilterWeekView from "../../screens/class_schedule/filterWeek";
import Filter3Date from "../../screens/class_schedule/filter3day";

const Drawer = createDrawerNavigator();
const IconMenu = R.images.icMenu;
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}
    >
        <Image source={R.images.icBack} resizeMode="contain" style={{width: 20, height: 20}}/>
    </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}>
      <Image source={IconMenu} style={styles.icon} resizeMode="contain" tintColor={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}`;
      }
      if (route.name === ScreenName.FILTERMONTH) {
        return `Tháng ${currentDate.getMonth() + 1}`;
      }
 


      return '';
    };

    return (
      <TouchableOpacity style={styles.headerTitleButton}>
        <Text style={styles.headerTitleText}>
          {getHeaderTitle()}
        </Text>
        <Image source={R.images.icDrop} style={{width: 25, height: 20}} resizeMode="contain" tintColor={R.colors.white}/>
      </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}
              >
                <Image source={IconSearch} style={styles.iconSearch} resizeMode="contain" tintColor={R.colors.white}/>
              </TouchableOpacity>
              <View style={styles.avatarButton} />
            </View>
          ),

          headerStyle: {
            backgroundColor: R.colors.blue,
          },
        })}
      >
        <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={FilterDateView}
          options={{
            drawerItemStyle: { height: 0 },
          }}
        />
        <Drawer.Screen
          name={ScreenName.FILTERWEEK}
          component={FilterWeekView}
          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.gray}
              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.sizes.lg,
    color: R.colors.white,
    fontFamily: R.fonts.fontMedium,
    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.sizes.lg,
    color: R.colors.black,
    fontFamily: R.fonts.fontMedium,
    fontWeight: '600',
    marginBottom: 10,
  },
  searchInput: {
    height: 40,
    borderColor: R.colors.gray,
    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.sizes.md,
    color: R.colors.white,
    fontFamily: R.fonts.fontMedium,
  },
  searchButtonModal: {
    backgroundColor: R.colors.blue,
    borderRadius: 5,
    height:30,
    width:80,
    alignItems:'center',
    justifyContent:'center',
  },
  searchButtonText: {
    fontSize: R.sizes.md,
    color: R.colors.white,
    fontFamily: R.fonts.fontMedium,
  },
});

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