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 PeopleOutlinedIcon from '@mui/icons-material/PeopleOutlined';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
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 { Card } from '../../atoms/Card';
import { Chip } from '../../atoms/Chip';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Divider } from '../../atoms/Divider';

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

/** Full venue detail data */
export interface VenueDetail {
  id: string;
  name: string;
  imageUrl: string;
  /** Additional gallery images (if provided, imageUrl becomes the first) */
  images?: GalleryImage[];
  location: string;
  venueType?: string;
  capacity?: number;
  price?: number;
  /** Explanation of how the price affects the plan total */
  priceNote?: string;
  description?: string;
  features?: string[];
  religions?: string[];
  address?: string;
}

/** Service add-on toggle */
export interface VenueService {
  id: string;
  name: string;
  description?: string;
  price?: number;
}

/** Props for the VenueDetailStep page component */
export interface VenueDetailStepProps {
  /** The venue to display */
  venue: VenueDetail;
  /** Callback when "Add Venue" is clicked */
  onAddVenue: () => void;
  /** Callback for back navigation */
  onBack?: () => void;
  /** Callback for save-and-exit */
  onSaveAndExit?: () => void;
  /** Whether the button is in a loading state */
  loading?: boolean;
  /** Available venue services */
  services?: VenueService[];
  /** 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>;
}

// ─── Helper ─────────────────────────────────────────────────────────────────

/** Compact icon + text row used for venue metadata */
const MetaRow: React.FC<{ icon: React.ReactNode; children: React.ReactNode }> = ({
  icon,
  children,
}) => (
  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
    <Box sx={{ color: 'text.secondary', display: 'flex', fontSize: 18 }}>{icon}</Box>
    <Typography variant="body2" color="text.secondary">
      {children}
    </Typography>
  </Box>
);

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

/**
 * Venue Detail page for the FA arrangement wizard.
 *
 * Detail-toggles layout: scrollable left panel with image, description,
 * features, location, and address. Sticky right panel with venue info,
 * price, CTA, supported religions, and service toggles.
 *
 * Reached by clicking a venue card on VenueStep.
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/07_venue_consolidated.yaml
 */
export const VenueDetailStep: React.FC<VenueDetailStepProps> = ({
  venue,
  onAddVenue,
  onBack,
  onSaveAndExit,
  loading = false,
  services = [],
  isPrePlanning = false,
  navigation,
  progressStepper,
  runningTotal,
  hideHelpBar,
  sx,
}) => {
  return (
    <WizardLayout
      variant="detail-toggles"
      navigation={navigation}
      progressStepper={progressStepper}
      runningTotal={runningTotal}
      showBackLink={!!onBack}
      backLabel="Back"
      onBack={onBack}
      hideHelpBar={hideHelpBar}
      sx={sx}
      secondaryPanel={
        <Box>
          {/* ─── Venue name ─── */}
          <Typography variant="h4" component="h1" sx={{ mb: 1.5 }}>
            {venue.name}
          </Typography>

          {/* ─── Meta: location, type, capacity ─── */}
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.75, mb: 3 }}>
            <MetaRow icon={<LocationOnOutlinedIcon fontSize="inherit" />}>{venue.location}</MetaRow>
            {venue.venueType && (
              <MetaRow icon={<HomeWorkOutlinedIcon fontSize="inherit" />}>
                {venue.venueType}
              </MetaRow>
            )}
            {venue.capacity != null && (
              <MetaRow icon={<PeopleOutlinedIcon fontSize="inherit" />}>
                Seats up to {venue.capacity} guests
              </MetaRow>
            )}
          </Box>

          {/* ─── Price ─── */}
          {venue.price != null && (
            <Box sx={{ mb: 3 }}>
              <Typography variant="h5" color="primary">
                ${venue.price.toLocaleString('en-AU')}
              </Typography>
              {venue.priceNote && (
                <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
                  {venue.priceNote}
                </Typography>
              )}
            </Box>
          )}

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

          {onSaveAndExit && (
            <Button
              variant="text"
              color="secondary"
              fullWidth
              onClick={onSaveAndExit}
              sx={{ mt: 1 }}
            >
              Save and continue later
            </Button>
          )}

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

          {/* ─── Address ─── */}
          {venue.address && (
            <Box sx={{ mb: 3 }}>
              <Typography variant="labelSm" color="text.secondary" sx={{ mb: 0.5 }}>
                Address
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1 }}>
                <LocationOnOutlinedIcon
                  sx={{ fontSize: 16, color: 'text.secondary', mt: 0.25 }}
                  aria-hidden
                />
                <Typography variant="body2">{venue.address}</Typography>
              </Box>
            </Box>
          )}

          {/* ─── Supported religions / service styles ─── */}
          {venue.religions && venue.religions.length > 0 && (
            <Box sx={{ mb: 3 }}>
              <Typography variant="labelSm" color="text.secondary" sx={{ mb: 1 }}>
                Supported service styles
              </Typography>
              <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap' }}>
                {venue.religions.map((r) => (
                  <Chip key={r} label={r} size="small" />
                ))}
              </Box>
            </Box>
          )}
        </Box>
      }
    >
      {/* ═══════ LEFT PANEL: scrollable content ═══════ */}

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

      {/* ─── Description ─── */}
      {venue.description && (
        <Typography variant="body1" color="text.primary" sx={{ mb: 3, lineHeight: 1.7 }}>
          {venue.description}
        </Typography>
      )}

      {/* ─── Features ─── */}
      {venue.features && venue.features.length > 0 && (
        <>
          <Divider sx={{ my: 3 }} />
          <Typography variant="h5" sx={{ mb: 2 }}>
            Venue features
          </Typography>
          <Box
            sx={{
              display: 'grid',
              gridTemplateColumns: { xs: '1fr', sm: 'repeat(2, 1fr)' },
              gap: 1.5,
              mb: 3,
            }}
          >
            {venue.features.map((feature) => (
              <Box key={feature} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <CheckCircleOutlineIcon sx={{ fontSize: 18, color: 'success.main' }} aria-hidden />
                <Typography variant="body2">{feature}</Typography>
              </Box>
            ))}
          </Box>
        </>
      )}

      {/* ─── Location (map placeholder) ─── */}
      <Divider sx={{ my: 3 }} />
      <Typography variant="h5" sx={{ mb: 2 }}>
        Location
      </Typography>
      <Card variant="outlined" padding="none" sx={{ mb: 3, overflow: 'hidden' }}>
        <Box
          sx={{
            height: 200,
            bgcolor: 'var(--fa-color-surface-cool)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Typography variant="body2" color="text.secondary">
            Map coming soon
          </Typography>
        </Box>
      </Card>

      {/* ─── Address (left panel) ─── */}
      {venue.address && (
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 1, mb: 3 }}>
          <LocationOnOutlinedIcon
            sx={{ fontSize: 18, color: 'text.secondary', mt: 0.25 }}
            aria-hidden
          />
          <Typography variant="body2" color="text.secondary">
            {venue.address}
          </Typography>
        </Box>
      )}

      {/* ─── Available services (informational) ─── */}
      {services.length > 0 && (
        <>
          <Divider sx={{ my: 3 }} />
          <Typography variant="h5" sx={{ mb: 1 }}>
            Available venue services
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            This venue offers the following optional services. You can choose which ones to include
            in the next step.
          </Typography>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
            {services.map((service) => (
              <Card key={service.id} variant="outlined" padding="compact">
                <Box
                  sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                  }}
                >
                  <Box>
                    <Typography variant="label">{service.name}</Typography>
                    {service.description && (
                      <Typography variant="body2" color="text.secondary">
                        {service.description}
                      </Typography>
                    )}
                  </Box>
                  {service.price != null && (
                    <Typography variant="labelSm" color="primary" sx={{ whiteSpace: 'nowrap' }}>
                      ${service.price.toLocaleString('en-AU')}
                    </Typography>
                  )}
                </Box>
              </Card>
            ))}
          </Box>
        </>
      )}
    </WizardLayout>
  );
};

VenueDetailStep.displayName = 'VenueDetailStep';
export default VenueDetailStep;
