import {
  Box,
  Text,
  Input,
  InputGroup,
  InputLeftElement,
  Stack,
  HStack,
  SimpleGrid,
  useColorModeValue,
  Badge,
  Card,
  CardBody,
  Flex,
  Button,
  IconButton,
  Divider,
  VStack,
  Wrap,
  WrapItem,
  Tooltip,
  Container,
  Table,
} from '@chakra-ui/react';
import { useState, useMemo } from '@wordpress/element';
import { SearchIcon, EditIcon, DeleteIcon, AddIcon } from '@chakra-ui/icons';
import { formatCondition, formatDiscount } from '../../../utils/formatters';
import ShortcodeCell from './ShortcodeCell';

const RuleCard = ({ rule, onEdit, onDelete }) => {
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = 'hsla(210, 93%, 29%, 0.1)';
  const titleColor = 'hsla(210, 93%, 29%, 1)';
  const accentColor = 'hsla(173, 80%, 40%, 1)';

  const getConditionBadgeColor = (type) => {
    return type === 'cart_total' ? 'green' : 'purple';
  };

  const getDiscountBadgeColor = (type) => {
    return type === 'percentage' ? 'hsla(173, 80%, 40%, 1)' : 'hsla(29, 100%, 47%, 1)';
  };

  return (
    <Card
      bg={cardBg}
      borderWidth="1px"
      borderColor={borderColor}
      borderRadius="xl"
      overflow="hidden"
      transition="all 0.2s"
      position="relative"
      _hover={{
        shadow: '2xl',
        borderColor: accentColor,
        transform: 'translateY(-2px)',
      }}
    >
      <Box position="absolute" top={0} left={0} right={0} height="4px" bg={accentColor} />

      <CardBody p={6}>
        <VStack spacing={6} align="stretch">
          {/* Header */}
          <Flex justify="space-between" align="start" gap={4}>
            <VStack align="start" spacing={3} flex={1}>
              <Text
                fontSize="xl"
                fontWeight="bold"
                color={titleColor}
                letterSpacing="tight"
                lineHeight="short"
              >
                {rule.title.rendered}
              </Text>
              <HStack spacing={3}>
                <Badge
                  px={3}
                  py={1}
                  borderRadius="full"
                  colorScheme="green"
                  fontSize="sm"
                  textTransform="none"
                  fontWeight="medium"
                >
                  {formatCondition(rule.meta.dlift_condition_type, rule.meta.dlift_condition_value)}
                </Badge>
                <Badge
                  px={3}
                  py={1}
                  borderRadius="full"
                  bg={getDiscountBadgeColor(rule.meta.dlift_discount_type)}
                  color="white"
                  fontSize="sm"
                  textTransform="none"
                  fontWeight="medium"
                >
                  {formatDiscount(rule.meta.dlift_discount_type, rule.meta.dlift_discount_value)}
                </Badge>
              </HStack>
            </VStack>

            <HStack spacing={2} position="relative" top="-8px" right="-8px">
              <Tooltip label="Edit Rule" hasArrow placement="top">
                <IconButton
                  icon={<EditIcon />}
                  variant="ghost"
                  color={accentColor}
                  size="sm"
                  onClick={() => onEdit(rule)}
                  aria-label="Edit rule"
                  _hover={{ bg: 'hsla(173, 80%, 40%, 0.1)' }}
                />
              </Tooltip>
              <Tooltip label="Delete Rule" hasArrow placement="top">
                <IconButton
                  icon={<DeleteIcon />}
                  variant="ghost"
                  color="red.400"
                  size="sm"
                  onClick={() => onDelete(rule.id)}
                  aria-label="Delete rule"
                  _hover={{ bg: 'red.50' }}
                />
              </Tooltip>
            </HStack>
          </Flex>

          {/* Message */}
          <Box
            bg="gray.50"
            p={4}
            borderRadius="lg"
            _dark={{ bg: 'gray.700' }}
          >
            <Text fontSize="sm" color="gray.500" mb={1} fontWeight="medium">
              Progress Message
            </Text>
            <Text fontSize="sm" color="gray.700" noOfLines={2}>
              {rule.meta.dlift_progress_message || 'No message set'}
            </Text>
          </Box>

          {/* Shortcode */}
          <Box>
            <Text
              fontSize="sm"
              color="gray.500"
              mb={2}
              fontWeight="medium"
            >
              Shortcode
            </Text>
            <ShortcodeCell ruleId={rule.id} />
          </Box>
        </VStack>
      </CardBody>
    </Card>
  );
};

