// components/sections/ComparisonTable.tsx
// Horizontal scrollable comparison matrix with pagination and theme variants
'use client';

import { useState } from 'react';
import { Star, ChevronLeft, ChevronRight } from 'lucide-react';
import Link from 'next/link';
import { getLinkAttributes, type LinkTarget, type LinkRel } from '@/lib/puck/linkHelpers';

// --- Types ---
interface ComparisonItem {
  name: string;
  logo: string;
  rank: number;
  rating: number;
  ctaText: string;
  ctaUrl: string;
  // Positional attribute values
  attr1?: string;
  attr2?: string;
  attr3?: string;
  attr4?: string;
  attr5?: string;
  attr6?: string;
  attr7?: string;
  attr8?: string;
}

interface ComparisonAttribute {
  label: string;
}

type ThemeKey = 'default' | 'cards' | 'compact' | 'ocean' | 'forest';

interface ThemeStyles {
  headerBg: string;
  headerLabel: string;
  rankBadge: (rank: number) => string;
  starFill: string;
  starEmpty: string;
  attrLabelBg: string;
  evenRow: string;
  oddRow: string;
  rowBorder: string;
  cellText: string;
  ctaBtn: string;
  paginationActive: string;
  paginationInactive: string;
  outerBorder: string;
}

const THEMES: Record<ThemeKey, ThemeStyles> = {
  default: {
    headerBg: 'bg-white',
    headerLabel: 'bg-slate-50 text-slate-600',
    rankBadge: (rank) =>
      rank === 1 ? 'bg-crimson-red text-white'
      : rank === 2 ? 'bg-orange-500 text-white'
      : rank === 3 ? 'bg-slate-800 text-white'
      : 'bg-slate-100 text-slate-500',
    starFill: 'fill-amber-400 text-amber-400',
    starEmpty: 'text-slate-200',
    attrLabelBg: 'bg-slate-50/80',
    evenRow: 'bg-white',
    oddRow: 'bg-slate-50',
    rowBorder: 'border-slate-200',
    cellText: 'text-slate-700',
    ctaBtn: 'bg-crimson-red text-white hover:bg-hover-red',
    paginationActive: 'bg-crimson-red text-white',
    paginationInactive: 'bg-slate-100 text-slate-600 hover:bg-slate-200',
    outerBorder: 'border border-slate-200',
  },
  cards: {
    headerBg: 'bg-gradient-to-b from-orange-50 to-white',
    headerLabel: 'bg-slate-50 text-slate-600',
    rankBadge: (rank) =>
      rank === 1 ? 'bg-gradient-to-br from-orange-500 to-red-500 text-white'
      : rank === 2 ? 'bg-gradient-to-br from-amber-400 to-orange-400 text-white'
      : rank === 3 ? 'bg-gradient-to-br from-yellow-300 to-amber-300 text-amber-900'
      : 'bg-orange-50 text-orange-600',
    starFill: 'fill-orange-400 text-orange-400',
    starEmpty: 'text-orange-200',
    attrLabelBg: 'bg-slate-50/90',
    evenRow: 'bg-white',
    oddRow: 'bg-orange-50/30',
    rowBorder: 'border-orange-100',
    cellText: 'text-slate-700',
    ctaBtn: 'bg-gradient-to-r from-orange-500 to-red-500 text-white hover:from-orange-600 hover:to-red-600 shadow-lg shadow-orange-500/20',
    paginationActive: 'bg-orange-500 text-white',
    paginationInactive: 'bg-orange-50 text-orange-600 hover:bg-orange-100',
    outerBorder: 'border border-orange-200 shadow-sm',
  },
  compact: {
    headerBg: 'bg-white',
    headerLabel: 'bg-slate-800 text-slate-200',
    rankBadge: (rank) =>
      rank === 1 ? 'bg-slate-800 text-amber-300'
      : rank === 2 ? 'bg-slate-600 text-slate-100'
      : rank === 3 ? 'bg-slate-400 text-white'
      : 'bg-slate-100 text-slate-500',
    starFill: 'fill-amber-400 text-amber-400',
    starEmpty: 'text-slate-200',
    attrLabelBg: 'bg-slate-800 text-white',
    evenRow: 'bg-white',
    oddRow: 'bg-slate-50',
    rowBorder: 'border-slate-100',
    cellText: 'text-slate-600',
    ctaBtn: 'bg-emerald-600 text-white hover:bg-emerald-700 shadow-md shadow-emerald-600/20',
    paginationActive: 'bg-slate-800 text-white',
    paginationInactive: 'bg-slate-100 text-slate-600 hover:bg-slate-200',
    outerBorder: 'border border-slate-200 shadow-sm ring-1 ring-slate-100',
  },

  ocean: {
    headerBg: 'bg-gradient-to-b from-blue-50 to-white',
    headerLabel: 'bg-blue-50 text-blue-700',
    rankBadge: (rank) =>
      rank === 1 ? 'bg-gradient-to-br from-blue-600 to-indigo-600 text-white'
      : rank === 2 ? 'bg-gradient-to-br from-cyan-500 to-blue-500 text-white'
      : rank === 3 ? 'bg-gradient-to-br from-sky-400 to-cyan-400 text-white'
      : 'bg-blue-50 text-blue-600',
    starFill: 'fill-blue-500 text-blue-500',
    starEmpty: 'text-blue-200',
    attrLabelBg: 'bg-blue-50/90',
    evenRow: 'bg-white',
    oddRow: 'bg-blue-50/30',
    rowBorder: 'border-blue-100',
    cellText: 'text-slate-700',
    ctaBtn: 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:from-blue-700 hover:to-indigo-700 shadow-lg shadow-blue-600/20',
    paginationActive: 'bg-blue-600 text-white',
    paginationInactive: 'bg-blue-50 text-blue-600 hover:bg-blue-100',
    outerBorder: 'border border-blue-200 shadow-sm',
  },

  forest: {
    headerBg: 'bg-gradient-to-b from-emerald-50 to-white',
    headerLabel: 'bg-emerald-50 text-emerald-700',
    rankBadge: (rank) => rank <= 3 ? 'bg-gradient-to-r from-emerald-500 to-teal-500 text-white' : 'bg-emerald-100 text-emerald-700',
    starFill: 'fill-emerald-400 text-emerald-400',
    starEmpty: 'fill-slate-200 text-slate-200',
    attrLabelBg: 'bg-emerald-50/50',
    evenRow: 'bg-white',
    oddRow: 'bg-emerald-50/30',
    rowBorder: 'border-b border-emerald-100',
    cellText: 'text-slate-700',
    ctaBtn: 'bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white shadow-sm',
    paginationActive: 'bg-emerald-600 text-white',
    paginationInactive: 'bg-emerald-50 text-emerald-600 hover:bg-emerald-100',
    outerBorder: 'border border-emerald-200 shadow-sm',
  },
};

