import React from 'react';
import Box from '@mui/material/Box';
import ReceiptLongOutlinedIcon from '@mui/icons-material/ReceiptLongOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { DialogShell } from '../../atoms/DialogShell';
import { Divider } from '../../atoms/Divider';
import { LineItem } from '../LineItem';

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

/** A single item in the plan cart */
export interface CartItem {
  /** Section heading (e.g. "Funeral Provider", "Venue") */
  section: string;
  /** Item name */
  name: string;
  /** Price in dollars — omit for included/complimentary items */
  price?: number;
  /** Custom price label (e.g. "Price on application", "Included") */
  priceLabel?: string;
}

/** Props for the CartButton molecule */
export interface CartButtonProps {
  /** Running total in dollars */
  total: number;
  /** Cart items grouped by section */
  items?: CartItem[];
  /** Override the structured dialog body with custom content */
  children?: React.ReactNode;
  /** MUI sx prop for the trigger button */
  sx?: SxProps<Theme>;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/** Group items by their section heading */
const groupBySection = (items: CartItem[]) => {
  const groups: { section: string; items: CartItem[] }[] = [];
  for (const item of items) {
    const last = groups[groups.length - 1];
    if (last && last.section === item.section) {
      last.items.push(item);
    } else {
      groups.push({ section: item.section, items: [item] });
    }
  }
  return groups;
};

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

/**
 * Cart button for the arrangement wizard progress bar.
 *
 * Shows the running plan total in a compact trigger button. Clicking opens
 * a DialogShell with the plan contents — items grouped by section using
 * LineItem molecules.
 *
 * Sits in the `runningTotal` slot of WizardLayout.
 *
 * Usage:
 * ```tsx
 * <CartButton
 *   total={6715}
 *   items={[
 *     { section: 'Funeral Provider', name: 'H. Parsons — Essential Package', price: 4950 },
 *     { section: 'Venue', name: 'West Chapel', price: 900 },
 *     { section: 'Extras', name: 'Catering', priceLabel: 'Price on application' },
 *   ]}
 * />
 * ```
 */
export const CartButton = React.forwardRef<HTMLButtonElement, CartButtonProps>(
  ({ total, items = [], children, sx }, ref) => {
    const [open, setOpen] = React.useState(false);
    const formattedTotal = `$${total.toLocaleString('en-AU')}`;
    const groups = groupBySection(items);

    return (
      <>
        {/* Trigger */}
        <Button
          ref={ref}
          variant="outlined"
          color="secondary"
          size="small"
          onClick={() => setOpen(true)}
          aria-haspopup="dialog"
          startIcon={<ReceiptLongOutlinedIcon sx={{ fontSize: 18 }} />}
          sx={[
            {
              borderRadius: '9999px',
              textTransform: 'none',
              gap: 1,
              pl: 2,
              pr: 2.5,
            },
            ...(Array.isArray(sx) ? sx : [sx]),
          ]}
        >
          <Box component="span" sx={{ display: { xs: 'none', sm: 'inline' }, fontWeight: 500 }}>
            Your Plan
          </Box>
          <Typography
            component="span"
            variant="label"
            sx={{ color: 'primary.main', fontWeight: 700 }}
          >
            {formattedTotal}
          </Typography>
        </Button>

        {/* Dialog */}
        <DialogShell
          open={open}
          onClose={() => setOpen(false)}
          title="Your plan so far"
          maxWidth="xs"
          footer={
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', px: 3, py: 2 }}>
              <Button variant="text" color="secondary" onClick={() => setOpen(false)}>
                Close
              </Button>
            </Box>
          }
        >
          {children || (
            <Box sx={{ px: 3, py: 2 }}>
              {items.length === 0 ? (
                <Typography
                  variant="body2"
                  color="text.secondary"
                  sx={{ textAlign: 'center', py: 4 }}
                >
                  Your plan is empty. Selections will appear here as you build your arrangement.
                </Typography>
              ) : (
                <>
                  {groups.map((group, gi) => (
                    <Box key={group.section} sx={{ mb: gi < groups.length - 1 ? 2 : 0 }}>
                      <Typography
                        variant="labelSm"
                        color="text.secondary"
                        sx={{ mb: 1, textTransform: 'uppercase', letterSpacing: '0.05em' }}
                      >
                        {group.section}
                      </Typography>
                      {group.items.map((item, ii) => (
                        <LineItem
                          key={`${group.section}-${ii}`}
                          name={item.name}
                          price={item.price}
                          priceLabel={item.priceLabel}
                        />
                      ))}
                    </Box>
                  ))}

                  <Divider sx={{ my: 2 }} />
                  <LineItem name="Total" price={total} variant="total" />
                </>
              )}
            </Box>
          )}
        </DialogShell>
      </>
    );
  },
);

CartButton.displayName = 'CartButton';
export default CartButton;
