import React from 'react';
import {
  Box,
  Button,
  Stack,
  Text,
  Spinner,
  RadioGroup,
  Radio,
  useToast,
  Alert,
  AlertIcon,
  VStack,
  HStack,
  Divider,
  Input,
  InputGroup,
  InputLeftElement,
  List,
  ListItem,
  Icon,
  Collapse,
  Badge
} from '@chakra-ui/react';
import { SearchIcon, ChevronDownIcon, ChevronRightIcon } from '@chakra-ui/icons';

const CategorySelector = ({ product, onCategorySelect }) => {
  const [suggestions, setSuggestions] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [selectedCategory, setSelectedCategory] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [activeTab, setActiveTab] = React.useState('suggestions');
  const [categories, setCategories] = React.useState([]);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [expandedCategories, setExpandedCategories] = React.useState([]);
  const [isCategoriesLoading, setIsCategoriesLoading] = React.useState(true);
  const toast = useToast();

  // Fetch all categories for manual selection
  const fetchCategories = async () => {
    setIsCategoriesLoading(true);
    try {
      const response = await fetch('/wp-json/wc/v3/products/categories', {
        headers: {
          'X-WP-Nonce': window.klcnnData.nonce,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch categories');
      }

      const data = await response.json();

      // Transform into hierarchical structure
      const categoriesMap = {};
      data.forEach(cat => {
        categoriesMap[cat.id] = {
          ...cat,
          children: []
        };
      });

      const hierarchicalCategories = [];
      data.forEach(cat => {
        if (cat.parent === 0) {
          hierarchicalCategories.push(categoriesMap[cat.id]);
        } else {
          categoriesMap[cat.parent]?.children.push(categoriesMap[cat.id]);
        }
      });

      setCategories(hierarchicalCategories);
    } catch (error) {
      toast({
        title: 'Error loading categories',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    } finally {
      setIsCategoriesLoading(false);
    }
  };

  React.useEffect(() => {
    if (activeTab === 'manual') {
      fetchCategories();
    }
  }, [activeTab]);

  const getSuggestions = async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('/wp-json/klcnn/v1/categories/decide', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': window.klcnnData.nonce
        },
        body: JSON.stringify({
          item: {
            title: product.name,
            description: product.description || '',
            manufacturer: product.manufacturer || ''
          },
          price: parseInt(product.price * 100)  // Price in cents
        })
      });

      if (!response.ok) {
        throw new Error('Failed to get category suggestions');
      }

      const data = await response.json();
      if (!data.success) {
        throw new Error(data.message || 'Failed to get category suggestions');
      }
      setSuggestions(data.data || []);
    } catch (error) {
      setError(error.message);
      toast({
        title: 'Error',
        description: error.message,
        status: 'error',
        duration: 3000
      });
    } finally {
      setIsLoading(false);
    }
  };

  const toggleCategory = (categoryId) => {
    setExpandedCategories(prev =>
      prev.includes(categoryId)
        ? prev.filter(id => id !== categoryId)
        : [...prev, categoryId]
    );
  };

  const renderCategory = (category) => {
    const isExpanded = expandedCategories.includes(category.id);
    const hasChildren = category.children && category.children.length > 0;
    const matchesSearch = searchQuery.toLowerCase() === '' ||
      category.name.toLowerCase().includes(searchQuery.toLowerCase());

    if (!matchesSearch && !hasChildren) return null;

    return (
      <Box key={category.id}>
        <ListItem
          py={2}
          px={2}
          cursor="pointer"
          _hover={{ bg: 'gray.50' }}
          onClick={() => {
            if (hasChildren) {
              toggleCategory(category.id);
            } else {
              setSelectedCategory(category.id);
              onCategorySelect(category.id);
            }
          }}
        >
          <HStack spacing={2}>
            {hasChildren ? (
              <Icon
                as={isExpanded ? ChevronDownIcon : ChevronRightIcon}
                w={4}
                h={4}
                onClick={(e) => {
                  e.stopPropagation();
                  toggleCategory(category.id);
                }}
              />
            ) : (
              <Box w={4} />
            )}
            <Text flex="1">{category.name}</Text>
            {category.count > 0 && (
              <Badge colorScheme="blue" rounded="full">
                {category.count}
              </Badge>
            )}
            {selectedCategory === category.id && (
              <Badge colorScheme="green">Selected</Badge>
            )}
          </HStack>
        </ListItem>
        {hasChildren && isExpanded && (
          <List pl={6}>
            {category.children.map(child => renderCategory(child))}
          </List>
        )}
      </Box>
    );
  };

  const filteredCategories = searchQuery
    ? categories.filter(cat =>
      cat.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      cat.children?.some(child =>
        child.name.toLowerCase().includes(searchQuery.toLowerCase())
      )
    )
    : categories;

  return (
    <Box>
      <HStack spacing={4} mb={6}>
        <Button
          flex="1"
          variant={activeTab === 'suggestions' ? 'solid' : 'outline'}
          colorScheme="blue"
          onClick={() => {
            setActiveTab('suggestions');
            setSuggestions([]); // Clear previous suggestions
            setError(null);
          }}
        >
          Automatic Suggestions
        </Button>
        <Button
          flex="1"
          variant={activeTab === 'manual' ? 'solid' : 'outline'}
          colorScheme="blue"
          onClick={() => setActiveTab('manual')}
        >
          Manual Selection
        </Button>
      </HStack>

      <Box mt={4}>
        {activeTab === 'suggestions' ? (
          // Suggestions View
          <VStack align="stretch" spacing={4}>
            <Text fontSize="lg">Suggested Categories</Text>
            {!suggestions.length && !isLoading && !error && (
              <Button
                onClick={getSuggestions}
                colorScheme="blue"
                isLoading={isLoading}
              >
                Get Suggestions
              </Button>
            )}

            {isLoading ? (
              <Spinner />
            ) : suggestions.length > 0 ? (
              <VStack align="stretch" spacing={4}>
                {suggestions.map(category => (
                  <Box
                    key={category.id_category}
                    p={3}
                    borderWidth={1}
                    borderRadius="md"
                    cursor="pointer"
                    bg={selectedCategory === category.id_category ? 'blue.50' : 'white'}
                    _hover={{ bg: 'gray.50' }}
                    onClick={() => {
                      if (selectedCategory === category.id_category) {
                        setSelectedCategory(null);
                        onCategorySelect(null);
                      } else {
                        setSelectedCategory(category.id_category);
                        onCategorySelect(category);
                      }
                    }}
                  >
                    <HStack justify="space-between">
                      <VStack align="start" spacing={1}>
                        <Text fontWeight="bold">{category.title_singular}</Text>
                        <Text fontSize="sm" color="gray.600">{category.name}</Text>
                      </VStack>
                      <HStack spacing={2}>
                        {category.variable_fee && (
                          <Badge colorScheme="blue">
                            Fee: {category.variable_fee}%
                          </Badge>
                        )}
                        {selectedCategory === category.id_category && (
                          <Badge colorScheme="green">Selected</Badge>
                        )}
                      </HStack>
                    </HStack>
                  </Box>
                ))}
              </VStack>
            ) : error ? (
              <Alert status="error">
                <AlertIcon />
                {error}
              </Alert>
            ) : null}
          </VStack>
        ) : (
          // Manual Selection View
          <VStack align="stretch" spacing={4}>
            <InputGroup>
              <InputLeftElement>
                <SearchIcon color="gray.400" />
              </InputLeftElement>
              <Input
                placeholder="Search categories..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </InputGroup>

            {isCategoriesLoading ? (
              <Spinner />
            ) : (
              <Box
                maxH="400px"
                overflowY="auto"
                borderWidth={1}
                borderRadius="md"
                p={2}
              >
                <List spacing={1}>
                  {filteredCategories.map(category => renderCategory(category))}
                </List>
              </Box>
            )}
          </VStack>
        )}
      </Box>
    </Box>
  );
};

export default CategorySelector;