import React, { useId, useState, useRef, useCallback } from 'react';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useTheme } from '@mui/material/styles';
import ShareOutlinedIcon from '@mui/icons-material/ShareOutlined';
import PrintOutlinedIcon from '@mui/icons-material/PrintOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Link } from '../../atoms/Link';
import { WizardLayout } from '../../templates/WizardLayout';
import {
  ComparisonTable,
  COMPARISON_TABLE_COL_WIDTH,
  type ComparisonPackage,
} from '../../organisms/ComparisonTable';
import { ComparisonPackageCard } from '../../molecules/ComparisonPackageCard';
import { ComparisonTabCard } from '../../molecules/ComparisonTabCard';

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

/** Props for the ComparisonPage */
export interface ComparisonPageProps {
  /** User-selected packages to compare (max 3) */
  packages: ComparisonPackage[];
  /** System-recommended package — always shown as an additional column */
  recommendedPackage?: ComparisonPackage;
  /** Called when user clicks CTA on a package */
  onArrange: (packageId: string) => void;
  /** Called when user removes a package from comparison */
  onRemove: (packageId: string) => void;
  /** Called when user clicks Back */
  onBack: () => void;
  /** Called when user clicks Share */
  onShare?: () => void;
  /** Called when user clicks Print */
  onPrint?: () => void;
  /** Navigation bar slot */
  navigation?: React.ReactNode;
  /** MUI sx prop */
  sx?: SxProps<Theme>;
}

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

/**
 * Package comparison page for the FA design system (V2 — production).
 *
 * Desktop: Full ComparisonTable with info card, floating verified badges,
 * section tables with left accent borders. **Recommended package appears as
 * the first (leftmost) column.**
 * Mobile: Tabbed card view with horizontal tab rail. **Recommended package is
 * the first tab in the rail, but the first user-selected package is the
 * initially active tab** — the recommended tab is a suggestion, not the
 * default view.
 *
 * Share + Print utility actions in the page header.
 *
 * See `ComparisonPageV1.tsx` for the archived V1 (recommended-last) layout.
 */
