"use client";

import { ReactNode } from "react";
import { CheckIcon, XMarkIcon, CurrencyYenIcon } from "@heroicons/react/24/outline";
import { AnimatedCard } from "@/components/molecules/AnimatedCard/AnimatedCard";
import { Button } from "@/components/atoms/button";

export interface ComparisonProduct {
  id: string;
  name: string;
  sku: string;
  description?: string;
  monthlyPrice?: number;
  oneTimePrice?: number;
  isRecommended?: boolean;
  badge?: string;
  href?: string;
  actionLabel?: string;
}

export interface ComparisonFeature {
  id: string;
  name: string;
  description?: string;
  values: (string | boolean | number | null)[];
}

export interface ProductComparisonProps {
  products: ComparisonProduct[];
  features: ComparisonFeature[];
  title?: string;
  description?: string;
  maxColumns?: number;
  showPricing?: boolean;
  showActions?: boolean;
  variant?: "table" | "cards";
  currencyLocale?: string;
  children?: ReactNode;
}

function renderFeatureValue(value: string | boolean | number | null | undefined, locale: string) {
  if (value === null || value === undefined) {
    return (
      <span className="text-muted-foreground/60" aria-label="Not available">
        —
      </span>
    );
  }
  if (typeof value === "boolean") {
    return value ? (
      <span className="inline-flex items-center">
        <CheckIcon className="h-5 w-5 text-green-600 mx-auto" aria-hidden="true" />
        <span className="sr-only">Included</span>
      </span>
    ) : (
      <span className="inline-flex items-center">
        <XMarkIcon className="h-5 w-5 text-muted-foreground/60 mx-auto" aria-hidden="true" />
        <span className="sr-only">Not included</span>
      </span>
    );
  }
  if (typeof value === "number") {
    return <span className="font-medium">{value.toLocaleString(locale)}</span>;
  }
  return <span className="text-sm">{value}</span>;
}

function ComparisonHeader({
  title,
  description,
}: {
  title: string | undefined;
  description: string | undefined;
}) {
  if (!title) return null;
  return (
    <div className="text-center">
      <h2 className="text-3xl font-bold text-foreground mb-4">{title}</h2>
      {description && (
        <p className="text-lg text-muted-foreground max-w-3xl mx-auto">{description}</p>
      )}
    </div>
  );
}

function ProductPricing({
  product,
  showPricing,
  locale,
}: {
  product: ComparisonProduct;
  showPricing: boolean;
  locale: string;
}) {
  if (!showPricing || (product.monthlyPrice == null && product.oneTimePrice == null)) return null;
  return (
    <div className="mt-4">
      {product.monthlyPrice != null && (
        <div className="flex items-baseline justify-center gap-1 text-2xl font-bold text-foreground">
          <CurrencyYenIcon className="h-6 w-6" aria-hidden="true" />
          <span>{product.monthlyPrice.toLocaleString(locale)}</span>
          <span className="text-sm text-muted-foreground font-normal">/month</span>
        </div>
      )}
      {product.oneTimePrice != null && (
        <div className="flex items-baseline justify-center gap-1 text-lg font-semibold text-orange-600 mt-1">
          <CurrencyYenIcon className="h-4 w-4" aria-hidden="true" />
          <span>{product.oneTimePrice.toLocaleString(locale)}</span>
          <span className="text-xs text-orange-500 font-normal">one-time</span>
        </div>
      )}
    </div>
  );
}

const gridColsClass: Record<number, string> = {
  1: "grid-cols-1",
  2: "grid-cols-1 md:grid-cols-2",
  3: "grid-cols-1 md:grid-cols-2 lg:grid-cols-3",
  4: "grid-cols-1 md:grid-cols-2 lg:grid-cols-4",
};

function ComparisonCardView({
  displayProducts,
  features,
  showPricing,
  showActions,
  locale,
  maxColumns,
}: {
  displayProducts: ComparisonProduct[];
  features: ComparisonFeature[];
  showPricing: boolean;
  showActions: boolean;
  locale: string;
  maxColumns: number;
}) {
  const cols = gridColsClass[Math.min(maxColumns, 4)] ?? gridColsClass[3];

  return (
    <div className={`grid ${cols} gap-6`}>
      {displayProducts.map((product, productIndex) => (
        <AnimatedCard
          key={product.id}
          variant={product.isRecommended ? "highlighted" : "default"}
          className="p-6 h-full flex flex-col"
        >
          <div className="text-center mb-6">
            <div className="mb-3 flex items-center justify-center gap-2">
              {product.isRecommended && (
                <span className="bg-blue-500 text-white px-3 py-1 rounded-full text-sm font-medium">
                  Recommended
                </span>
              )}
              {product.badge && (
                <span className="bg-muted text-foreground px-3 py-1 rounded-full text-sm font-medium">
                  {product.badge}
                </span>
              )}
            </div>

            <h3 className="text-xl font-bold text-foreground mb-2">{product.name}</h3>
            {product.description && (
              <p className="text-muted-foreground text-sm">{product.description}</p>
            )}
            <ProductPricing product={product} showPricing={showPricing} locale={locale} />
          </div>

          <div className="flex-grow mb-6">
            <ul className="space-y-3">
              {features.map(feature => {
                const value = feature.values[productIndex];
                return (
                  <li key={feature.id} className="flex items-start justify-between">
                    <span className="text-sm text-foreground flex-1">{feature.name}</span>
                    <div className="ml-3 flex-shrink-0">{renderFeatureValue(value, locale)}</div>
                  </li>
                );
              })}
            </ul>
          </div>

          {showActions && product.href && (
            <Button
              as="a"
              href={product.href}
              className="w-full"
              variant={product.isRecommended ? "default" : "outline"}
            >
              {product.actionLabel || "Select Plan"}
            </Button>
          )}
        </AnimatedCard>
      ))}
    </div>
  );
}

