import React from 'react';
import Box from '@mui/material/Box';
import SearchOutlinedIcon from '@mui/icons-material/SearchOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { Input } from '../../atoms/Input';
import { ToggleButtonGroup } from '../../atoms/ToggleButtonGroup';
import { Collapse } from '../../atoms/Collapse';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Divider } from '../../atoms/Divider';

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

/** Form values for the cemetery step */
export interface CemeteryStepValues {
  /** Does the family already own a burial plot? */
  ownPlot: 'yes' | 'no' | 'unsure' | null;
  /** Do they have a preference for a cemetery? (when ownPlot ≠ yes) */
  hasPreference: 'yes' | 'no' | 'unsure' | null;
  /** Cemetery search text (freetext — parent wires to Places API) */
  cemeterySearch: string;
}

/** Field-level error messages */
export interface CemeteryStepErrors {
  ownPlot?: string;
  hasPreference?: string;
  cemeterySearch?: string;
}

/** Props for the CemeteryStep page component */
export interface CemeteryStepProps {
  /** Current form values */
  values: CemeteryStepValues;
  /** Callback when any field value changes */
  onChange: (values: CemeteryStepValues) => 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?: CemeteryStepErrors;
  /** Whether Continue is loading */
  loading?: boolean;
  /** Slot for a location autocomplete (e.g. Google Places) — rendered below the search input */
  searchSlot?: React.ReactNode;
  /** 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 9 — Cemetery for the FA arrangement wizard.
 *
 * Cemetery selection and burial plot preferences. Only shown for
 * burial-type funerals (Service & Burial, Graveside, Burial Only).
 *
 * Progressive disclosure flow:
 * 1. "Do you already own a burial plot?" → Yes / No / Not sure
 * 2a. Yes → "Tell us where it's located" + cemetery dropdown
 * 2b. No/Not sure → "Do you have a preference?" → Yes / No / Not sure
 * 3. Preference Yes → "Select your preferred cemetery" + dropdown
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/09_cemetery.yaml
 */
export const CemeteryStep: React.FC<CemeteryStepProps> = ({
  values,
  onChange,
  onContinue,
  onBack,
  onSaveAndExit,
  errors,
  loading = false,
  searchSlot,
  isPrePlanning = false,
  navigation,
  progressStepper,
  runningTotal,
  hideHelpBar,
  sx,
}) => {
  const showPreferenceQuestion = values.ownPlot === 'no' || values.ownPlot === 'unsure';
  const showCemeteryForOwnPlot = values.ownPlot === 'yes';
  const showCemeteryForPreference = showPreferenceQuestion && values.hasPreference === 'yes';

  const handleOwnPlotChange = (value: string | null) => {
    onChange({
      ...values,
      ownPlot: (value ?? null) as CemeteryStepValues['ownPlot'],
      // Reset dependent fields
      hasPreference: null,
      cemeterySearch: '',
    });
  };

  const handlePreferenceChange = (value: string | null) => {
    onChange({
      ...values,
      hasPreference: (value ?? null) as CemeteryStepValues['hasPreference'],
      cemeterySearch: '',
    });
  };

  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}>
        Cemetery
      </Typography>

      <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
        {isPrePlanning
          ? 'If you haven\u2019t decided on a cemetery yet, the funeral provider can help with this later.'
          : 'Choose where the burial will take place.'}
      </Typography>

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

      <Box
        component="form"
        noValidate
        aria-busy={loading}
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          if (!loading) onContinue();
        }}
      >
        {/* ─── Question 1: Own a burial plot? ─── */}
        <Box sx={{ mb: 4 }}>
          <ToggleButtonGroup
            label="Do you already own a burial plot?"
            options={[
              { value: 'yes', label: 'Yes' },
              { value: 'no', label: 'No' },
              { value: 'unsure', label: 'Not sure' },
            ]}
            value={values.ownPlot}
            onChange={handleOwnPlotChange}
            error={!!errors?.ownPlot}
            helperText={errors?.ownPlot}
            fullWidth
          />
        </Box>

        {/* ─── Own plot: tell us where ─── */}
        <Collapse in={showCemeteryForOwnPlot}>
          <Box sx={{ mb: 4 }}>
            <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
              Tell us where the burial plot is located.
            </Typography>

            {searchSlot ?? (
              <Input
                value={values.cemeterySearch}
                onChange={(e) => onChange({ ...values, cemeterySearch: e.target.value })}
                placeholder="Search for a cemetery or location..."
                startIcon={<SearchOutlinedIcon />}
                error={!!errors?.cemeterySearch}
                helperText={errors?.cemeterySearch}
                fullWidth
              />
            )}
          </Box>
        </Collapse>

        {/* ─── Question 2: Have a preference? (when no plot) ─── */}
        <Collapse in={showPreferenceQuestion}>
          <Box sx={{ mb: 4 }}>
            <ToggleButtonGroup
              label="Do you have a preference for a cemetery?"
              options={[
                { value: 'yes', label: 'Yes' },
                { value: 'no', label: 'No' },
                { value: 'unsure', label: 'Not sure' },
              ]}
              value={values.hasPreference}
              onChange={handlePreferenceChange}
              error={!!errors?.hasPreference}
              helperText={errors?.hasPreference}
              fullWidth
            />
          </Box>
        </Collapse>

        {/* ─── Preference: search cemetery ─── */}
        <Collapse in={showCemeteryForPreference}>
          <Box sx={{ mb: 4 }}>
            {searchSlot ?? (
              <Input
                value={values.cemeterySearch}
                onChange={(e) => onChange({ ...values, cemeterySearch: e.target.value })}
                placeholder="Search for a cemetery or location..."
                startIcon={<SearchOutlinedIcon />}
                error={!!errors?.cemeterySearch}
                helperText={errors?.cemeterySearch}
                fullWidth
              />
            )}
          </Box>
        </Collapse>

        <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>
  );
};

CemeteryStep.displayName = 'CemeteryStep';
export default CemeteryStep;
