import React from 'react';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import type { SxProps, Theme } from '@mui/material/styles';
import { Typography } from '../../atoms/Typography';
import { Card } from '../../atoms/Card';
import { ComparisonColumnCard } from '../../molecules/ComparisonColumnCard';

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

/** Cell value types for the comparison table */
export type ComparisonCellValue =
  | { type: 'price'; amount: number }
  | { type: 'allowance'; amount: number }
  | { type: 'complimentary' }
  | { type: 'included' }
  | { type: 'poa' }
  | { type: 'unknown' }
  | { type: 'unavailable' };

export interface ComparisonLineItem {
  name: string;
  info?: string;
  value: ComparisonCellValue;
}

export interface ComparisonSection {
  heading: string;
  items: ComparisonLineItem[];
}

export interface ComparisonProvider {
  name: string;
  location: string;
  logoUrl?: string;
  rating?: number;
  reviewCount?: number;
  verified: boolean;
}

export interface ComparisonPackage {
  id: string;
  name: string;
  price: number;
  provider: ComparisonProvider;
  sections: ComparisonSection[];
  isRecommended?: boolean;
  itemizedAvailable?: boolean;
}

export interface ComparisonTableProps {
  packages: ComparisonPackage[];
  onArrange: (packageId: string) => void;
  onRemove: (packageId: string) => void;
  sx?: SxProps<Theme>;
}

// ─── Helpers ────────────────────────────────────────────────────────────────

function formatPrice(amount: number): string {
  return `$${amount.toLocaleString('en-AU', { minimumFractionDigits: amount % 1 !== 0 ? 2 : 0 })}`;
}

/**
 * Inline icon + label wrapper with optically aligned centres.
 *
 * body2's line-height adds vertical padding above/below the glyphs. Flex
 * centring then aligns geometric centres, which puts the icon slightly
 * above the text's visual centre. Setting `lineHeight: 1` on the row
 * collapses the text line-box to the font size so geometric and visual
 * centres match.
 */
function CellIconText({
  icon,
  iconPosition = 'leading',
  color,
  children,
}: {
  icon: React.ReactNode;
  iconPosition?: 'leading' | 'trailing';
  color: string;
  children: React.ReactNode;
}) {
  return (
    <Box
      sx={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 0.5,
        lineHeight: 1,
      }}
    >
      {iconPosition === 'leading' && icon}
      <Typography variant="body2" sx={{ color, fontWeight: 500, lineHeight: 1 }} component="span">
        {children}
      </Typography>
      {iconPosition === 'trailing' && icon}
    </Box>
  );
}

/** Sections where a missing item is better expressed as "Not Included"
 * than a bare em-dash — these are opt-in items, so absence is meaningful. */
const OPTIONAL_SECTION_HEADINGS = new Set(['Optionals', 'Extras']);

function CellValue({
  value,
  sectionHeading,
}: {
  value: ComparisonCellValue;
  sectionHeading: string;
}) {
  switch (value.type) {
    case 'price':
      return (
        <Typography variant="body2" sx={{ fontWeight: 600, color: 'text.primary' }}>
          {formatPrice(value.amount)}
        </Typography>
      );
    case 'allowance':
      return (
        <Typography variant="body2" sx={{ fontWeight: 600, color: 'text.primary' }}>
          {formatPrice(value.amount)}*
        </Typography>
      );
    case 'complimentary':
      return (
        <CellIconText
          color="var(--fa-color-feedback-success)"
          icon={
            <CheckCircleOutlineIcon
              sx={{ fontSize: 16, color: 'var(--fa-color-feedback-success)' }}
              aria-hidden
            />
          }
        >
          Complimentary
        </CellIconText>
      );
    case 'included':
      return (
        <CellIconText
          color="var(--fa-color-feedback-success)"
          icon={
            <CheckCircleOutlineIcon
              sx={{ fontSize: 16, color: 'var(--fa-color-feedback-success)' }}
              aria-hidden
            />
          }
        >
          Included
        </CellIconText>
      );
    case 'poa':
      return (
        <Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
          Price On Application
        </Typography>
      );
    case 'unknown':
      return (
        <CellIconText
          color="var(--fa-color-neutral-500)"
          iconPosition="trailing"
          icon={
            <InfoOutlinedIcon
              sx={{ fontSize: 14, color: 'var(--fa-color-neutral-500)' }}
              aria-hidden
            />
          }
        >
          Unknown
        </CellIconText>
      );
    case 'unavailable':
      if (OPTIONAL_SECTION_HEADINGS.has(sectionHeading)) {
        return (
          <Typography
            variant="body2"
            sx={{ color: 'var(--fa-color-neutral-500)', fontWeight: 500 }}
          >
            Not Included
          </Typography>
        );
      }
      return (
        <Typography variant="body2" sx={{ color: 'var(--fa-color-neutral-400)' }}>
          —
        </Typography>
      );
  }
}

