import React from 'react';
import Box from '@mui/material/Box';
import type { SxProps, Theme } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { ImageGallery } from '../../molecules/ImageGallery';
import type { GalleryImage } from '../../molecules/ImageGallery';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Divider } from '../../atoms/Divider';

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

/** Colour option for a coffin */
export interface CoffinColour {
  id: string;
  name: string;
  /** Hex colour value for the swatch */
  hex: string;
}

/** Coffin specification key-value pair */
export interface CoffinSpec {
  label: string;
  value: string;
}

/** Selected coffin profile data */
export interface CoffinProfile {
  name: string;
  imageUrl: string;
  /** Additional gallery images */
  images?: GalleryImage[];
  /** Short description shown on the right panel */
  description?: string;
  /** Product specifications (Range, Shape, Colour, Finish, Hardware) */
  specs?: CoffinSpec[];
  price: number;
  /** Available colour options */
  colours?: CoffinColour[];
}

/** Package coffin allowance amount (shown in info bubble, omit if no allowance) */
export type CoffinAllowanceAmount = number;

/** Props for the CoffinDetailsStep page component */
export interface CoffinDetailsStepProps {
  /** The selected coffin profile */
  coffin: CoffinProfile;
  /** Callback when "Add Coffin" is clicked */
  onAddCoffin: () => void;
  /** Callback for back navigation */
  onBack?: () => void;
  /** Callback for save-and-exit */
  onSaveAndExit?: () => void;
  /** Whether the CTA is in a loading state */
  loading?: boolean;
  /** Selected colour ID (controlled) */
  selectedColourId?: string;
  /** Colour change callback */
  onColourChange?: (colourId: string) => void;
  /** Package coffin allowance amount (shown in info bubble, omit if no allowance) */
  allowanceAmount?: number;
  /** Whether this is a pre-planning flow */
  isPrePlanning?: boolean;
  /** Navigation bar */
  navigation?: React.ReactNode;
  /** Progress stepper */
  progressStepper?: React.ReactNode;
  /** Running total */
  runningTotal?: React.ReactNode;
  /** Hide the help bar */
  hideHelpBar?: boolean;
  /** MUI sx prop */
  sx?: SxProps<Theme>;
}

// ─── Internal: Colour Swatch ────────────────────────────────────────────────

const SWATCH_SIZE = 36;

const ColourSwatch: React.FC<{
  colour: CoffinColour;
  selected: boolean;
  onClick: () => void;
}> = ({ colour, selected, onClick }) => (
  <Box
    component="button"
    type="button"
    onClick={onClick}
    aria-label={colour.name}
    aria-pressed={selected}
    sx={{
      width: SWATCH_SIZE,
      height: SWATCH_SIZE,
      borderRadius: '50%',
      backgroundColor: colour.hex,
      border: '2px solid',
      borderColor: selected ? 'primary.main' : 'var(--fa-color-border-default)',
      outline: selected ? '2px solid' : 'none',
      outlineColor: 'primary.main',
      outlineOffset: 2,
      cursor: 'pointer',
      padding: 0,
      transition: 'border-color 150ms, outline 150ms',
      '&:hover': {
        borderColor: selected ? 'primary.main' : 'text.secondary',
      },
      '&:focus-visible': {
        outline: '2px solid',
        outlineColor: 'primary.main',
        outlineOffset: 2,
      },
    }}
  />
);

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

/**
 * Step 11 — Coffin Details for the FA arrangement wizard.
 *
 * Detail-toggles layout matching VenueDetailStep pattern:
 * scrollable left panel with image gallery and specs,
 * sticky right panel with name, description, colour picker,
 * price, allowance info, and CTA.
 *
 * Reached by clicking a coffin card on CoffinsStep.
 * Colour selection does not affect price.
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/11_coffin_details.yaml
 */