function TableProductHeader({
  product,
  showPricing,
  locale,
}: {
  product: ComparisonProduct;
  showPricing: boolean;
  locale: string;
}) {
  return (
    <th scope="col" className="text-center py-4 px-6 bg-muted min-w-[200px]">
      <div className="space-y-2">
        <div className="flex items-center justify-center gap-2">
          {product.isRecommended && (
            <span className="bg-blue-500 text-white px-2 py-1 rounded-full text-xs font-medium">
              Recommended
            </span>
          )}
          {product.badge && (
            <span className="bg-muted text-foreground px-2 py-1 rounded-full text-xs font-medium">
              {product.badge}
            </span>
          )}
        </div>
        <div className="font-bold text-foreground">{product.name}</div>
        {product.description && (
          <div className="text-sm text-muted-foreground">{product.description}</div>
        )}
        {showPricing && (product.monthlyPrice != null || product.oneTimePrice != null) && (
          <div className="space-y-1">
            {product.monthlyPrice != null && (
              <div className="flex items-baseline justify-center gap-1 text-lg font-bold text-foreground">
                <CurrencyYenIcon className="h-4 w-4" aria-hidden="true" />
                <span>{product.monthlyPrice.toLocaleString(locale)}</span>
                <span className="text-xs text-muted-foreground font-normal">/mo</span>
              </div>
            )}
            {product.oneTimePrice != null && (
              <div className="flex items-baseline justify-center gap-1 text-sm font-semibold text-orange-600">
                <CurrencyYenIcon className="h-3 w-3" aria-hidden="true" />
                <span>{product.oneTimePrice.toLocaleString(locale)}</span>
                <span className="text-xs text-orange-500 font-normal">one-time</span>
              </div>
            )}
          </div>
        )}
      </div>
    </th>
  );
}

function ComparisonTableView({
  displayProducts,
  features,
  showPricing,
  showActions,
  locale,
}: {
  displayProducts: ComparisonProduct[];
  features: ComparisonFeature[];
  showPricing: boolean;
  showActions: boolean;
  locale: string;
}) {
  return (
    <AnimatedCard className="overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-border">
              <th scope="col" className="text-left py-4 px-6 font-medium text-foreground bg-muted">
                Features
              </th>
              {displayProducts.map(product => (
                <TableProductHeader
                  key={product.id}
                  product={product}
                  showPricing={showPricing}
                  locale={locale}
                />
              ))}
            </tr>
          </thead>
          <tbody>
            {features.map(feature => (
              <tr key={feature.id} className="border-b border-border/50 hover:bg-muted/50">
                <th scope="row" className="py-4 px-6 text-left font-normal">
                  <div>
                    <div className="font-medium text-foreground">{feature.name}</div>
                    {feature.description && (
                      <div className="text-sm text-muted-foreground mt-1">
                        {feature.description}
                      </div>
                    )}
                  </div>
                </th>
                {displayProducts.map((product, productIndex) => (
                  <td key={product.id} className="py-4 px-6 text-center">
                    {renderFeatureValue(feature.values[productIndex], locale)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
          {showActions && (
            <tfoot>
              <tr>
                <td className="py-6 px-6"></td>
                {displayProducts.map(product => (
                  <td key={product.id} className="py-6 px-6 text-center">
                    {product.href && (
                      <Button
                        as="a"
                        href={product.href}
                        className="w-full"
                        variant={product.isRecommended ? "default" : "outline"}
                      >
                        {product.actionLabel || "Select Plan"}
                      </Button>
                    )}
                  </td>
                ))}
              </tr>
            </tfoot>
          )}
        </table>
      </div>
    </AnimatedCard>
  );
}

export function ProductComparison({
  products,
  features,
  title = "Compare Plans",
  description,
  maxColumns = 4,
  showPricing = true,
  showActions = true,
  variant = "table",
  currencyLocale = "ja-JP",
  children,
}: ProductComparisonProps) {
  const displayProducts = products.slice(0, maxColumns);

  const commonProps = {
    displayProducts,
    features,
    showPricing,
    showActions,
    locale: currencyLocale,
  };

  return (
    <div className="space-y-8">
      <ComparisonHeader title={title} description={description} />

      {variant === "cards" ? (
        <ComparisonCardView {...commonProps} maxColumns={maxColumns} />
      ) : (
        <ComparisonTableView {...commonProps} />
      )}

      {children}
    </div>
  );
}