function buildMergedSections(
  packages: ComparisonPackage[],
): { heading: string; items: { name: string; info?: string }[] }[] {
  const sectionMap = new Map<string, { name: string; info?: string }[]>();
  const sectionOrder: string[] = [];

  for (const pkg of packages) {
    if (pkg.itemizedAvailable === false) continue;
    for (const section of pkg.sections) {
      if (!sectionMap.has(section.heading)) {
        sectionMap.set(section.heading, []);
        sectionOrder.push(section.heading);
      }
      const existing = sectionMap.get(section.heading)!;
      for (const item of section.items) {
        if (!existing.some((e) => e.name === item.name)) {
          existing.push({ name: item.name, info: item.info });
        }
      }
    }
  }

  return sectionOrder.map((heading) => ({
    heading,
    items: sectionMap.get(heading) ?? [],
  }));
}

function lookupValue(
  pkg: ComparisonPackage,
  sectionHeading: string,
  itemName: string,
): ComparisonCellValue {
  if (pkg.itemizedAvailable === false) return { type: 'unavailable' };
  const section = pkg.sections.find((s) => s.heading === sectionHeading);
  if (!section) return { type: 'unavailable' };
  const item = section.items.find((i) => i.name === itemName);
  if (!item) return { type: 'unavailable' };
  return item.value;
}

/** Section heading with left accent border */
function SectionHeading({ children }: { children: React.ReactNode }) {
  return (
    <Box
      sx={{
        bgcolor: 'var(--fa-color-surface-subtle)',
        px: 3,
        py: 2.5,
        borderLeft: '3px solid',
        borderLeftColor: 'var(--fa-color-brand-500)',
      }}
    >
      <Typography variant="h6" component="h3">
        {children}
      </Typography>
    </Box>
  );
}

/** Reusable bordered table wrapper */
const tableSx = {
  display: 'grid',
  border: '1px solid',
  borderColor: 'divider',
  borderRadius: 'var(--fa-card-border-radius-default)',
  overflow: 'hidden',
  bgcolor: 'background.paper',
};

/**
 * Fixed column width for both the row-label column and each package column.
 * Natural table width = COMPARISON_TABLE_COL_WIDTH × (packages.length + 1).
 * Exposed so ComparisonPage can size its width-matching page header container
 * to align left edges with the table on horizontal overflow.
 */
export const COMPARISON_TABLE_COL_WIDTH = 300;

/** z-index scale for sticky layers inside the table. */
const Z_HEADER_ROW = 30;
const Z_STICKY_LEFT = 20;
const Z_STICKY_LEFT_SECTION = 25; // section heading left cell above body cells

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

/**
 * Side-by-side package comparison table for the FA design system.
 *
 * Info card in top-left column, floating verified badges above cards,
 * section tables with left accent borders, no reviews table (rating in cards).
 *
 * Desktop only — ComparisonPage handles the mobile card view.
 */
