import { Check, X } from 'lucide-react';

import * as React from 'react';

import { InfoTooltip } from '@/Components/ui/info-tooltip';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { cn } from '@/lib/utils';

interface ComparisonFeature {
  feature: string;
  rankwiz: boolean | string;
  competitor: boolean | string;
  group?: 'differentiator' | 'shared' | 'competitor_strength';
  /** Link to competitor's feature page as evidence for this claim */
  sourceUrl?: string;
  /** Optional tooltip explaining the feature — shown as an info icon next to the feature name */
  tooltip?: string;
}

interface ComparisonTableProps {
  features: ComparisonFeature[];
  competitorName: string;
  className?: string;
}

export const ComparisonTable = React.forwardRef<HTMLTableElement, ComparisonTableProps>(
  ({ features, competitorName, className }, ref) => {
    const renderValue = (value: boolean | string, isRankwiz: boolean, sourceUrl?: string) => {
      const citation =
        !isRankwiz && sourceUrl ? (
          <a
            href={sourceUrl}
            target="_blank"
            rel="noopener noreferrer"
            aria-label="Source"
            className="ml-0.5 align-super text-[0.65rem] text-muted-foreground hover:text-primary"
          >
            [↗]
          </a>
        ) : null;

      if (typeof value === 'boolean') {
        if (value) {
          return (
            <div className="flex items-center justify-center">
              <Check
                className={cn('h-5 w-5', isRankwiz ? 'text-primary' : 'text-muted-foreground')}
                aria-label="Included"
              />
              {citation}
            </div>
          );
        }
        return (
          <div className="flex items-center justify-center">
            <X className="h-5 w-5 text-muted-foreground" aria-label="Not included" />
            {citation}
          </div>
        );
      }
      return (
        <div className="text-center text-sm">
          {value}
          {citation}
        </div>
      );
    };

    const GROUP_LABELS: Record<string, string> = {
      differentiator: 'Where RankWiz leads',
      shared: 'Shared capabilities',
      competitor_strength: `Where ${competitorName} shines`,
    };

    const hasGroups = features.some((f) => f.group);

    const rows: React.ReactNode[] = [];
    let lastGroup: string | undefined;

    for (let i = 0; i < features.length; i++) {
      const row = features[i];
      if (hasGroups && row.group && row.group !== lastGroup) {
        lastGroup = row.group;
        rows.push(
          <TableRow key={`group-${row.group}`}>
            <TableCell
              colSpan={3}
              className="bg-muted/50 py-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground"
            >
              {GROUP_LABELS[row.group] ?? row.group}
            </TableCell>
          </TableRow>,
        );
      }
      rows.push(
        <TableRow key={i}>
          <TableCell className="text-xs font-medium sm:text-sm">
            <span className="inline-flex items-center gap-1">
              {row.feature}
              {row.tooltip && (
                <InfoTooltip content={row.tooltip} iconClassName="h-3 w-3" side="right" />
              )}
            </span>
          </TableCell>
          <TableCell className="bg-primary/5">{renderValue(row.rankwiz, true)}</TableCell>
          <TableCell>{renderValue(row.competitor, false, row.sourceUrl)}</TableCell>
        </TableRow>,
      );
    }

    return (
      <div className={cn('overflow-x-auto', className)}>
        <Table ref={ref}>
          <TableHeader>
            <TableRow>
              <TableHead scope="col" className="w-1/2 text-xs sm:text-sm">
                Feature
              </TableHead>
              <TableHead
                scope="col"
                className="w-1/4 text-center text-xs font-semibold text-primary sm:text-sm"
              >
                RankWiz
              </TableHead>
              <TableHead
                scope="col"
                className="w-1/4 text-center text-xs text-muted-foreground sm:text-sm"
              >
                {competitorName}
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>{rows}</TableBody>
        </Table>
      </div>
    );
  },
);
ComparisonTable.displayName = 'ComparisonTable';
