import React from 'react';
import Box from '@mui/material/Box';
import Tooltip from '@mui/material/Tooltip';
import StarRoundedIcon from '@mui/icons-material/StarRounded';
import VerifiedOutlinedIcon from '@mui/icons-material/VerifiedOutlined';
import type { SxProps, Theme } from '@mui/material/styles';
import { Typography } from '../../atoms/Typography';
import { Button } from '../../atoms/Button';
import { Badge } from '../../atoms/Badge';
import { Card } from '../../atoms/Card';
import { Divider } from '../../atoms/Divider';
import { Link } from '../../atoms/Link';
import type { ComparisonPackage } from '../../organisms/ComparisonTable';

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

export interface ComparisonColumnCardProps {
  /** Package data to render — same shape used by ComparisonTable */
  pkg: ComparisonPackage;
  /** Called when the user clicks the CTA (Make Arrangement / Make Enquiry) */
  onArrange: (packageId: string) => void;
  /** Called when the user clicks Remove — hidden when not provided or for recommended packages */
  onRemove?: (packageId: string) => void;
  /** MUI sx prop for outer wrapper overrides */
  sx?: SxProps<Theme>;
}

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

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

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

/**
 * Desktop column header card for the ComparisonTable.
 *
 * Shows provider info (verified/recommended badge, name, location, rating),
 * package name, total price, CTA button, and optional Remove link. The badge
 * floats above the card's top edge — "Recommended" (primary fill) replaces
 * "Verified" (soft) when the package is recommended. Recommended packages
 * also get a warm selected card state with a brand-600 border.
 *
 * Used as the sticky header for each column in the desktop comparison grid.
 * Mobile comparison uses ComparisonPackageCard instead.
 */
export const ComparisonColumnCard = React.forwardRef<HTMLDivElement, ComparisonColumnCardProps>(
  ({ pkg, onArrange, onRemove, sx }, ref) => {
    return (
      <Box
        ref={ref}
        role="columnheader"
        aria-label={pkg.isRecommended ? `${pkg.name} (Recommended)` : pkg.name}
        sx={[
          {
            position: 'relative',
            overflow: 'visible',
            display: 'flex',
            flexDirection: 'column',
          },
          ...(Array.isArray(sx) ? sx : [sx]),
        ]}
      >
        {/* Floating badge — Recommended (primary fill) takes priority over Verified (soft) */}
        {(pkg.isRecommended || pkg.provider.verified) && (
          <Badge
            color="brand"
            variant={pkg.isRecommended ? 'filled' : 'soft'}
            size="medium"
            icon={
              pkg.isRecommended ? (
                <StarRoundedIcon sx={{ fontSize: 16 }} />
              ) : (
                <VerifiedOutlinedIcon sx={{ fontSize: 16 }} />
              )
            }
            sx={{
              position: 'absolute',
              top: -13,
              left: '50%',
              transform: 'translateX(-50%)',
              zIndex: 1,
              boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
            }}
          >
            {pkg.isRecommended ? 'Recommended' : 'Verified'}
          </Badge>
        )}

        <Card
          variant="outlined"
          selected={pkg.isRecommended}
          padding="none"
          sx={{
            overflow: 'hidden',
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            ...(pkg.isRecommended && {
              borderColor: 'var(--fa-color-brand-600)',
            }),
          }}
        >
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              textAlign: 'center',
              px: 2.5,
              pt: 5,
              pb: 3,
              gap: 1,
              flex: 1,
            }}
          >
            {/* Provider name — always reserves space for 2 lines (via minHeight),
                content bottom-aligned so single-line names sit flush with the
                next item below rather than floating high in the slot. */}
            <Box
              sx={{
                display: 'flex',
                alignItems: 'flex-end',
                justifyContent: 'center',
                gap: 0.75,
                maxWidth: '100%',
                minHeight: 36, // 2 × (14px label × 1.286 line-height)
              }}
            >
              {pkg.isRecommended && (
                <VerifiedOutlinedIcon
                  sx={{
                    fontSize: 16,
                    color: 'var(--fa-color-brand-600)',
                    flexShrink: 0,
                    mb: '2px',
                  }}
                  aria-label="Verified provider"
                />
              )}
              <Tooltip
                title={pkg.provider.name}
                arrow
                placement="top"
                disableHoverListener={pkg.provider.name.length < 50}
              >
                <Typography
                  variant="label"
                  sx={{
                    fontWeight: 600,
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    minWidth: 0,
                  }}
                >
                  {pkg.provider.name}
                </Typography>
              </Tooltip>
            </Box>

            {/* Location */}
            <Typography variant="caption" color="text.secondary">
              {pkg.provider.location}
            </Typography>

            {/* Rating (or dash placeholder to keep card heights consistent) */}
            {pkg.provider.rating != null ? (
              <Box sx={{ display: 'inline-flex', alignItems: 'center', gap: 0.5 }}>
                <StarRoundedIcon
                  sx={{ fontSize: 16, color: 'var(--fa-color-brand-500)' }}
                  aria-hidden
                />
                <Typography variant="body2" color="text.secondary">
                  {pkg.provider.rating}
                  {pkg.provider.reviewCount != null && ` (${pkg.provider.reviewCount})`}
                </Typography>
              </Box>
            ) : (
              <Typography variant="body2" color="text.secondary" aria-label="No reviews yet">
                —
              </Typography>
            )}

            <Divider sx={{ width: '100%', my: 1.5 }} />

            <Typography variant="h6" component="p">
              {pkg.name}
            </Typography>

            {/* Price subgroup — tighter internal spacing than the outer gap
                so the label sits close to the amount it describes. */}
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: 0.25,
              }}
            >
              <Typography variant="caption" color="text.secondary">
                Total package price
              </Typography>
              <Typography variant="h5" sx={{ color: 'primary.main', fontWeight: 700 }}>
                {formatPrice(pkg.price)}
              </Typography>
            </Box>

            {/* Spacer pushes CTA to bottom across all cards */}
            <Box sx={{ flex: 1 }} />

            <Button
              variant={pkg.provider.verified ? 'contained' : 'soft'}
              color={pkg.provider.verified ? 'primary' : 'secondary'}
              size="medium"
              onClick={() => onArrange(pkg.id)}
              sx={{ px: 4 }}
            >
              {pkg.provider.verified ? 'Make Arrangement' : 'Make Enquiry'}
            </Button>

            {/* Always render the same Link element; hide when no Remove action
                applies (recommended or no handler). Keeps the footer row
                identical across all cards so CTAs align. */}
            {(() => {
              const canRemove = !pkg.isRecommended && !!onRemove;
              return (
                <Link
                  component="button"
                  variant="caption"
                  color="text.secondary"
                  underline="hover"
                  onClick={canRemove ? () => onRemove!(pkg.id) : undefined}
                  tabIndex={canRemove ? 0 : -1}
                  aria-hidden={!canRemove}
                  sx={{
                    ...(!canRemove && { visibility: 'hidden', pointerEvents: 'none' }),
                  }}
                >
                  Remove
                </Link>
              );
            })()}
          </Box>
        </Card>
      </Box>
    );
  },
);

ComparisonColumnCard.displayName = 'ComparisonColumnCard';
export default ComparisonColumnCard;
