import React from 'react';
import Box from '@mui/material/Box';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import { WizardLayout } from '../../templates/WizardLayout';
import { ProviderCardCompact } from '../../molecules/ProviderCardCompact';
import { ProviderCard } from '../../molecules/ProviderCard';
import { Badge } from '../../atoms/Badge';
import { Button } from '../../atoms/Button';
import { Typography } from '../../atoms/Typography';
import { Divider } from '../../atoms/Divider';

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

/** A piece of known information about the unverified provider */
export interface ProviderDetail {
  /** Label (e.g. "Estimated pricing") */
  label: string;
  /** Value (e.g. "From approximately $750") */
  value: string;
}

/** A verified provider recommendation */
export interface RecommendedProvider {
  id: string;
  name: string;
  location: string;
  imageUrl?: string;
  logoUrl?: string;
  rating?: number;
  reviewCount?: number;
  startingPrice?: number;
}

/** Props for the UnverifiedProviderStep page */
export interface UnverifiedProviderStepProps {
  /** Provider display name */
  providerName: string;
  /** Provider location */
  providerLocation: string;
  /** Average rating (if available from reviews) */
  providerRating?: number;
  /** Number of reviews */
  providerReviewCount?: number;
  /** Known details — only sections with data are rendered */
  details?: ProviderDetail[];
  /** Callback when "Make an Enquiry" is clicked */
  onEnquire: () => void;
  /** Whether the enquiry is being submitted */
  enquiryLoading?: boolean;
  /** Verified provider recommendations matching the user's search */
  recommendations?: RecommendedProvider[];
  /** Label for the recommendations section (e.g. "near Wollongong") */
  recommendationContext?: string;
  /** Callback when a recommended provider is clicked */
  onSelectRecommendation?: (id: string) => void;
  /** Callback for back navigation */
  onBack: () => void;
  /** Navigation bar */
  navigation?: React.ReactNode;
  /** Progress stepper */
  progressStepper?: React.ReactNode;
  /** Running total widget */
  runningTotal?: React.ReactNode;
  /** MUI sx prop */
  sx?: SxProps<Theme>;
}

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

/**
 * Unverified provider detail page for the FA arrangement wizard.
 *
 * Shown when a user selects an unverified (scraped) provider from
 * the ProvidersStep. Uses the same list-detail layout as PackagesStep
 * for consistency — left panel has provider info + recommendations,
 * right panel has the enquiry CTA.
 *
 * Displays whatever information we have, offers an enquiry CTA,
 * and recommends verified alternatives.
 *
 * Pure presentation component — props in, callbacks out.
 */
