import React from 'react';
import {
  Paper,
  Group,
  Title,
  ActionIcon,
  ScrollArea,
  Box,
  Divider,
} from '@mantine/core';
import { IconX } from '@tabler/icons-react';

export interface SidebarProps {
  opened: boolean;
  onClose: () => void;
  title: string;
  width?: number;
  position?: 'left' | 'right';
  headerActions?: React.ReactNode;
  footer?: React.ReactNode;
  children: React.ReactNode;
  
  // Styling customization
  zIndex?: number;
  offsetTop?: number;
  backgroundColor?: string;
  borderColor?: string;
  
  // Animation
  animationDuration?: string;
  
  // Accessibility
  'aria-label'?: string;
}

const Sidebar: React.FC<SidebarProps> = ({
  opened,
  onClose,
  title,
  width = 450,
  position = 'right',
  headerActions,
  footer,
  children,
  zIndex = 1000,
  offsetTop = 60,
  backgroundColor = 'var(--mantine-color-body)',
  borderColor = 'var(--mantine-color-gray-3)',
  animationDuration = '0.3s',
  'aria-label': ariaLabel,
}) => {
  // Calculate position styles based on position prop
  const getPositionStyles = () => {
    const baseStyles = {
      position: 'fixed' as const,
      top: offsetTop,
      bottom: 0,
      width: `${width}px`,
      zIndex,
      borderRadius: 0,
      display: 'flex',
      flexDirection: 'column' as const,
      backgroundColor,
      transition: `${position} ${animationDuration} ease`,
    };

    if (position === 'right') {
      return {
        ...baseStyles,
        right: opened ? 0 : `-${width}px`,
        borderLeft: `1px solid ${borderColor}`,
      };
    } else {
      return {
        ...baseStyles,
        left: opened ? 0 : `-${width}px`,
        borderRight: `1px solid ${borderColor}`,
      };
    }
  };

  return (
    <Paper
      style={getPositionStyles()}
      role="dialog"
      aria-modal="true"
      aria-label={ariaLabel || title}
      aria-hidden={!opened}
    >
      {/* Header */}
      <Group 
        justify="space-between" 
        p="md" 
        style={{ borderBottom: `1px solid ${borderColor}` }}
      >
        <Title order={4} style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {title}
        </Title>
        
        {/* Header actions (optional) */}
        {headerActions && (
          <Group gap="xs">
            {headerActions}
          </Group>
        )}
        
        {/* Close button */}
        <ActionIcon
          variant="subtle"
          color="gray"
          onClick={onClose}
          aria-label="Close sidebar"
          ml="xs"
        >
          <IconX size={18} />
        </ActionIcon>
      </Group>

      {/* Content */}
      <ScrollArea style={{ flex: 1 }} scrollbarSize={6}>
        <Box p="md">
          {children}
        </Box>
      </ScrollArea>

      {/* Footer (optional) */}
      {footer && (
        <>
          <Divider />
          <Box p="md" style={{ borderTop: `1px solid ${borderColor}` }}>
            {footer}
          </Box>
        </>
      )}
    </Paper>
  );
};

export default Sidebar;

// Higher-level convenience component that combines Sidebar with common form patterns
export interface FormSidebarWrapperProps extends Omit<SidebarProps, 'children'> {
  children: React.ReactNode;
  cancelLabel?: string;
  submitLabel?: string;
  onCancel?: () => void;
  onSubmit?: () => void;
  submitDisabled?: boolean;
  showFooterActions?: boolean;
}

export const FormSidebarWrapper: React.FC<FormSidebarWrapperProps> = ({
  children,
  cancelLabel = 'Cancel',
  submitLabel = 'Save',
  onCancel,
  onSubmit,
  submitDisabled = false,
  showFooterActions = true,
  onClose,
  ...sidebarProps
}) => {
  const handleCancel = () => {
    onCancel?.();
    onClose();
  };

  const footer = showFooterActions ? (
    <Group justify="flex-end" gap="sm">
      <ActionIcon
        variant="subtle"
        onClick={handleCancel}
        size="sm"
      >
        {cancelLabel}
      </ActionIcon>
      <ActionIcon
        onClick={onSubmit}
        disabled={submitDisabled}
        size="sm"
      >
        {submitLabel}
      </ActionIcon>
    </Group>
  ) : undefined;

  return (
    <Sidebar
      {...sidebarProps}
      onClose={onClose}
      footer={footer}
    >
      {children}
    </Sidebar>
  );
};

// Specialized sidebar variants for common use cases
export interface DetailsSidebarProps extends Omit<SidebarProps, 'title'> {
  itemName: string;
  itemType?: string;
  editButton?: React.ReactNode;
  deleteButton?: React.ReactNode;
  status?: React.ReactNode;
}

export const DetailsSidebar: React.FC<DetailsSidebarProps> = ({
  itemName,
  itemType = 'Item',
  editButton,
  deleteButton,
  status,
  children,
  ...sidebarProps
}) => {
  const headerActions = (
    <Group gap="xs">
      {status}
      {editButton}
      {deleteButton}
    </Group>
  );

  return (
    <Sidebar
      {...sidebarProps}
      title={`${itemType}: ${itemName}`}
      headerActions={headerActions}
    >
      {children}
    </Sidebar>
  );
};

// Quick sidebar for simple content display
export interface QuickSidebarProps extends Omit<SidebarProps, 'children'> {
  content: React.ReactNode;
  actions?: React.ReactNode;
}

export const QuickSidebar: React.FC<QuickSidebarProps> = ({
  content,
  actions,
  ...sidebarProps
}) => (
  <Sidebar {...sidebarProps} footer={actions}>
    {content}
  </Sidebar>
);

// Hooks for sidebar state management
export const useSidebar = (initialOpened = false) => {
  const [opened, setOpened] = React.useState(initialOpened);
  
  const open = React.useCallback(() => setOpened(true), []);
  const close = React.useCallback(() => setOpened(false), []);
  const toggle = React.useCallback(() => setOpened(prev => !prev), []);
  
  return {
    opened,
    open,
    close,
    toggle,
    setOpened,
  };
};