import React from 'react';
import Box from '@mui/material/Box';
import type { SxProps, Theme } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { ProviderCardCompact } from '../../molecules/ProviderCardCompact';
import { ServiceOption } from '../../molecules/ServiceOption';
import { PackageDetail } from '../../organisms/PackageDetail';
import type { PackageSection } from '../../organisms/PackageDetail';
import { Typography } from '../../atoms/Typography';
import { Divider } from '../../atoms/Divider';

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

/** Provider summary for the compact card */
export interface PackagesStepProvider {
  /** Provider name */
  name: string;
  /** Location */
  location: string;
  /** Image URL */
  imageUrl?: string;
  /** Rating */
  rating?: number;
  /** Review count */
  reviewCount?: number;
}

/** Package data for the selection list */
export interface PackageData {
  /** Unique package ID */
  id: string;
  /** Package display name */
  name: string;
  /** Package price in dollars */
  price: number;
  /** Short description */
  description?: string;
  /** Line item sections for the detail panel */
  sections: PackageSection[];
  /** Total price (may differ from base price with extras) */
  total?: number;
  /** Extra items section (after total) */
  extras?: PackageSection;
  /** Terms and conditions */
  terms?: string;
}

/** Props for the PackagesStep page component */
export interface PackagesStepProps {
  /** Provider summary shown at top of the list panel */
  provider: PackagesStepProvider;
  /** Packages matching the user's filters from the previous step */
  packages: PackageData[];
  /** Other packages from this provider that didn't match filters (shown in secondary group) */
  otherPackages?: PackageData[];
  /** Currently selected package ID */
  selectedPackageId: string | null;
  /** Callback when a package is selected */
  onSelectPackage: (id: string) => void;
  /** Callback when "Make Arrangement" is clicked (opens ArrangementDialog) */
  onArrange: () => void;
  /** Callback when the provider card is clicked (opens provider profile popup) */
  onProviderClick?: () => void;
  /** Callback for the Back button */
  onBack: () => void;
  /** Validation error */
  error?: string;
  /** Whether the arrange action is loading */
  loading?: boolean;
  /** Navigation bar */
  navigation?: React.ReactNode;
  /** Whether this is a pre-planning flow */
  isPrePlanning?: boolean;
  /** MUI sx prop */
  sx?: SxProps<Theme>;
}

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

/**
 * Step 3 — Package selection page for the FA arrangement wizard.
 *
 * List + Detail split layout. Left panel shows the selected provider
 * (compact) and selectable package cards. Right panel shows the full
 * detail breakdown of the selected package with "Make Arrangement" CTA.
 *
 * Packages are split into two groups:
 * - **Matching your preferences**: packages that matched the user's filters
 *   from the providers step
 * - **Other packages from [Provider]**: remaining packages outside those
 *   filters, shown below a divider for passive discovery
 *
 * Selecting a package reveals its detail. Clicking "Make Arrangement"
 * on the detail panel triggers the ArrangementDialog (D-E).
 *
 * Pure presentation component — props in, callbacks out.
 *
 * Spec: documentation/steps/steps/03_packages.yaml
 */