export const ComparisonTable = React.forwardRef<HTMLDivElement, ComparisonTableProps>(
  ({ packages, onArrange, onRemove, sx }, ref) => {
    const mergedSections = buildMergedSections(packages);
    const colCount = packages.length + 1;
    const gridCols = `${COMPARISON_TABLE_COL_WIDTH}px repeat(${packages.length}, ${COMPARISON_TABLE_COL_WIDTH}px)`;
    const recommendedColIdx = packages.findIndex((p) => p.isRecommended);

    return (
      <Box
        ref={ref}
        role="table"
        aria-label="Package comparison"
        sx={[
          {
            display: { xs: 'none', md: 'block' },
            width: COMPARISON_TABLE_COL_WIDTH * colCount,
          },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
      >
        {/* ── Package header cards ── */}
        <Box
          role="row"
          sx={{
            display: 'grid',
            gridTemplateColumns: gridCols,
            mb: 4,
            alignItems: 'stretch',
            pt: 3, // Room for floating verified badges
          }}
        >
          {/* Info card — sticky-left, matches the row-label column below */}
          <Box
            sx={{
              position: 'sticky',
              left: 0,
              zIndex: Z_HEADER_ROW,
              bgcolor: 'background.default',
              px: 2,
            }}
          >
            <Card
              role="columnheader"
              variant="elevated"
              padding="default"
              sx={{
                bgcolor: 'var(--fa-color-surface-subtle)',
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'flex-start',
                border: 'none',
                boxShadow: 'none',
              }}
            >
              <Typography variant="label" sx={{ fontWeight: 700, display: 'block', mb: 1 }}>
                Package Comparison
              </Typography>
              <Typography
                variant="body2"
                color="text.secondary"
                sx={{ lineHeight: 1.5, display: 'block' }}
              >
                Review and compare features side-by-side to find the right fit.
              </Typography>
            </Card>
          </Box>

          {packages.map((pkg) => (
            <Box key={pkg.id} sx={{ px: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
              <ComparisonColumnCard
                pkg={pkg}
                onArrange={onArrange}
                onRemove={onRemove}
                sx={{ flex: 1 }}
              />
            </Box>
          ))}
        </Box>

        {/* ── Section tables (each separate with left accent headings) ── */}
        {mergedSections.map((section) => (
          <Box key={section.heading} sx={{ ...tableSx, gridTemplateColumns: gridCols, mb: 3 }}>
            {/* Section heading row — left cell sticky so label stays visible on horizontal scroll */}
            <Box
              role="row"
              sx={{
                gridColumn: `1 / ${colCount + 1}`,
                display: 'grid',
                gridTemplateColumns: 'subgrid',
              }}
            >
              <Box
                sx={{
                  position: 'sticky',
                  left: 0,
                  zIndex: Z_STICKY_LEFT_SECTION,
                  gridColumn: '1 / 2',
                }}
              >
                <SectionHeading>{section.heading}</SectionHeading>
              </Box>
              {/* Background continuation for the remaining columns so they
                  share the heading's surface-subtle wash. */}
              <Box
                aria-hidden
                sx={{
                  gridColumn: `2 / ${colCount + 1}`,
                  bgcolor: 'var(--fa-color-surface-subtle)',
                }}
              />
            </Box>

            {section.items.map((item) => (
              <Box
                key={item.name}
                role="row"
                sx={{
                  gridColumn: `1 / ${colCount + 1}`,
                  display: 'grid',
                  gridTemplateColumns: 'subgrid',
                  // Tiered hover: base cells go to surface-subtle, recommended
                  // column cells inherit a warmer surface-warm tint on row hover.
                  '&:hover .comparison-cell': {
                    bgcolor: 'var(--fa-color-surface-subtle)',
                  },
                  '&:hover .comparison-cell--recommended': {
                    bgcolor: 'var(--fa-color-surface-warm)',
                  },
                }}
              >
                {/* Row-label cell — sticky-left */}
                <Box
                  role="cell"
                  className="comparison-cell comparison-cell--label"
                  sx={{
                    position: 'sticky',
                    left: 0,
                    zIndex: Z_STICKY_LEFT,
                    bgcolor: 'background.paper',
                    px: 3,
                    py: 2,
                    borderTop: '1px solid',
                    borderColor: 'divider',
                    transition: 'background-color 0.15s ease',
                  }}
                >
                  <Typography variant="body2" color="text.secondary" component="span">
                    {item.name}
                  </Typography>
                  {item.info && (
                    <Box component="span" sx={{ whiteSpace: 'nowrap' }}>
                      {'\u00A0'}
                      <Tooltip title={item.info} arrow placement="top">
                        <InfoOutlinedIcon
                          aria-label={`More information about ${item.name}`}
                          sx={{
                            fontSize: 14,
                            color: 'var(--fa-color-neutral-400)',
                            cursor: 'help',
                            verticalAlign: 'middle',
                          }}
                        />
                      </Tooltip>
                    </Box>
                  )}
                </Box>

                {packages.map((pkg, idx) => {
                  const isRecommended = idx === recommendedColIdx;
                  return (
                    <Box
                      key={pkg.id}
                      role="cell"
                      className={
                        'comparison-cell' + (isRecommended ? ' comparison-cell--recommended' : '')
                      }
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        px: 2,
                        py: 2,
                        borderTop: '1px solid',
                        borderColor: 'divider',
                        borderLeft: '1px solid',
                        borderLeftColor: 'divider',
                        transition: 'background-color 0.15s ease',
                        // Resting tint for the recommended column so it reads
                        // as the default column even without hover.
                        ...(isRecommended && {
                          bgcolor:
                            'color-mix(in srgb, var(--fa-color-surface-warm) 50%, transparent)',
                        }),
                      }}
                    >
                      <CellValue
                        value={lookupValue(pkg, section.heading, item.name)}
                        sectionHeading={section.heading}
                      />
                    </Box>
                  );
                })}
              </Box>
            ))}
          </Box>
        ))}

        {packages.some((p) => p.itemizedAvailable === false) && mergedSections.length > 0 && (
          <Typography variant="caption" color="text.secondary" sx={{ fontStyle: 'italic' }}>
            * Some providers have not provided an itemised pricing breakdown. Their items are shown
            as "—" above.
          </Typography>
        )}
      </Box>
    );
  },
);

ComparisonTable.displayName = 'ComparisonTable';
export default ComparisonTable;
