import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Image,
  Dimensions,
  ListRenderItem,
  Platform,
  StatusBar,
  SafeAreaView,
  ActivityIndicator
} from 'react-native';
import fontSize from '../utils/fontsizeUtils';
import widthUtils from '../utils/widthUtils';
import { categoriesApi, Category } from '../services/api/categories';

export const CategoryScreen = () => {
  const [mainCategories, setMainCategories] = useState<Category[]>([]);
  const [subCategories, setSubCategories] = useState<Category[]>([]);
  const [activeMainCategory, setActiveMainCategory] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [subLoading, setSubLoading] = useState(false);

  useEffect(() => {
    fetchMainCategories();
  }, []);

  useEffect(() => {
    if (activeMainCategory) {
      fetchSubCategories(activeMainCategory);
    }
  }, [activeMainCategory]);

  const fetchMainCategories = async () => {
    try {
      const response = await categoriesApi.getCategories();
      setMainCategories(response);
      if (response.length > 0) {
        setActiveMainCategory(response[0].category_id);
      }
    } catch (error) {
      console.error('Error fetching main categories:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchSubCategories = async (parentId: number) => {
    setSubLoading(true);
    try {
      const response = await categoriesApi.getCategory(parentId);
      if (Array.isArray(response)) {
        setSubCategories(response);
      }
    } catch (error) {
      console.error('Error fetching sub categories:', error);
    } finally {
      setSubLoading(false);
    }
  };

  const renderMainCategoryItem: ListRenderItem<Category> = ({ item }) => (
    <TouchableOpacity
      style={[
        styles.menuItem,
        item.category_id === activeMainCategory && styles.menuItemActive,
      ]}
      onPress={() => setActiveMainCategory(item.category_id)}
    >
      <Text
        style={[
          styles.menuText,
          item.category_id === activeMainCategory && styles.menuTextActive,
        ]}
        numberOfLines={1}
        ellipsizeMode="tail"
      >
        {item.name_cn}
      </Text>
    </TouchableOpacity>
  );

  const renderSubCategoryItem: ListRenderItem<Category> = ({ item }) => (
    <TouchableOpacity
      style={[
        styles.menuItem,
      ]}
      onPress={() => {}}
    >
      <Text
        style={styles.menuText}
        numberOfLines={1}
        ellipsizeMode="tail"
      >
        {item.name_cn}
      </Text>
    </TouchableOpacity>
  );

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#e60012" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      <View style={styles.safeAreaContent}>
        <View style={styles.container}>
          <View style={styles.leftMenu}>
            <FlatList
              data={mainCategories}
              renderItem={renderMainCategoryItem}
              keyExtractor={(item) => item.category_id.toString()}
            />
          </View>
          <View style={styles.rightContent}>
            {subLoading ? (
              <View style={styles.loadingContainer}>
                <ActivityIndicator size="large" color="#e60012" />
              </View>
            ) : (
              <FlatList
                data={subCategories}
                renderItem={renderSubCategoryItem}
                keyExtractor={(item) => item.category_id.toString()}
                numColumns={3}
                contentContainerStyle={styles.productGrid}
              />
            )}
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#fff',
  },
  safeAreaContent: {
    flex: 1,
    paddingTop: Platform.OS === 'android' ? 0 : 0,
  },
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  leftMenu: {
    width: widthUtils(100,100).width,
    backgroundColor: '#fff',
    borderRightWidth: 1,
    borderColor: '#eee',
  },
  menuItem: {
    paddingVertical: 16,
    alignItems: 'center',
    borderBottomWidth: 1,
    borderColor: '#f0f0f0',
  },
  menuItemActive: {
    backgroundColor: '#f5f5f5',
  },
  menuText: {
    fontSize: fontSize(14),
    color: '#333',
  },
  menuTextActive: {
    color: '#e60012',
    fontWeight: 'bold',
  },
  rightContent: {
    flex: 1,
    backgroundColor: '#f8f8f8',
    paddingHorizontal: 10,
    paddingTop: 12,
  },
  productGrid: {
    paddingBottom: 20,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});