export const PackagesStep: React.FC<PackagesStepProps> = ({
  provider,
  packages,
  otherPackages = [],
  selectedPackageId,
  onSelectPackage,
  onArrange,
  onProviderClick,
  onBack,
  error,
  loading = false,
  navigation,
  isPrePlanning = false,
  sx,
}) => {
  const allPackages = [...packages, ...otherPackages];
  const selectedPackage = allPackages.find((p) => p.id === selectedPackageId);
  const hasOtherPackages = otherPackages.length > 0;

  const subheading = isPrePlanning
    ? 'Compare packages to find what suits your wishes. Nothing is committed until you confirm.'
    : 'Each package includes a set of services. You can customise your selections in the next steps.';

  return (
    <WizardLayout
      variant="list-detail"
      navigation={navigation}
      showBackLink
      backLabel="Back"
      onBack={onBack}
      sx={sx}
      secondaryPanel={
        selectedPackage ? (
          <PackageDetail
            name={selectedPackage.name}
            price={selectedPackage.price}
            sections={selectedPackage.sections}
            total={selectedPackage.total}
            extras={selectedPackage.extras}
            terms={selectedPackage.terms}
            onArrange={onArrange}
            arrangeDisabled={loading}
          />
        ) : (
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100%',
              minHeight: 300,
              bgcolor: 'var(--fa-color-brand-50)',
              borderRadius: 2,
              p: 4,
            }}
          >
            <Typography variant="body1" color="text.secondary" sx={{ textAlign: 'center' }}>
              Select a package to see what&apos;s included.
            </Typography>
          </Box>
        )
      }
    >
      {/* Provider compact card — clickable to open provider profile */}
      <Box sx={{ mb: 3 }}>
        <ProviderCardCompact
          name={provider.name}
          location={provider.location}
          imageUrl={provider.imageUrl}
          rating={provider.rating}
          reviewCount={provider.reviewCount}
          onClick={onProviderClick}
        />
      </Box>

      {/* Heading */}
      <Typography variant="h4" component="h1" sx={{ mb: 0.5 }} tabIndex={-1}>
        Choose a funeral package
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
        {subheading}
      </Typography>

      {/* Error message */}
      {error && (
        <Typography
          variant="body2"
          sx={{ mb: 2, color: 'var(--fa-color-text-brand)' }}
          role="alert"
        >
          {error}
        </Typography>
      )}

      {/* ─── Matching packages ─── */}
      {hasOtherPackages && (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1.5,
            mb: 2,
          }}
        >
          <Box
            sx={{
              width: 3,
              height: 20,
              borderRadius: 1,
              bgcolor: 'primary.main',
              flexShrink: 0,
            }}
          />
          <Typography variant="body2" sx={{ fontWeight: 600, color: 'text.primary' }}>
            Matching your preferences
          </Typography>
        </Box>
      )}

      <Box
        role="radiogroup"
        aria-label="Funeral packages"
        sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 3 }}
      >
        {packages.map((pkg) => (
          <ServiceOption
            key={pkg.id}
            name={pkg.name}
            description={pkg.description}
            price={pkg.price}
            selected={selectedPackageId === pkg.id}
            onClick={() => onSelectPackage(pkg.id)}
          />
        ))}

        {packages.length === 0 && (
          <Box sx={{ py: 4, textAlign: 'center' }}>
            <Typography variant="body2" color="text.secondary">
              No packages match your current preferences.
            </Typography>
          </Box>
        )}
      </Box>

      {/* ─── Other packages (passive discovery) ─── */}
      {hasOtherPackages && (
        <>
          <Divider sx={{ mb: 2 }} />
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1.5,
              mb: 2,
            }}
          >
            <Box
              sx={{
                width: 3,
                height: 20,
                borderRadius: 1,
                bgcolor: 'text.secondary',
                flexShrink: 0,
              }}
            />
            <Typography variant="body2" sx={{ fontWeight: 600, color: 'text.secondary' }}>
              Other packages from {provider.name}
            </Typography>
          </Box>
          <Box
            role="radiogroup"
            aria-label={`Other packages from ${provider.name}`}
            sx={{ display: 'flex', flexDirection: 'column', gap: 2, mb: 3, opacity: 0.85 }}
          >
            {otherPackages.map((pkg) => (
              <ServiceOption
                key={pkg.id}
                name={pkg.name}
                description={pkg.description}
                price={pkg.price}
                selected={selectedPackageId === pkg.id}
                onClick={() => onSelectPackage(pkg.id)}
              />
            ))}
          </Box>
        </>
      )}
    </WizardLayout>
  );
};

PackagesStep.displayName = 'PackagesStep';
export default PackagesStep;
