import { Link } from '@inertiajs/react';
import { useCreditRule } from '@/hooks/use-credit-rule';
import {
    DEFAULT_HOURS_PER_CREDIT,
    classroomHours,
    classroomHoursLabel,
    creditsLabel,
} from '@/lib/credits';
import { formatEuro } from '@/lib/format';
import { register } from '@/routes';

export type PricingPackage = {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    /** `plan` = abbonamento ricorrente, `topup` = ricarica una tantum. */
    kind?: 'plan' | 'topup';
    /** Periodo di fatturazione del piano; assente o `null` per le ricariche. */
    interval?: 'month' | 'year' | null;
    /** Crediti accreditati a ogni periodo (piano) o una tantum (ricarica). */
    credits: number;
    price_cents: number;
    currency: string;
};

const focusRing =
    'rounded-marketing-sm outline-marketing-primary focus-visible:outline-2 focus-visible:outline-offset-2';

const primaryButton = `inline-flex items-center justify-center rounded-marketing-sm bg-marketing-primary px-5 py-3 text-[0.9375rem] leading-none font-medium text-marketing-primary-foreground transition-colors hover:bg-marketing-primary-hover ${focusRing}`;

const secondaryButton = `inline-flex items-center justify-center rounded-marketing-sm border border-marketing-ink/25 px-5 py-3 text-[0.9375rem] leading-none font-medium text-marketing-ink transition-colors hover:bg-marketing-ink/5 ${focusRing}`;

const wholeEuroFormatter = new Intl.NumberFormat('it-IT', {
    style: 'currency',
    currency: 'EUR',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
    useGrouping: true,
});

/** Importi tondi senza decimali ("199 €"), gli altri con i centesimi. */
export function formatPackagePrice(cents: number): string {
    return cents % 100 === 0
        ? wholeEuroFormatter.format(cents / 100)
        : formatEuro(cents);
}

export function isPlan(pkg: PricingPackage): boolean {
    return pkg.kind === 'plan';
}

/** Unità accanto al prezzo: "/mese" per i piani, "una tantum" per le ricariche. */
export function packagePriceUnit(pkg: PricingPackage): string {
    if (!isPlan(pkg)) {
        return 'una tantum';
    }

    return pkg.interval === 'year' ? '/anno' : '/mese';
}

/** "40 crediti al mese" per i piani, "10 crediti" per le ricariche. */
export function packageCreditsLine(pkg: PricingPackage): string {
    const credits = creditsLabel(pkg.credits);

    if (!isPlan(pkg)) {
        return credits;
    }

    return `${credits} ${pkg.interval === 'year' ? "all'anno" : 'al mese'}`;
}

/** Costo per credito, es. "0,50 € a credito". */
export function packageCreditPrice(pkg: PricingPackage): string {
    if (!Number.isFinite(pkg.credits) || pkg.credits <= 0) {
        return '—';
    }

    return `${formatEuro(pkg.price_cents / pkg.credits)} a credito`;
}

/** "= 40 ore d'aula": il credito tradotto nell'unità che l'ente conta davvero. */
export function packageHoursLine(
    pkg: PricingPackage,
    hoursPerCredit: number = DEFAULT_HOURS_PER_CREDIT,
): string {
    return `= ${classroomHoursLabel(classroomHours(pkg.credits, hoursPerCredit))}`;
}

export function packageFeatures(
    pkg: PricingPackage,
    hoursPerCredit: number = DEFAULT_HOURS_PER_CREDIT,
    priceFrom = false,
): string[] {
    return [
        packageCreditsLine(pkg),
        packageHoursLine(pkg, hoursPerCredit),
        packageCreditPrice(pkg),
        'Registro presenze e invio a Forma.Temp inclusi',
        ...(priceFrom ? ['Contratto annuale su richiesta'] : []),
    ];
}