const RulesTable = ({ rules, onEdit, onDelete }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filterBy, setFilterBy] = useState('all');

  // Modern color scheme
  const containerBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.100', 'gray.700');
  const headerBg = 'hsla(210, 93%, 29%, 1)'; // polynesian-blue
  const statBg = 'hsla(173, 80%, 40%, 0.15)'; // keppel with transparency
  const statText = 'hsla(173, 80%, 40%, 1)'; // keppel
  const addButtonBg = 'hsla(29, 100%, 47%, 1)'; // safety-orange
  const searchBg = 'hsla(39, 61%, 65%, 0.1)'; // ecru with transparency

  const filteredRules = useMemo(() => {
    if (!rules) return [];
    return rules.filter(rule => {
      const matchesSearch = rule.title.rendered.toLowerCase().includes(searchQuery.toLowerCase()) ||
        rule.meta.dlift_condition_type.toLowerCase().includes(searchQuery.toLowerCase()) ||
        rule.meta.dlift_discount_type.toLowerCase().includes(searchQuery.toLowerCase());

      if (filterBy === 'all') return matchesSearch;
      if (filterBy === 'cart_total') return matchesSearch && rule.meta.dlift_condition_type === 'cart_total';
      return matchesSearch;
    });
  }, [rules, searchQuery, filterBy]);

  if (!rules || rules.length === 0) {
    return (
      <Container maxW="7xl" p={0}>
        <Box
          bg={containerBg}
          borderWidth="1px"
          borderColor={borderColor}
          borderRadius="2xl"
          overflow="hidden"
          boxShadow="xl"
        >
          <Box bg={headerBg} px={8} py={6}>
            <Text fontSize="2xl" fontWeight="bold" color="white">
              Discount Rules
            </Text>
          </Box>
          <Box p={8} textAlign="center">
            <VStack spacing={4}>
              <Text fontSize="lg" color="gray.500">
                No rules found. Click 'Add New' to create one.
              </Text>
              <Button
                leftIcon={<AddIcon />}
                colorScheme="blue"
                size="lg"
                onClick={() => onEdit()}
              >
                Create Your First Rule
              </Button>
            </VStack>
          </Box>
        </Box>
      </Container>
    );
  }

  return (
    <Container maxW="7xl" p={0}>
      <Box
        bg={containerBg}
        borderWidth="1px"
        borderColor="hsla(210, 93%, 29%, 0.2)"
        borderRadius="2xl"
        overflow="hidden"
        boxShadow="lg"
      >
        {/* Modern Header with Stats */}
        <Box
          bg={headerBg}
          px={6}
          py={4}
          position="relative"
          overflow="hidden"
        >
          <Flex
            justify="space-between"
            align="center"
            gap={4}
            direction="row"
            position="relative"
          >
            {/* Left section with title */}
            <VStack align="start" spacing={0} flex={1}>
              <Text
                fontSize="xl"
                fontWeight="bold"
                color="white"
                letterSpacing="tight"
                lineHeight="1"
              >
                Discount Rules
              </Text>
              <Text
                fontSize="sm"
                color="whiteAlpha.800"
                fontWeight="medium"
              >
                Cart total based discount management
              </Text>
            </VStack>

            {/* Center logo */}

            {/* Right section with stats and button */}
            <HStack spacing={3} align="center" flex={1} justify="flex-end">
              <Box
                bg="whiteAlpha.200"
                px={4}
                py={2}
                h="36px"
                borderRadius="lg"
                backdropFilter="blur(8px)"
                border="1px solid"
                borderColor="whiteAlpha.300"
                display="flex"
                alignItems="center"
              >
                <HStack spacing={2} align="center">
                  <Text fontSize="sm" color="whiteAlpha.800">Total Rules</Text>
                  <Text fontSize="sm" fontWeight="bold" color="white">
                    {filteredRules.length}
                  </Text>
                </HStack>
              </Box>
              <Button
                leftIcon={<AddIcon boxSize={3.5} />}
                bg={addButtonBg}
                color="white"
                h="36px"
                px={4}
                fontSize="sm"
                fontWeight="semibold"
                borderRadius="lg"
                _hover={{
                  bg: 'hsla(29, 100%, 42%, 1)',
                  transform: 'translateY(-1px)',
                  shadow: 'md'
                }}
                _active={{
                  transform: 'translateY(0)',
                  bg: 'hsla(29, 100%, 37%, 1)'
                }}
                transition="all 0.2s"
                onClick={() => onEdit()}
              >
                Add New Rule
              </Button>
            </HStack>
          </Flex>
        </Box>

        {/* Search Bar with Modern Design */}
        <Box px={8} py={5} bg={searchBg}>
          <InputGroup maxW="md">
            <InputLeftElement pointerEvents="none">
              <SearchIcon color="hsla(210, 93%, 29%, 0.6)" />
            </InputLeftElement>
            <Input
              placeholder="Search rules..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              bg="white"
              _dark={{ bg: 'gray.800' }}
              borderColor="hsla(210, 93%, 29%, 0.2)"
              _hover={{ borderColor: 'hsla(173, 80%, 40%, 0.5)' }}
              _focus={{
                borderColor: 'hsla(173, 80%, 40%, 1)',
                boxShadow: '0 0 0 1px hsla(173, 80%, 40%, 0.5)'
              }}
              fontSize="md"
              size="lg"
            />
          </InputGroup>
        </Box>

        {/* Add wrapper div for scrolling */}
        <Box className="wp-list-table-wrapper">
          {/* Rules Grid */}
          <Box p={8}>
            <SimpleGrid columns={{ base: 1, lg: 2 }} spacing={6}>
              {filteredRules.map(rule => (
                <RuleCard
                  key={rule.id}
                  rule={rule}
                  onEdit={() => onEdit(rule)}
                  onDelete={() => onDelete(rule.id)}
                />
              ))}
            </SimpleGrid>
          </Box>
        </Box>
      </Box>
    </Container>
  );
};

export default RulesTable;