// --- Rating Stars ---
function RatingStars({ rating, t }: { rating: number; t: ThemeStyles }) {
  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star
          key={star}
          className={`w-3.5 h-3.5 ${star <= Math.round(rating) ? t.starFill : t.starEmpty}`}
        />
      ))}
      <span className="ml-1 text-xs font-semibold text-white">{rating}</span>
    </div>
  );
}

// --- Props ---
interface ComparisonTableProps {
  sectionTitle: string;
  sectionSubtitle?: string;
  attributes: ComparisonAttribute[];
  items: ComparisonItem[];
  itemsPerPage?: number;
  theme?: ThemeKey;
  openInNewTab?: LinkTarget;
  relAttribute?: LinkRel;
  anchorId?: string;
}

// --- Main Component ---
export function ComparisonTable({ sectionTitle, sectionSubtitle, attributes, items, itemsPerPage = 5, theme = 'default', openInNewTab = 'new', relAttribute = 'sponsored', anchorId }: ComparisonTableProps) {
  const [page, setPage] = useState(0);
  const t = THEMES[theme] || THEMES.default;
  const linkAttrs = getLinkAttributes({ openInNewTab, relAttribute });

  const safeAttributes = attributes && attributes.length > 0 ? attributes : [];
  const safeItems = items && items.length > 0 ? items : [];

  const normalizedItems = safeItems
    .map(item => ({ ...item, name: item.name?.trim() || '未登録アイテム' }));

  const totalPages = Math.ceil(normalizedItems.length / itemsPerPage);
  const pagedItems = normalizedItems.slice(page * itemsPerPage, (page + 1) * itemsPerPage);
  const showPagination = totalPages > 1;

  if (safeAttributes.length === 0 || normalizedItems.length === 0) {
    return (
      <section id={anchorId || undefined} className="w-full py-12 md:py-16">
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {sectionTitle && (
          <h2 className="text-2xl font-bold text-white mb-4">{sectionTitle}</h2>
        )}
        <div className="text-center py-8 text-text-light-gray italic border border-soft-gray-border/30 rounded-xl"></div>
      </div>
      </section>
    );
  }

  return (
    <section id={anchorId || undefined} className="w-full py-12 md:py-16">
    <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      {/* Section header */}
      <div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-white">{sectionTitle}</h2>
          {sectionSubtitle && (
            <p className="mt-2 text-text-light-gray">{sectionSubtitle}</p>
          )}
        </div>
        {showPagination && (
          <div className="flex items-center gap-3">
            <span className="text-sm text-text-light-gray"></span>
            <div className="flex gap-1">
              <button
                onClick={() => setPage(Math.max(0, page - 1))}
                disabled={page === 0}
                className="p-2 rounded-lg border border-slate-200 hover:bg-slate-50 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronLeft className="w-4 h-4 text-white" />
              </button>
              <button
                onClick={() => setPage(Math.min(totalPages - 1, page + 1))}
                disabled={page >= totalPages - 1}
                className="p-2 rounded-lg border border-slate-200 hover:bg-slate-50 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronRight className="w-4 h-4 text-white" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Scrollable table */}
      <div className={`${t.outerBorder} rounded-xl overflow-x-auto`}>
        <table className="w-full min-w-[800px]">
          <thead>
            <tr className={`border-b ${t.rowBorder}`}>
              <th className={`w-48 p-4 ${t.headerLabel} text-left text-xs font-semibold uppercase tracking-wider sticky left-0 z-10`}>Features</th>
              {pagedItems.map((item) => (
                <th key={item.name} className={`p-4 ${t.headerBg} text-center min-w-[180px]`}>
                  <div className="flex flex-col items-center gap-2">
                    <span className={`inline-flex items-center justify-center w-8 h-8 rounded-full text-xs font-bold ${t.rankBadge(item.rank)}`}>{item.rank}</span>
                    {item.logo ? (
                      <div className="w-16 h-16 rounded-lg border border-slate-200 flex items-center justify-center bg-white overflow-hidden">
                        <img src={item.logo} alt={item.name} className="w-14 h-14 object-contain" />
                      </div>
                    ) : (
                      <div className="w-16 h-16 rounded-lg bg-slate-100 flex items-center justify-center">
                        <span className="text-lg font-bold text-slate-500">{(item.name || '?').charAt(0)}</span>
                      </div>
                    )}
                    <span className="text-sm font-bold text-white">{item.name}</span>
                    <RatingStars rating={item.rating} t={t} />
                  </div>
                </th>
              ))}
            </tr>
          </thead>

          <tbody>
            {safeAttributes.map((attr, rowIdx) => {
              const attrField = `attr${rowIdx + 1}` as keyof ComparisonItem;
              return (
              <tr
                key={rowIdx}
                className={`border-b ${t.rowBorder} ${rowIdx % 2 === 0 ? t.evenRow : t.oddRow}`}
              >
                <td className={`p-4 text-sm font-semibold text-white ${t.attrLabelBg} sticky left-0 z-10 border-r ${t.rowBorder}`}>
                  {attr.label}
                </td>
                {pagedItems.map((item) => (
                  <td key={`${item.name}-attr${rowIdx}`} className={`p-4 text-center text-sm ${t.cellText}`}>
                    {String(item[attrField as keyof ComparisonItem] || '-')}
                  </td>
                ))}
              </tr>
              );
            })}

            {/* CTA row */}
            <tr className={t.oddRow}>
              <td className={`p-4 ${t.attrLabelBg} sticky left-0 z-10 border-r ${t.rowBorder}`} />
              {pagedItems.map((item) => (
                <td key={`${item.name}-cta`} className="p-4 text-center">
                  <Link
                    href={item.ctaUrl || '#'}
          {...linkAttrs}
                    className={`inline-block px-5 py-2.5 font-semibold rounded-lg transition-all duration-200 text-sm ${t.ctaBtn}`}
                  >
                    {item.ctaText}
                  </Link>
                </td>
              ))}
            </tr>
          </tbody>
        </table>
      </div>

      {/* Bottom pagination */}
      {showPagination && (
        <div className="flex items-center justify-center gap-2 mt-4">
          {Array.from({ length: totalPages }).map((_, i) => (
            <button
              key={i}
              onClick={() => setPage(i)}
              className={`w-8 h-8 rounded-lg text-sm font-medium transition-colors ${
                page === i ? t.paginationActive : t.paginationInactive
              }`}
            >
              {i + 1}
            </button>
          ))}
        </div>
      )}
    </div>
    </section>
  );
}