/** Timbro circolare del piano più scelto (vedi docs/design-system.md §5). */
function ChoiceStamp({ idPrefix }: { idPrefix: string }) {
    const ringId = `${idPrefix}-choice-stamp-ring`;

    return (
        <svg
            viewBox="0 0 64 64"
            role="img"
            aria-label="Scelta più frequente"
            className="text-marketing-primary size-16 -rotate-[5deg]"
        >
            <circle
                cx="32"
                cy="32"
                r="30"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
            />
            <path
                id={ringId}
                d="M 32 54 A 22 22 0 0 1 32 10 A 22 22 0 0 1 32 54"
                fill="none"
            />
            <text
                fill="currentColor"
                fontSize="7"
                fontWeight="600"
                letterSpacing="0.3"
                fontFamily="var(--font-display)"
            >
                <textPath
                    href={`#${ringId}`}
                    startOffset="50%"
                    textAnchor="middle"
                >
                    SCELTA PIÙ FREQUENTE
                </textPath>
            </text>
        </svg>
    );
}

type CardProps = {
    pkg: PricingPackage;
    featured: boolean;
    /** Livello del titolo: `h3` nella landing (sotto un h2 di sezione), `h2` su /prezzi. */
    heading?: 'h2' | 'h3';
    /** Distingue gli id del timbro quando due card compaiono nella stessa pagina. */
    idPrefix?: string;
    /**
     * Mostra la descrizione del pacchetto sotto il nome. Spenta di default:
     * la lista di ciò che include dice già le stesse cose (design-system §5).
     */
    showDescription?: boolean;
    /** Prezzo di partenza ("da 499 €"): il piano si chiude su preventivo. */
    priceFrom?: boolean;
};

/**
 * Card di piano o ricarica per le pagine pubbliche. Il CTA porta alla
 * registrazione con il pacchetto già scelto.
 */
export function MarketingPackageCard({
    pkg,
    featured,
    heading = 'h2',
    idPrefix = 'package',
    showDescription = false,
    priceFrom = false,
}: CardProps) {
    const Heading = heading;
    const { hoursPerCredit } = useCreditRule();
    const cta = isPlan(pkg) ? `Scegli ${pkg.name}` : `Acquista ${pkg.name}`;

    return (
        <article
            className={`rounded-marketing bg-marketing-surface relative flex w-full flex-col p-6 ${
                featured
                    ? 'border-marketing-primary border-[1.5px]'
                    : 'border-marketing-border border'
            }`}
        >
            <Heading className="font-display text-[1.125rem] leading-[1.35] font-semibold">
                {pkg.name}
            </Heading>

            {showDescription && pkg.description && (
                <p className="text-marketing-ink/70 mt-1 text-sm leading-[1.5]">
                    {pkg.description}
                </p>
            )}

            <div className="relative mt-3 flex items-baseline gap-2">
                {priceFrom && (
                    <span className="text-marketing-ink/60 text-sm">da</span>
                )}
                <span className="marketing-data text-[1.75rem] leading-none">
                    {formatPackagePrice(pkg.price_cents)}
                </span>
                <span className="text-marketing-ink/60 text-sm">
                    {packagePriceUnit(pkg)}
                </span>

                {featured && (
                    <span className="pointer-events-none absolute -top-9 -right-2">
                        <ChoiceStamp idPrefix={`${idPrefix}-${pkg.slug}`} />
                    </span>
                )}
            </div>

            <ul className="text-marketing-ink/80 mt-4 mb-6 flex flex-col gap-2 text-sm leading-[1.5]">
                {packageFeatures(pkg, hoursPerCredit, priceFrom).map(
                    (feature, index) => (
                        // Posizione e non testo: due voci con la stessa frase sono improbabili
                        // ma non impossibili, e colliderebbero come chiave.
                        <li
                            key={`${pkg.slug}-feature-${index}`}
                            className="border-marketing-border border-t pt-2"
                        >
                            {feature}
                        </li>
                    ),
                )}
            </ul>

            <Link
                href={register.url({ query: { package: pkg.slug } })}
                className={`mt-auto ${
                    featured ? primaryButton : secondaryButton
                } w-full`}
            >
                {cta}
            </Link>
        </article>
    );
}

/** Card di pagina /prezzi: titolo h2, sotto l'h1 della pagina. */
export function PricingPackageCard({
    pkg,
    featured,
    priceFrom = false,
}: {
    pkg: PricingPackage;
    featured: boolean;
    priceFrom?: boolean;
}) {
    return (
        <MarketingPackageCard
            pkg={pkg}
            featured={featured}
            heading="h2"
            idPrefix="pricing"
            priceFrom={priceFrom}
        />
    );
}
