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

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

/** Compact venue reference for the header card */
export interface VenueServicesVenue {
  name: string;
  imageUrl?: string;
  location: string;
  venueType?: string;
}

/** A venue service that can be toggled on/off */
export interface VenueServiceOption {
  id: string;
  name: string;
  description?: string;
  price?: number;
}

/** An informational notice about unavailable services */
export interface VenueServiceNotice {
  title: string;
  detail?: string;
}

/** Current toggle state — map of service ID to checked */
export interface VenueServicesStepValues {
  [serviceId: string]: boolean;
}

/** Props for the VenueServicesStep page component */
export interface VenueServicesStepProps {
  /** The selected venue (shown as compact summary card) */
  venue: VenueServicesVenue;
  /** Available services to toggle */
  services: VenueServiceOption[];
  /** Current toggle state for each service */
  values: VenueServicesStepValues;
  /** Callback when any service toggle changes */
  onChange: (values: VenueServicesStepValues) => void;
  /** Callback when Continue is clicked */
  onContinue: () => void;
  /** Callback for back navigation */
  onBack?: () => void;
  /** Callback for save-and-exit */
  onSaveAndExit?: () => void;
  /** Whether Continue is loading */
  loading?: boolean;
  /** Notices about unavailable services (e.g. no livestreaming) */
  notices?: VenueServiceNotice[];
  /** 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 ───────────────────────────────────────────────────────────────

/**
 * Venue Services page for the FA arrangement wizard.
 *
 * Shown after VenueDetailStep — the user has already selected a venue
 * and now chooses which venue-specific services to include (photo
 * presentation, livestreaming, recording, etc.).
 *
 * Compact venue card at top for context. Availability notices for
 * services the selected package doesn't support. AddOnOption toggles
 * with expandable descriptions for services that have detail.
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/07_venue.yaml (venue services section)
 */
export const VenueServicesStep: React.FC<VenueServicesStepProps> = ({
  venue,
  services,
  values,
  onChange,
  onContinue,
  onBack,
  onSaveAndExit,
  loading = false,
  notices = [],
  isPrePlanning = false,
  navigation,
  progressStepper,
  runningTotal,
  hideHelpBar,
  sx,
}) => {
  const handleToggle = (serviceId: string, checked: boolean) => {
    onChange({ ...values, [serviceId]: checked });
  };

  // Compute tally of selected priced services
  const selectedServices = services.filter((s) => values[s.id] && s.price != null);
  const totalAdditional = selectedServices.reduce((sum, s) => sum + (s.price ?? 0), 0);

  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}>
        Funeral Service
      </Typography>

      {/* ─── Compact venue card ─── */}
      <Card
        variant="outlined"
        padding="none"
        sx={{
          display: 'flex',
          overflow: 'hidden',
          minHeight: 100,
          mb: 4,
        }}
      >
        {venue.imageUrl && (
          <Box
            role="img"
            aria-label={`${venue.name} photo`}
            sx={{
              width: { xs: 120, sm: 160 },
              flexShrink: 0,
              backgroundImage: `url(${venue.imageUrl})`,
              backgroundSize: 'cover',
              backgroundPosition: 'center',
            }}
          />
        )}
        <Box
          sx={{
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            gap: 0.5,
            p: 2,
            minWidth: 0,
          }}
        >
          <Typography variant="h6" component="span" maxLines={1}>
            {venue.name}
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
            <LocationOnOutlinedIcon sx={{ fontSize: 14, color: 'text.secondary' }} aria-hidden />
            <Typography variant="body2" color="text.secondary">
              {venue.location}
            </Typography>
          </Box>
          {venue.venueType && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <HomeWorkOutlinedIcon sx={{ fontSize: 14, color: 'text.secondary' }} aria-hidden />
              <Typography variant="body2" color="text.secondary">
                {venue.venueType}
              </Typography>
            </Box>
          )}
        </Box>
      </Card>

      {/* ─── Additional services heading ─── */}
      <Typography variant="h5" component="h2" sx={{ mb: 0.5 }}>
        Additional services
      </Typography>
      <Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
        {isPrePlanning
          ? 'These can be finalised later. Toggle on the ones you\u2019re interested in.'
          : 'Select any additional services offered at this venue that you would like included in the funeral plan.'}
      </Typography>

      <Box
        component="form"
        noValidate
        aria-busy={loading}
        onSubmit={(e: React.FormEvent) => {
          e.preventDefault();
          if (!loading) onContinue();
        }}
      >
        {/* ─── Availability notices ─── */}
        {notices.map((notice, i) => (
          <Card
            key={i}
            variant="outlined"
            padding="compact"
            sx={{
              mb: 2,
              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 }}>
                  {notice.title}
                </Typography>
                {notice.detail && (
                  <Typography variant="body2" color="text.secondary">
                    {notice.detail}
                  </Typography>
                )}
              </Box>
            </Box>
          </Card>
        ))}

        {/* ─── Service toggles ─── */}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 4 }}>
          {services.map((service) => (
            <AddOnOption
              key={service.id}
              name={service.name}
              description={service.description}
              price={service.price}
              checked={!!values[service.id]}
              onChange={(checked) => handleToggle(service.id, checked)}
              maxDescriptionLines={3}
            />
          ))}
        </Box>

        {/* ─── Tally ─── */}
        {selectedServices.length > 0 && (
          <>
            <Divider sx={{ my: 3 }} />
            <Box
              sx={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
              aria-live="polite"
              aria-atomic="true"
            >
              <Typography variant="h6">Additional services total</Typography>
              <Typography variant="h6" color="primary">
                ${totalAdditional.toLocaleString('en-AU')}
              </Typography>
            </Box>
          </>
        )}

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

VenueServicesStep.displayName = 'VenueServicesStep';
export default VenueServicesStep;