export const CoffinDetailsStep: React.FC<CoffinDetailsStepProps> = ({
  coffin,
  onAddCoffin,
  onBack,
  onSaveAndExit,
  loading = false,
  selectedColourId,
  onColourChange,
  allowanceAmount,
  isPrePlanning = false,
  navigation,
  progressStepper,
  runningTotal,
  hideHelpBar,
  sx,
}) => {
  const selectedColour = coffin.colours?.find((c) => c.id === selectedColourId);

  // Allowance impact
  const hasAllowance = allowanceAmount != null;
  const isFullyCovered = hasAllowance && allowanceAmount >= coffin.price;
  const additionalCost = hasAllowance && !isFullyCovered ? coffin.price - allowanceAmount : 0;

  return (
    <WizardLayout
      variant="detail-toggles"
      navigation={navigation}
      progressStepper={progressStepper}
      runningTotal={runningTotal}
      showBackLink={!!onBack}
      backLabel="Back"
      onBack={onBack}
      hideHelpBar={hideHelpBar}
      sx={sx}
      secondaryPanel={
        <Box sx={{ position: 'sticky', top: 24 }}>
          {/* ─── Coffin name ─── */}
          <Typography variant="h4" component="h1" sx={{ mb: 1 }}>
            {coffin.name}
          </Typography>

          {/* ─── Short description ─── */}
          {coffin.description && (
            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              {coffin.description}
            </Typography>
          )}

          {/* ─── Colour picker ─── */}
          {coffin.colours && coffin.colours.length > 0 && onColourChange && (
            <Box sx={{ mb: 3 }}>
              <Typography
                variant="labelSm"
                color="text.secondary"
                sx={{ mb: 1.5, display: 'block' }}
              >
                Colour
              </Typography>
              <Box
                role="group"
                aria-label="Coffin colour"
                sx={{ display: 'flex', gap: 1.5, flexWrap: 'wrap', mb: 1 }}
              >
                {coffin.colours.map((colour) => (
                  <ColourSwatch
                    key={colour.id}
                    colour={colour}
                    selected={colour.id === selectedColourId}
                    onClick={() => onColourChange(colour.id)}
                  />
                ))}
              </Box>
              {selectedColour && (
                <Typography variant="body2" color="text.primary">
                  {selectedColour.name}
                </Typography>
              )}
            </Box>
          )}

          {/* ─── Price ─── */}
          <Typography
            variant="h5"
            component="p"
            color="primary"
            sx={{ mb: hasAllowance ? 0.5 : 3 }}
          >
            ${coffin.price.toLocaleString('en-AU', { minimumFractionDigits: 2 })}
          </Typography>

          {/* ─── Allowance impact ─── */}
          {isFullyCovered && (
            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              Included in your package allowance — no change to your plan total.
            </Typography>
          )}

          {hasAllowance && !isFullyCovered && (
            <Box sx={{ mb: 3 }}>
              <Typography variant="body2" color="text.secondary">
                ${allowanceAmount.toLocaleString('en-AU')} package allowance applied
              </Typography>
              <Typography variant="label" color="primary">
                +${additionalCost.toLocaleString('en-AU', { minimumFractionDigits: 2 })} to your
                plan total
              </Typography>
            </Box>
          )}

          {/* ─── Add Coffin CTA ─── */}
          <Box
            component="form"
            noValidate
            aria-busy={loading}
            onSubmit={(e: React.FormEvent) => {
              e.preventDefault();
              if (!loading) onAddCoffin();
            }}
          >
            <Button type="submit" variant="contained" size="large" fullWidth loading={loading}>
              {isPrePlanning ? 'Select coffin' : 'Add coffin'}
            </Button>
          </Box>

          {/* ─── Save and exit ─── */}
          {onSaveAndExit && (
            <>
              <Divider sx={{ my: 3 }} />
              <Button variant="text" color="secondary" fullWidth onClick={onSaveAndExit}>
                Save and continue later
              </Button>
            </>
          )}
        </Box>
      }
    >
      {/* ═══════ LEFT PANEL: scrollable content ═══════ */}

      {/* ─── Image gallery ─── */}
      <ImageGallery
        images={
          coffin.images && coffin.images.length > 0
            ? coffin.images
            : [{ src: coffin.imageUrl, alt: `Photo of ${coffin.name}` }]
        }
        heroHeight={{ xs: 280, md: 420 }}
        sx={{ mb: 3 }}
      />

      {/* ─── Product details ─── */}
      {coffin.specs && coffin.specs.length > 0 && (
        <>
          <Divider sx={{ my: 3 }} />
          <Box
            component="dl"
            sx={{
              display: 'flex',
              flexDirection: 'column',
              gap: 1.5,
              m: 0,
            }}
          >
            {coffin.specs.map((spec) => (
              <Box key={spec.label}>
                <Typography component="dt" variant="label" sx={{ display: 'block', mb: 0.25 }}>
                  {spec.label}
                </Typography>
                <Typography component="dd" variant="body2" color="text.secondary" sx={{ m: 0 }}>
                  {spec.value}
                </Typography>
              </Box>
            ))}
          </Box>
        </>
      )}
    </WizardLayout>
  );
};

CoffinDetailsStep.displayName = 'CoffinDetailsStep';
export default CoffinDetailsStep;
