import { ChevronDown, ChevronUp } from 'lucide-react';
import { ReactNode, useState } from 'react';
import { Icon } from '@/ui/Icon';
import { Surface } from '@/ui/Surface';
import { Text } from '@/ui/Text';
import { Box } from '@/ui/Box';

export interface AccordionProps {
  title: string;
  children: ReactNode;
  defaultOpen?: boolean;
  isOpen?: boolean;
  onToggle?: () => void;
}

export const Accordion = ({ 
  title, 
  children, 
  defaultOpen = false,
  isOpen: controlledIsOpen,
  onToggle
}: AccordionProps) => {
  const [internalIsOpen, setInternalIsOpen] = useState(defaultOpen);
  
  const isControlled = controlledIsOpen !== undefined;
  const isOpen = isControlled ? controlledIsOpen : internalIsOpen;

  const handleToggle = () => {
    if (onToggle) {
      onToggle();
    }
    if (!isControlled) {
      setInternalIsOpen(!internalIsOpen);
    }
  };

  return (
    <Surface variant="muted" rounded="lg" style={{ border: '1px solid var(--ui-color-border-default)', overflow: 'hidden' }}>
      <Box
        as="button"
        onClick={handleToggle}
        fullWidth
        display="flex"
        alignItems="center"
        justifyContent="between"
        paddingX={4}
        paddingY={3}
        hoverBg="rgba(255,255,255,0.05)"
        transition
      >
        <Text weight="bold" size="sm" variant="high">
          {title}
        </Text>
        <Icon icon={isOpen ? ChevronUp : ChevronDown} size={4} intent="low" />
      </Box>
      
      {isOpen && (
        <Box padding={4} borderTop>
          {children}
        </Box>
      )}
    </Surface>
  );
};
