import { createRoot } from '@wordpress/element';
import { useState, useEffect, useCallback } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { ChakraProvider, Spinner, Button, Box, Heading, VStack, Container } from '@chakra-ui/react';

import RuleForm from './components/rules/RuleForm';
import RulesTable from './components/rules/RulesTable';
import RuleEditor from './components/rules/RuleEditor';
import { useRules } from './hooks/useRules';
import theme from './theme';
import './index.scss';

const App = () => {
  const {
    rules,
    isLoading,
    error,
    createRule,
    updateRule,
    deleteRule,
    reloadRules,
  } = useRules();

  const [currentPage, setCurrentPage] = useState('list');
  const [editingRule, setEditingRule] = useState(null);

  const handleAddNew = useCallback(() => {
    setEditingRule(null);
    setCurrentPage('form');
  }, []);

  const handleEditRule = useCallback((rule) => {
    setEditingRule(rule);
    setCurrentPage('form');
  }, []);

  const handleSaveRule = useCallback(async (savedRule) => {
    setCurrentPage('list');
    setEditingRule(null);
    await reloadRules();
  }, [reloadRules]);

  if (isLoading) {
    return (
      <ChakraProvider theme={theme}>
        <VStack spacing={4} align="center" justify="center" h="100vh">
          <Spinner size="xl" color="primary.500" />
          <Box>Loading...</Box>
        </VStack>
      </ChakraProvider>
    );
  }

  if (error) {
    return (
      <ChakraProvider theme={theme}>
        <VStack spacing={4} align="center" justify="center" h="100vh">
          <Box color="accent.500">Error: {error}</Box>
          <Button onClick={reloadRules}>Retry</Button>
        </VStack>
      </ChakraProvider>
    );
  }

  if (currentPage === 'form') {
    return (
      <ChakraProvider theme={theme}>
        <Container maxW="container.xl" py={5}>
          <RuleForm
            rule={editingRule}
            onSave={handleSaveRule}
            onCancel={() => setCurrentPage('list')}
          />
        </Container>
      </ChakraProvider>
    );
  }

  return (
    <ChakraProvider theme={theme}>
      <Container maxW="container.xl" py={5}>
        <RulesTable
          rules={rules}
          onEdit={handleEditRule}
          onDelete={deleteRule}
        />
      </Container>
    </ChakraProvider>
  );
};

window.addEventListener('load', () => {
  const container = document.getElementById('discountlift-app');
  if (container) {
    const root = createRoot(container);
    root.render(<App />);
  }
});