import {
  Box,
  VStack,
  HStack,
  Button,
  Card,
  CardBody,
  CardHeader,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  useToast,
  Grid,
  GridItem,
  Heading,
  Text,
  Badge,
  useDisclosure,
  AlertDialog,
  AlertDialogBody,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogContent,
  AlertDialogOverlay,
  useColorModeValue
} from '@chakra-ui/react';
import { useEffect, useRef, useState } from 'react';

import BasicDetails from './BasicDetails';
import ConditionSettings from './ConditionSettings';
import DiscountSettings from './DiscountSettings';
import MessageSettings from './MessageSettings';
import StyleSettings from './StyleSettings';
import Preview from './Preview';
import { useRuleForm } from '../RuleEditor/useRuleForm';

const RuleForm = ({ rule, onSave, onCancel }) => {
  const toast = useToast();
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [lastChangeTimestamp, setLastChangeTimestamp] = useState(Date.now());
  const { isOpen, onOpen, onClose } = useDisclosure();
  const cancelRef = useRef();

  const {
    formData,
    handleChange,
    handleStyleChange,
    handleSave,
    progressStyles,
    successStyles,
    isSaving
  } = useRuleForm(rule, (savedRule) => {
    // Only update form state if we have a successful save
    if (savedRule) {
      setHasUnsavedChanges(false);
      onSave(savedRule);
    }
  });

  const previewBg = useColorModeValue('gray.50', 'gray.700');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  // Handle form changes
  const handleFormChange = (...args) => {
    setHasUnsavedChanges(true);
    setLastChangeTimestamp(Date.now());
    handleChange(...args);
  };

  const handleStyleFormChange = (...args) => {
    setHasUnsavedChanges(true);
    setLastChangeTimestamp(Date.now());
    handleStyleChange(...args);
  };

  // Handle save
  const onSaveClick = async () => {
    if (isSaving) {
      return;
    }

    try {
      await handleSave();
      toast({
        title: "Rule saved successfully",
        status: "success",
        duration: 3000,
        isClosable: true,
      });
    } catch (error) {
      console.error('Error in form save handler:', error);
      toast({
        title: "Error saving rule",
        description: error.message || 'An unexpected error occurred',
        status: "error",
        duration: 5000,
        isClosable: true,
      });
    }
  };

  // Handle cancel with unsaved changes
  const handleCancelClick = () => {
    if (hasUnsavedChanges) {
      onOpen();
    } else {
      onCancel();
    }
  };

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        if (!isSaving && hasUnsavedChanges) {
          onSaveClick();
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isSaving, hasUnsavedChanges]);

  // Warn before leaving with unsaved changes
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      if (hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '';
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [hasUnsavedChanges]);

  return (
    <Box>
      <Grid templateColumns="3fr 2fr" gap={6}>
        <GridItem>
          <Card variant="outline" mb={5}>
            <CardBody>
              <Tabs>
                <TabList>
                  <Tab>Basic Details</Tab>
                  <Tab>Conditions</Tab>
                  <Tab>Discount</Tab>
                  <Tab>Message</Tab>
                  <Tab>Style</Tab>
                </TabList>

                <TabPanels>
                  <TabPanel>
                    <BasicDetails formData={formData} onChange={handleFormChange} />
                  </TabPanel>
                  <TabPanel>
                    <ConditionSettings formData={formData} onChange={handleFormChange} />
                  </TabPanel>
                  <TabPanel>
                    <DiscountSettings formData={formData} onChange={handleFormChange} />
                  </TabPanel>
                  <TabPanel>
                    <MessageSettings formData={formData} onChange={handleFormChange} />
                  </TabPanel>
                  <TabPanel>
                    <StyleSettings formData={{ progressStyles, successStyles }} onChange={handleStyleFormChange} />
                  </TabPanel>
                </TabPanels>
              </Tabs>
            </CardBody>
          </Card>

          <HStack spacing={4} justify="space-between">
            <Box>
              {hasUnsavedChanges && (
                <Badge colorScheme="yellow" variant="subtle">
                  Unsaved changes
                </Badge>
              )}
            </Box>
            <HStack spacing={4}>
              <Button
                variant="outline"
                onClick={handleCancelClick}
                isDisabled={isSaving}
              >
                Cancel
              </Button>
              <Button
                colorScheme="blue"
                onClick={onSaveClick}
                isLoading={isSaving}
                loadingText="Saving..."
                isDisabled={!hasUnsavedChanges || isSaving}
              >
                Save Rule
              </Button>
            </HStack>
          </HStack>
        </GridItem>

        <GridItem>
          <Card
            variant="outline"
            position="sticky"
            top={6}
            bg={previewBg}
            borderColor={borderColor}
            borderWidth="2px"
          >
            <CardHeader pb={0}>
              <HStack justify="space-between" align="center">
                <Heading size="sm">Live Preview</Heading>
                <Text fontSize="xs" color="gray.500">
                  Last updated: {new Date(lastChangeTimestamp).toLocaleTimeString()}
                </Text>
              </HStack>
            </CardHeader>
            <CardBody>
              <Preview
                formData={formData}
                progressStyles={progressStyles}
                successStyles={successStyles}
              />
            </CardBody>
          </Card>
        </GridItem>
      </Grid>

      <AlertDialog
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent>
            <AlertDialogHeader fontSize="lg" fontWeight="bold">
              Discard Changes?
            </AlertDialogHeader>

            <AlertDialogBody>
              You have unsaved changes. Are you sure you want to discard them?
            </AlertDialogBody>

            <AlertDialogFooter>
              <Button ref={cancelRef} onClick={onClose}>
                Continue Editing
              </Button>
              <Button colorScheme="red" onClick={onCancel} ml={3}>
                Discard Changes
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialog>
    </Box>
  );
};

export default RuleForm;