"use client";

import Link from "next/link";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import {
  selectPackages,
  selectPackagesLoaded,
  fetchPackages,
  type Package,
} from "@/store/slices/subscribeSlice";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { useEffect, useRef } from "react";

interface CompareBandProps {
  locale: string;
}

// ── Icons ─────────────────────────────────────────────────────────────────────
const CheckIcon = () => (
  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="var(--brand, #C1272D)" strokeWidth="2.5" strokeLinecap="round">
    <path d="M5 12l5 5L20 7" />
  </svg>
);
const CrossIcon = () => (
  <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="var(--text-3, #9ca3af)" strokeWidth="2" strokeLinecap="round">
    <path d="M6 6l12 12M18 6L6 18" />
  </svg>
);

// ── Feature row definition ────────────────────────────────────────────────────
interface FeatureRow {
  label: string;
  description?: string;
  /** returns the cell value for a given package (or "free" for the free plan) */
  getValue: (pkg: Package | null) => boolean | string;
  isSection?: boolean;
}

const FEATURE_ROWS: FeatureRow[] = [
  // ── Content
  { label: "Content", isSection: true, getValue: () => "" },
  {
    label: "Breaking news & alerts",
    getValue: () => true,
  },
  {
    label: "Premium articles",
    description: "Exclusive in-depth reporting and analysis",
    getValue: (pkg) => (pkg === null ? false : pkg.is_premium_news === 1),
  },
  {
    label: "Daily e-paper",
    description: "PDF edition delivered every morning",
    getValue: (pkg) => (pkg === null ? false : pkg.is_epaper === 1),
  },
  // ── Experience
  { label: "Experience", isSection: true, getValue: () => "" },
  {
    label: "Ad-free reading",
    getValue: (pkg) => (pkg === null ? false : pkg.is_ads_free === 1),
  },
  {
    label: "Comments & discussion",
    getValue: () => true,
  },
  {
    label: "Shorts & clips",
    getValue: () => true,
  },
  // ── Duration
  { label: "Plan details", isSection: true, getValue: () => "" },
  {
    label: "Billing period",
    getValue: (pkg) =>
      pkg === null ? "—" : `${pkg.time} ${pkg.type}${parseInt(pkg.time) > 1 ? "" : ""}`,
  },
  {
    label: "Price",
    // Currency symbol is injected at render time — the static ₹ is replaced
    // in CompareBand via the priceOverride logic below
    getValue: (pkg) => (pkg === null ? "Free" : `__PRICE__${pkg.price}`),
  },
];

// ── Cell renderer ─────────────────────────────────────────────────────────────
function Cell({
  value,
  featured = false,
}: {
  value: boolean | string;
  featured?: boolean;
}) {
  if (typeof value === "boolean") {
    return (
      <div className="col" style={featured ? { color: "var(--brand)" } : {}}>
        <span className={value ? "y" : "n"}>
          {value ? <CheckIcon /> : <CrossIcon />}
        </span>
      </div>
    );
  }
  return (
    <div className="col" style={featured ? { color: "var(--brand)", fontWeight: 700 } : {}}>
      <span className="v">{value}</span>
    </div>
  );
}

// ── Skeleton ──────────────────────────────────────────────────────────────────
function CompareSkeleton() {
  return (
    <section className="compare-band">
      <div className="wrap">
        <div style={{ height: 28, width: "40%", background: "#e5e7eb", borderRadius: 6, marginBottom: "2rem" }} />
        <div className="compare-table">
          {Array.from({ length: 8 }).map((_, i) => (
            <div key={i} className="compare-row" style={{ opacity: 0.5 }}>
              <div className="feat"><div style={{ height: 13, width: "60%", background: "#e5e7eb", borderRadius: 4 }} /></div>
              {Array.from({ length: 4 }).map((__, j) => (
                <div key={j} className="col"><div style={{ height: 20, width: 20, background: "#e5e7eb", borderRadius: 4, margin: "0 auto" }} /></div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Main ──────────────────────────────────────────────────────────────────────
export function CompareBand({ locale: _locale }: CompareBandProps) {
  const dispatch = useAppDispatch();
  const packages = useAppSelector(selectPackages);
  const loaded   = useAppSelector(selectPackagesLoaded);
  const fetchedRef = useRef(false);
  const { settings } = useGeneralSettings();
  const currency = settings?.currencySymbol ?? "₹";

  useEffect(() => {
    if (!loaded && !fetchedRef.current) {
      fetchedRef.current = true;
      dispatch(fetchPackages());
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!loaded) return <CompareSkeleton />;

  // Free plan is always the first column (null = free)
  const allPlans: (Package | null)[] = [null, ...packages];

  return (
    <section className="compare-band">
      <div className="wrap">
        <h2>Compare every feature</h2>

        <div className="compare-table">
          {/* ── Column headers ── */}
          <div className="compare-row">
            <div className="feat">Feature</div>
            {/* Free plan */}
            <div className="col">
              <span style={{ fontWeight: 700, fontSize: "0.875rem", color: "var(--text-2, #6b7280)" }}>
                Free
              </span>
            </div>
            {/* API plans */}
            {packages.map((pkg) => (
              <div
                key={pkg.id}
                className="col featured-col"
                style={{ color: "var(--brand, #C1272D)", fontWeight: 800, fontSize: "0.875rem" }}
              >
                {pkg.name}
                <div style={{ fontSize: 10, fontFamily: "var(--mono, monospace)", fontWeight: 500, color: "var(--text-3, #9ca3af)", marginTop: 2 }}>
                  {currency}{pkg.price}/{pkg.time}{pkg.type.charAt(0).toLowerCase()}
                </div>
              </div>
            ))}
          </div>

          {/* ── Feature rows ── */}
          {FEATURE_ROWS.map((row, rowIdx) => {
            if (row.isSection) {
              return (
                <div key={rowIdx} className="compare-row section">
                  <div style={{ gridColumn: "1 / -1" }}>{row.label}</div>
                </div>
              );
            }

            return (
              <div key={rowIdx} className="compare-row">
                <div className="feat">
                  {row.label}
                  {row.description && <div className="desc">{row.description}</div>}
                </div>
                {allPlans.map((pkg, colIdx) => {
                  let val = row.getValue(pkg);
                  // Inject dynamic currency symbol for price row
                  if (typeof val === "string" && val.startsWith("__PRICE__")) {
                    val = `${currency}${val.replace("__PRICE__", "")}`;
                  }
                  const isFeatured = pkg !== null && packages.indexOf(pkg) === Math.floor(packages.length / 2);
                  return (
                    <Cell
                      key={colIdx}
                      value={val}
                      featured={isFeatured}
                    />
                  );
                })}
              </div>
            );
          })}

          {/* ── Subscribe CTA row ── */}
          <div className="compare-row">
            <div className="feat" />
            {/* Free */}
            <div className="col">
              <span style={{ fontSize: 11, color: "var(--text-3, #9ca3af)", fontFamily: "var(--mono, monospace)" }}>
                Current
              </span>
            </div>
            {/* Plan CTAs */}
            {packages.map((pkg) => (
              <div key={pkg.id} className="col featured-col">
                <Link
                  href="/subscribe"
                  style={{
                    display: "inline-block",
                    padding: "0.4375rem 0.875rem",
                    background: "var(--brand, #C1272D)",
                    color: "#fff",
                    borderRadius: 7,
                    fontWeight: 700,
                    fontSize: "0.75rem",
                    textDecoration: "none",
                    whiteSpace: "nowrap",
                  }}
                >
                  {pkg.is_buy === 1 ? "Active" : `Get ${pkg.name}`}
                </Link>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