export const UnverifiedProviderStep: React.FC<UnverifiedProviderStepProps> = ({
  providerName,
  providerLocation,
  providerRating,
  providerReviewCount,
  details = [],
  onEnquire,
  enquiryLoading = false,
  recommendations = [],
  recommendationContext,
  onSelectRecommendation,
  onBack,
  navigation,
  progressStepper,
  runningTotal,
  sx,
}) => {
  return (
    <WizardLayout
      variant="list-detail"
      navigation={navigation}
      progressStepper={progressStepper}
      runningTotal={runningTotal}
      showBackLink
      backLabel="Back to providers"
      onBack={onBack}
      sx={sx}
      secondaryPanel={
        /* ── Right panel: Enquiry CTA ── */
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            height: '100%',
          }}
        >
          {/* Warm header band — matches PackageDetail pattern */}
          <Box
            sx={{
              bgcolor: 'var(--fa-color-surface-warm)',
              px: 3,
              py: 2.5,
              borderBottom: '1px solid',
              borderColor: 'divider',
            }}
          >
            <Typography variant="overline" color="text.secondary">
              Enquire
            </Typography>
            <Typography variant="h5">{providerName}</Typography>
          </Box>

          {/* Detail rows — whatever we know */}
          <Box sx={{ px: 3, py: 2.5, flex: 1 }}>
            {details.length > 0 ? (
              <Box
                component="dl"
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 2,
                  m: 0,
                  mb: 3,
                  '& dt': { color: 'text.secondary', m: 0, fontSize: '0.75rem' },
                  '& dd': { m: 0, fontWeight: 500 },
                }}
              >
                {details.map((detail) => (
                  <Box key={detail.label}>
                    <Typography component="dt" variant="caption">
                      {detail.label}
                    </Typography>
                    <Typography component="dd" variant="body2">
                      {detail.value}
                    </Typography>
                  </Box>
                ))}
              </Box>
            ) : (
              <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
                Contact this provider directly for pricing and service details.
              </Typography>
            )}

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

            <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
              We&rsquo;ll pass your details along so they can reach out to you directly. No
              commitment required.
            </Typography>

            <Button
              variant="contained"
              size="large"
              onClick={onEnquire}
              loading={enquiryLoading}
              fullWidth
            >
              Make an Enquiry
            </Button>

            {details.length > 0 && (
              <Typography variant="caption" color="text.secondary" sx={{ mt: 2, display: 'block' }}>
                Based on publicly available information. Pricing and services may vary.
              </Typography>
            )}
          </Box>
        </Box>
      }
    >
      {/* ── Left panel: Provider info + recommendations ── */}

      {/* Provider compact card */}
      <Box sx={{ mb: 1.5 }}>
        <ProviderCardCompact
          name={providerName}
          location={providerLocation}
          rating={providerRating}
          reviewCount={providerReviewCount}
        />
      </Box>

      <Box sx={{ mb: 3 }}>
        <Badge variant="soft" color="default" size="medium" icon={<InfoOutlinedIcon />}>
          Listing
        </Badge>
      </Box>

      {/* Heading */}
      <Typography variant="h4" component="h1" sx={{ mb: 0.5 }} tabIndex={-1}>
        About this provider
      </Typography>
      <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
        This provider hasn&rsquo;t partnered with us yet. We have limited information, but you can
        still enquire directly.
      </Typography>

      {/* Available information (inline, if any) */}
      {details.length > 0 && (
        <Box
          sx={{
            bgcolor: 'var(--fa-color-surface-subtle)',
            borderRadius: 2,
            p: 2.5,
            mb: 3,
          }}
        >
          <Box
            component="dl"
            sx={{
              display: 'grid',
              gridTemplateColumns: { xs: '1fr', sm: 'auto 1fr' },
              gap: 1.5,
              m: 0,
              '& dt': { color: 'text.secondary', m: 0 },
              '& dd': { m: 0, fontWeight: 500 },
            }}
          >
            {details.map((detail) => (
              <React.Fragment key={detail.label}>
                <Typography component="dt" variant="body2">
                  {detail.label}
                </Typography>
                <Typography component="dd" variant="body2">
                  {detail.value}
                </Typography>
              </React.Fragment>
            ))}
          </Box>
        </Box>
      )}

      {/* ── Verified recommendations ── */}
      {recommendations.length > 0 && (
        <>
          <Divider sx={{ mb: 3 }} />

          <Typography variant="h6" sx={{ mb: 0.5 }}>
            Verified providers{recommendationContext ? ` ${recommendationContext}` : ''}
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            Full online arrangement with transparent pricing
          </Typography>

          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              gap: 2,
              mb: 3,
            }}
          >
            {recommendations.map((provider) => (
              <ProviderCard
                key={provider.id}
                name={provider.name}
                location={provider.location}
                verified
                imageUrl={provider.imageUrl}
                logoUrl={provider.logoUrl}
                rating={provider.rating}
                reviewCount={provider.reviewCount}
                startingPrice={provider.startingPrice}
                onClick={
                  onSelectRecommendation ? () => onSelectRecommendation(provider.id) : undefined
                }
              />
            ))}
          </Box>
        </>
      )}
    </WizardLayout>
  );
};

UnverifiedProviderStep.displayName = 'UnverifiedProviderStep';
export default UnverifiedProviderStep;
