import React from 'react';
import Box from '@mui/material/Box';
import LocationOnOutlinedIcon from '@mui/icons-material/LocationOnOutlined';
import DirectionsCarOutlinedIcon from '@mui/icons-material/DirectionsCarOutlined';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { Card } from '../../atoms/Card';
import { Badge } from '../../atoms/Badge';
import { ToggleButtonGroup } from '../../atoms/ToggleButtonGroup';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Divider } from '../../atoms/Divider';

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

/** The pre-selected crematorium */
export interface Crematorium {
  name: string;
  imageUrl?: string;
  address: string;
  distance?: string;
}

/** Form values for the crematorium step */
export interface CrematoriumStepValues {
  /** Will anyone follow the hearse? (service & cremation only) */
  attend: 'yes' | 'no' | 'later' | null;
}

/** Field-level error messages */
export interface CrematoriumStepErrors {
  attend?: string;
}

/** Props for the CrematoriumStep page component */
export interface CrematoriumStepProps {
  /** The pre-selected crematorium */
  crematorium: Crematorium;
  /** Current form values */
  values: CrematoriumStepValues;
  /** Callback when any field value changes */
  onChange: (values: CrematoriumStepValues) => void;
  /** Callback when Continue is clicked */
  onContinue: () => void;
  /** Callback for back navigation */
  onBack?: () => void;
  /** Callback for save-and-exit */
  onSaveAndExit?: () => void;
  /** Field-level validation errors */
  errors?: CrematoriumStepErrors;
  /** Whether Continue is in a loading state */
  loading?: boolean;
  /** Whether this is a cremation-only flow (no service) */
  isCremationOnly?: boolean;
  /** Deceased first name — personalises witness question */
  deceasedName?: string;
  /** 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>;
}

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

/**
 * Step 8 — Crematorium for the FA arrangement wizard.
 *
 * Confirmation page for the provider's pre-selected crematorium.
 * Two variants based on funeral type:
 *
 * **Service & Cremation:** Crematorium card + witness question
 * ("Will anyone follow the hearse?") with personalised helper text.
 *
 * **Cremation Only:** Crematorium card + "Cremation Only" badge +
 * "Included in Package" notice. No witness question (no procession).
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/08_crematorium.yaml
 */
export const CrematoriumStep: React.FC<CrematoriumStepProps> = ({
  crematorium,
  values,
  onChange,
  onContinue,
  onBack,
  onSaveAndExit,
  errors,
  loading = false,
  isCremationOnly = false,
  deceasedName,
  isPrePlanning = false,
  navigation,
  progressStepper,
  runningTotal,
  hideHelpBar,
  sx,
}) => {
  const witnessHelper = deceasedName
    ? `Please indicate if you wish to follow the hearse in your own vehicles to escort ${deceasedName} to the crematorium.`
    : isPrePlanning
      ? 'This can be decided closer to the time.'
      : 'Please indicate if anyone wishes to follow the hearse to the crematorium.';

  return (
    <WizardLayout
      variant="centered-form"
      navigation={navigation}
      progressStepper={progressStepper}
      runningTotal={runningTotal}
      showBackLink={!!onBack}
      backLabel="Back"
      onBack={onBack}
      hideHelpBar={hideHelpBar}
      sx={sx}
    >
      {/* Page heading */}
      <Typography variant="display3" component="h1" sx={{ mb: 2 }} tabIndex={-1}>
        Crematorium
      </Typography>

      <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
        {isPrePlanning
          ? 'Review the crematorium details. You can update this later.'
          : isCremationOnly
            ? 'The crematorium included with your selected package.'
            : 'Confirm the crematorium and let us know about any preferences.'}
      </Typography>

      <Divider sx={{ mb: 4 }} />

      <Box
        component="form"
        noValidate
        aria-busy={loading}
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          if (!loading) onContinue();
        }}
      >
        {/* ─── Crematorium card ─── */}
        <Card variant="outlined" padding="none" sx={{ overflow: 'hidden', mb: 4 }}>
          {crematorium.imageUrl && (
            <Box
              role="img"
              aria-label={`${crematorium.name} photo`}
              sx={{
                height: { xs: 160, sm: 180 },
                backgroundImage: `url(${crematorium.imageUrl})`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
              }}
            />
          )}
          <Box sx={{ p: 2.5, display: 'flex', flexDirection: 'column', gap: 1 }}>
            <Typography variant="h6" component="span">
              {crematorium.name}
            </Typography>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                <LocationOnOutlinedIcon
                  sx={{ fontSize: 18, color: 'text.secondary', mt: 0.25 }}
                  aria-hidden
                />
                <Typography variant="body2" color="text.secondary">
                  {crematorium.address}
                </Typography>
              </Box>
              {crematorium.distance && (
                <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                  <DirectionsCarOutlinedIcon
                    sx={{ fontSize: 18, color: 'text.secondary', mt: 0.25 }}
                    aria-hidden
                  />
                  <Typography variant="body2" color="text.secondary">
                    {crematorium.distance}
                  </Typography>
                </Box>
              )}
            </Box>
          </Box>
        </Card>

        {isCremationOnly ? (
          <>
            {/* ─── Cremation Only: badge + included notice ─── */}
            <Badge variant="soft" color="success" sx={{ mb: 3 }}>
              Cremation Only
            </Badge>

            <Card
              variant="outlined"
              padding="compact"
              sx={{
                bgcolor: 'var(--fa-color-surface-subtle)',
                borderColor: 'var(--fa-color-border-default)',
              }}
            >
              <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'flex-start' }}>
                <InfoOutlinedIcon
                  sx={{ fontSize: 20, color: 'text.secondary', mt: 0.25, flexShrink: 0 }}
                  aria-hidden
                />
                <Box>
                  <Typography variant="label" sx={{ display: 'block', mb: 0.5 }}>
                    Crematorium included in package
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    The selected crematorium is included in your funeral package. If you have any
                    questions or would prefer a different option, please speak with your funeral
                    director.
                  </Typography>
                </Box>
              </Box>
            </Card>
          </>
        ) : (
          <>
            {/* ─── Service & Cremation: witness question ─── */}
            <Typography variant="h5" component="h2" sx={{ mb: 0.5 }}>
              Will anyone be following the hearse to the crematorium?
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              {witnessHelper}
            </Typography>

            <ToggleButtonGroup
              label=""
              options={[
                { value: 'yes', label: 'Yes' },
                { value: 'no', label: 'No' },
                { value: 'later', label: 'Decide later' },
              ]}
              value={values.attend}
              onChange={(v) =>
                onChange({ ...values, attend: v as CrematoriumStepValues['attend'] })
              }
              error={!!errors?.attend}
              helperText={errors?.attend}
              fullWidth
            />
          </>
        )}

        <Divider sx={{ my: 3 }} />

        {/* CTAs */}
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            flexDirection: { xs: 'column-reverse', sm: 'row' },
            gap: 2,
          }}
        >
          {onSaveAndExit ? (
            <Button variant="text" color="secondary" onClick={onSaveAndExit} type="button">
              Save and continue later
            </Button>
          ) : (
            <Box />
          )}
          <Button type="submit" variant="contained" size="large" loading={loading}>
            Continue
          </Button>
        </Box>
      </Box>
    </WizardLayout>
  );
};

CrematoriumStep.displayName = 'CrematoriumStep';
export default CrematoriumStep;