export const ComparisonPage = React.forwardRef<HTMLDivElement, ComparisonPageProps>(
  (
    { packages, recommendedPackage, onArrange, onRemove, onBack, onShare, onPrint, navigation, sx },
    ref,
  ) => {
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const tablistId = useId();
    const railRef = useRef<HTMLDivElement>(null);
    const tabRefs = useRef<(HTMLDivElement | null)[]>([]);

    const allPackages = React.useMemo(() => {
      const result: ComparisonPackage[] = [];
      if (recommendedPackage) {
        result.push({ ...recommendedPackage, isRecommended: true });
      }
      result.push(...packages);
      return result;
    }, [packages, recommendedPackage]);

    // On mobile, default the active tab to the first user-selected package
    // (not the recommended). Recommended is first in the rail as a suggestion.
    const defaultTabIdx = recommendedPackage ? 1 : 0;
    const [activeTabIdx, setActiveTabIdx] = useState(defaultTabIdx);
    const activePackage = allPackages[activeTabIdx] ?? allPackages[0];

    const providerCount = new Set(allPackages.map((p) => p.provider.name)).size;
    const subtitle =
      providerCount > 1
        ? `Comparing ${packages.length} package${packages.length !== 1 ? 's' : ''} from different providers`
        : `Comparing ${packages.length} package${packages.length !== 1 ? 's' : ''}`;

    const hasRecommended = allPackages.some((p) => p.isRecommended);

    const scrollToCenter = useCallback((idx: number) => {
      const tab = tabRefs.current[idx];
      if (tab && railRef.current) {
        const rail = railRef.current;
        const tabCenter = tab.offsetLeft + tab.offsetWidth / 2;
        const railCenter = rail.offsetWidth / 2;
        rail.scrollTo({ left: tabCenter - railCenter, behavior: 'smooth' });
      }
    }, []);

    const handleTabClick = useCallback(
      (idx: number) => {
        setActiveTabIdx(idx);
        scrollToCenter(idx);
      },
      [scrollToCenter],
    );

    // Center the default tab on mount
    React.useEffect(() => {
      // Small delay to allow layout to settle
      const timer = setTimeout(() => scrollToCenter(defaultTabIdx), 50);
      return () => clearTimeout(timer);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // Natural table width = (row-label col) + (pkg col × n), matches page header maxWidth.
    // Page header container reaches this same width so the table's left edge aligns
    // with the page header's left edge when the table overflows horizontally.
    const tableNaturalWidth = COMPARISON_TABLE_COL_WIDTH * (allPackages.length + 1);
    const pageMaxWidth = COMPARISON_TABLE_COL_WIDTH * 4; // fits 3-package case flush

    // Matching horizontal padding between the page header container and the
    // table-zone spacers keeps inner-content left edges aligned on all viewports.
    const edgePadding = { xs: 16, md: 24 };

    return (
      <Box ref={ref} sx={sx}>
        <WizardLayout
          variant={isMobile ? 'wide-form' : 'bleed'}
          navigation={navigation}
          showBackLink={isMobile}
          backLabel="Back"
          onBack={onBack}
        >
          {!isMobile && (
            <>
              {/* Page header zone — centred, bounded to the table's natural width */}
              <Box sx={{ display: 'flex', justifyContent: 'center', width: '100%' }}>
                <Box
                  sx={{
                    width: '100%',
                    maxWidth: pageMaxWidth,
                    px: { xs: `${edgePadding.xs}px`, md: `${edgePadding.md}px` },
                    pt: { xs: 2, md: 3 },
                    pb: { xs: 3, md: 5 },
                  }}
                >
                  <Link
                    component="button"
                    onClick={onBack}
                    underline="hover"
                    sx={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: 0.5,
                      color: 'text.secondary',
                      fontSize: '0.875rem',
                      fontWeight: 500,
                      mb: 2,
                      '&:hover': { color: 'text.primary' },
                    }}
                  >
                    <ArrowBackIcon sx={{ fontSize: 18 }} />
                    Back
                  </Link>
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      justifyContent: 'space-between',
                      gap: 2,
                      flexWrap: 'wrap',
                    }}
                  >
                    <Box>
                      <Typography variant="h2" component="h1" sx={{ mb: 1 }}>
                        Compare packages
                      </Typography>
                      <Typography variant="body1" color="text.secondary" aria-live="polite">
                        {subtitle}
                      </Typography>
                    </Box>

                    {(onShare || onPrint) && (
                      <Box sx={{ display: 'flex', gap: 1, flexShrink: 0 }}>
                        {onShare && (
                          <Button
                            variant="outlined"
                            color="secondary"
                            size="small"
                            startIcon={<ShareOutlinedIcon />}
                            onClick={onShare}
                          >
                            Share
                          </Button>
                        )}
                        {onPrint && (
                          <Button
                            variant="outlined"
                            color="secondary"
                            size="small"
                            startIcon={<PrintOutlinedIcon />}
                            onClick={onPrint}
                          >
                            Print
                          </Button>
                        )}
                      </Box>
                    )}
                  </Box>
                </Box>
              </Box>

              <Divider />

              {/* Table zone — width-matching spacers centre the table when room
                  allows, collapse to the minimum when table is wider than
                  viewport so overflow extends rightward from the page's
                  content column. */}
              <Box
                sx={{
                  display: 'flex',
                  width: 'max-content',
                  minWidth: '100%',
                  py: { xs: 3, md: 5 },
                }}
              >
                <Box
                  aria-hidden
                  sx={{
                    flex: 1,
                    minWidth: { xs: `${edgePadding.xs}px`, md: `${edgePadding.md}px` },
                  }}
                />
                <Box sx={{ flexShrink: 0, width: tableNaturalWidth }}>
                  <ComparisonTable
                    packages={allPackages}
                    onArrange={onArrange}
                    onRemove={onRemove}
                  />
                </Box>
                <Box
                  aria-hidden
                  sx={{
                    flex: 1,
                    minWidth: { xs: `${edgePadding.xs}px`, md: `${edgePadding.md}px` },
                  }}
                />
              </Box>
            </>
          )}

          {/* Mobile: Tab rail + card view */}
          {isMobile && allPackages.length > 0 && (
            <>
              <Box sx={{ mb: 3 }}>
                <Typography variant="h2" component="h1" sx={{ mb: 1 }}>
                  Compare packages
                </Typography>
                <Typography variant="body1" color="text.secondary" aria-live="polite">
                  {subtitle}
                </Typography>
              </Box>

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

              <Typography
                id="comparison-rail-heading"
                variant="label"
                component="h2"
                sx={{ fontWeight: 600, display: 'block', mb: 1.5 }}
              >
                Choose a package to view
              </Typography>
              <Box
                ref={railRef}
                role="tablist"
                id={tablistId}
                aria-labelledby="comparison-rail-heading"
                sx={{
                  display: 'flex',
                  gap: 1.5,
                  overflowX: 'auto',
                  py: 2,
                  px: 2,
                  mx: -2,
                  mb: 1.5,
                  scrollbarWidth: 'none',
                  '&::-webkit-scrollbar': { display: 'none' },
                  WebkitOverflowScrolling: 'touch',
                }}
              >
                {allPackages.map((pkg, idx) => (
                  <ComparisonTabCard
                    key={pkg.id}
                    ref={(el: HTMLDivElement | null) => {
                      tabRefs.current[idx] = el;
                    }}
                    pkg={pkg}
                    isActive={idx === activeTabIdx}
                    hasRecommended={hasRecommended}
                    tabId={`comparison-tab-${idx}`}
                    tabPanelId={`comparison-tabpanel-${idx}`}
                    onClick={() => handleTabClick(idx)}
                  />
                ))}
              </Box>

              {/* Dot indicator — position + count. Purely visual supplement;
                  the tab rail above is the accessible navigation, so dots
                  are aria-hidden and skipped by keyboard tab-order. */}
              <Box
                aria-hidden="true"
                sx={{
                  display: 'flex',
                  justifyContent: 'center',
                  gap: 0.5,
                  mb: 3,
                }}
              >
                {allPackages.map((_, idx) => {
                  const isActive = idx === activeTabIdx;
                  return (
                    <Box
                      key={idx}
                      component="button"
                      type="button"
                      tabIndex={-1}
                      onClick={() => handleTabClick(idx)}
                      sx={{
                        appearance: 'none',
                        border: 0,
                        background: 'transparent',
                        cursor: 'pointer',
                        p: 1,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        '& > span': {
                          display: 'block',
                          width: isActive ? 24 : 8,
                          height: 8,
                          borderRadius: 4,
                          bgcolor: isActive
                            ? 'var(--fa-color-brand-600)'
                            : 'var(--fa-color-neutral-300)',
                          transition: 'width 0.2s ease, background-color 0.2s ease',
                        },
                      }}
                    >
                      <span />
                    </Box>
                  );
                })}
              </Box>

              {activePackage && (
                <Box
                  role="tabpanel"
                  id={`comparison-tabpanel-${activeTabIdx}`}
                  aria-labelledby={`comparison-tab-${activeTabIdx}`}
                >
                  <ComparisonPackageCard pkg={activePackage} onArrange={onArrange} />
                </Box>
              )}
            </>
          )}
        </WizardLayout>
      </Box>
    );
  },
);

ComparisonPage.displayName = 'ComparisonPage';
export default ComparisonPage;
