import React from 'react';
import Box from '@mui/material/Box';
import Dialog from '@mui/material/Dialog';
import type { DialogProps } from '@mui/material/Dialog';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import type { SxProps, Theme } from '@mui/material/styles';
import { Typography } from '../Typography';
import { Divider } from '../Divider';

// ─── Types ───────────────────────────────────────────────────────────────────

/** Props for the DialogShell atom */
export interface DialogShellProps {
  /** Whether the dialog is open */
  open: boolean;
  /** Callback when the dialog is closed (close button or backdrop) */
  onClose: () => void;
  /** Dialog title */
  title: React.ReactNode;
  /** Show a back arrow before the title */
  onBack?: () => void;
  /** Back button aria-label */
  backLabel?: string;
  /** Main content — rendered in the scrollable body */
  children: React.ReactNode;
  /** Footer actions — rendered below the body divider */
  footer?: React.ReactNode;
  /** MUI Dialog maxWidth */
  maxWidth?: DialogProps['maxWidth'];
  /** Whether the dialog should be full-width up to maxWidth */
  fullWidth?: boolean;
  /** MUI sx prop for the Dialog Paper */
  paperSx?: SxProps<Theme>;
  /** MUI sx prop for the root Dialog */
  sx?: SxProps<Theme>;
}

// ─── Component ───────────────────────────────────────────────────────────────

/**
 * Standard dialog container for the FA design system.
 *
 * Provides consistent chrome for all popup dialogs across the site:
 * header (title + optional back + close), scrollable body, optional footer.
 *
 * Used by FilterPanel, ArrangementDialog, and any future popup pattern.
 *
 * Usage:
 * ```tsx
 * <DialogShell open={open} onClose={handleClose} title="Filters" footer={<Button>Done</Button>}>
 *   {filterControls}
 * </DialogShell>
 * ```
 */
export const DialogShell = React.forwardRef<HTMLDivElement, DialogShellProps>(
  (
    {
      open,
      onClose,
      title,
      onBack,
      backLabel = 'Back',
      children,
      footer,
      maxWidth = 'sm',
      fullWidth = true,
      paperSx,
      sx,
    },
    ref,
  ) => {
    const titleId = React.useId();
    const titleRef = React.useRef<HTMLHeadingElement>(null);

    // Focus title on open or when title changes (e.g. step transitions)
    React.useEffect(() => {
      if (open && titleRef.current) {
        titleRef.current.focus();
      }
    }, [open, title]);

    return (
      <Dialog
        ref={ref}
        open={open}
        onClose={onClose}
        maxWidth={maxWidth}
        fullWidth={fullWidth}
        aria-labelledby={titleId}
        sx={sx}
        PaperProps={{
          sx: [
            {
              borderRadius: 2,
              maxHeight: '80vh',
              display: 'flex',
              flexDirection: 'column',
            },
            ...(Array.isArray(paperSx) ? paperSx : paperSx ? [paperSx] : []),
          ],
        }}
      >
        {/* Header */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            px: 5,
            pt: 2.5,
            pb: 2,
            flexShrink: 0,
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, minWidth: 0 }}>
            {onBack && (
              <IconButton
                onClick={onBack}
                aria-label={backLabel}
                sx={{ minWidth: 44, minHeight: 44 }}
              >
                <ArrowBackIcon fontSize="small" />
              </IconButton>
            )}
            <Typography
              id={titleId}
              ref={titleRef}
              variant="h6"
              component="h2"
              tabIndex={-1}
              sx={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
            >
              {title}
            </Typography>
          </Box>
          <IconButton
            onClick={onClose}
            aria-label="Close"
            sx={{ color: 'text.secondary', flexShrink: 0, ml: 1, minWidth: 44, minHeight: 44 }}
          >
            <CloseIcon fontSize="small" />
          </IconButton>
        </Box>

        <Divider />

        {/* Scrollable body */}
        <Box
          sx={{
            px: 5,
            py: 2.5,
            overflowY: 'auto',
            flex: 1,
          }}
        >
          {children}
        </Box>

        {/* Footer (optional) */}
        {footer && (
          <>
            <Divider />
            <Box sx={{ px: 5, py: 2, flexShrink: 0 }}>{footer}</Box>
          </>
        )}
      </Dialog>
    );
  },
);

DialogShell.displayName = 'DialogShell';
export default DialogShell;
