import { createSignal, createMemo, Show, For } from "solid-js";
import { useNavigate } from "@solidjs/router";
import { useI18n } from "../providers/i18n-provider";

const PricingRoute = () => {
  const navigate = useNavigate();
  const { locale, toggleLocale } = useI18n();
  const isCs = () => locale() === "cs";
  const [billingInterval, setBillingInterval] = createSignal<"monthly" | "yearly">("monthly");
  const isYearly = () => billingInterval() === "yearly";
  const [openFaq, setOpenFaq] = createSignal<number | null>(0);

  const plans = createMemo(() => [
    {
      id: "starter",
      name: "Starter",
      desc: isCs() ? "Pro jednotlivce a malé podniky" : "For individuals and small businesses",
      monthly: isCs() ? "199 Kč" : "$9",
      yearly: isCs() ? "1 990 Kč" : "$90",
      period: isCs() ? "/měsíc" : "/mo",
      yearlyPeriod: isCs() ? "/rok" : "/yr",
      savings: isCs() ? "Ušetřete 398 Kč" : "Save $18",
      savingsPercent: "17%",
      trial: isCs() ? "15 dní zdarma po registraci" : "15 days free after sign-up",
      features: [
        isCs() ? "Do 50 rezervací/měsíc" : "Up to 50 bookings/month",
        isCs() ? "1 lokace, 1 zaměstnanec" : "1 location, 1 staff member",
        isCs() ? "E-mailová podpora" : "Email support",
        isCs() ? "Základní rezervační widget" : "Basic booking widget",
        isCs() ? "Potvrzení e-mailem" : "Email confirmations",
      ],
      cta: isCs() ? "Začít zdarma" : "Start for free",
      popular: false,
    },
    {
      id: "pro",
      name: "Pro",
      desc: isCs() ? "Pro rostoucí podniky" : "For growing businesses",
      monthly: isCs() ? "399 Kč" : "$19",
      yearly: isCs() ? "3 990 Kč" : "$190",
      period: isCs() ? "/měsíc" : "/mo",
      yearlyPeriod: isCs() ? "/rok" : "/yr",
      savings: isCs() ? "Ušetřete 798 Kč" : "Save $38",
      savingsPercent: "17%",
      trial: isCs() ? "15 dní zdarma po registraci" : "15 days free after sign-up",
      features: [
        isCs() ? "Neomezené rezervace" : "Unlimited bookings",
        isCs() ? "3 lokace, 10 zaměstnanců" : "3 locations, 10 staff",
        isCs() ? "E-mailová připomenutí" : "Email reminders",
        isCs() ? "Prioritní podpora" : "Priority support",
        isCs() ? "Analytika a reporty" : "Analytics & reports",
        isCs() ? "Vlastní branding widgetu" : "Custom widget branding",
        isCs() ? "Rozšířené nastavení dostupnosti" : "Advanced availability",
      ],
      cta: isCs() ? "Začít 15denní zkoušku" : "Start 15-day trial",
      popular: true,
    },
    {
      id: "business",
      name: "Business",
      desc: isCs() ? "Pro větší týmy a franšízy" : "For larger teams and franchises",
      monthly: isCs() ? "799 Kč" : "$39",
      yearly: isCs() ? "7 990 Kč" : "$390",
      period: isCs() ? "/měsíc" : "/mo",
      yearlyPeriod: isCs() ? "/rok" : "/yr",
      savings: isCs() ? "Ušetřete 1 598 Kč" : "Save $78",
      savingsPercent: "17%",
      trial: "",
      features: [
        isCs() ? "Neomezené vše" : "Unlimited everything",
        isCs() ? "Neomezené lokace a zaměstnanci" : "Unlimited locations & staff",
        isCs() ? "API přístup" : "API access",
        isCs() ? "Dedikovaný manažer" : "Dedicated manager",
        isCs() ? "Bílý labeling" : "White labeling",
        isCs() ? "Pokročilá analytika" : "Advanced analytics",
        isCs() ? "Integrace s externími systémy" : "External system integrations",
      ],
      cta: isCs() ? "Kontaktovat nás" : "Contact us",
      popular: false,
    },
  ]);

  const handleSelectPlan = (planId: string) => {
    // Redirect to signup with plan selection
    navigate("/?signup=true&plan=" + planId + "&billing=" + billingInterval());
  };

  const { t } = useI18n();

  const comparisonFeatures = [
    { key: "pricing.compare.locations", starter: "1", pro: "3", business: "∞" },
    { key: "pricing.compare.staff", starter: "1", pro: "10", business: "∞" },
    { key: "pricing.compare.bookings", starter: "50", pro: "∞", business: "∞" },
    { key: "pricing.compare.emailSupport", starter: t("pricing.compare.yes"), pro: t("pricing.compare.priority"), business: t("pricing.compare.dedicated") },
    { key: "pricing.compare.reminders", starter: "no", pro: "yes", business: "yes" },
    { key: "pricing.compare.analytics", starter: "no", pro: "yes", business: t("pricing.compare.advanced") },
    { key: "pricing.compare.api", starter: "no", pro: "no", business: "yes" },
    { key: "pricing.compare.branding", starter: "no", pro: "yes", business: "yes" },
    { key: "pricing.compare.whiteLabel", starter: "no", pro: "no", business: "yes" },
    { key: "pricing.compare.manager", starter: "no", pro: "no", business: "yes" },
  ];

  const ComparisonValue = (props: { value: string; highlight?: boolean }) => {
    const v = props.value.toLowerCase();
    if (v === "yes" || v === t("pricing.compare.yes").toLowerCase()) {
      return (
        <span class={`inline-flex items-center justify-center w-6 h-6 rounded-full ${props.highlight ? 'bg-accent/15 text-accent' : 'bg-success/15 text-success'}`}>
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
            <path d="M20 6 9 17l-5-5"/>
          </svg>
        </span>
      );
    }
    if (v === "no" || v === t("pricing.compare.no").toLowerCase()) {
      return (
        <span class="inline-flex items-center justify-center w-6 h-6 rounded-full bg-ink/5 text-ink-muted">
          <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M18 6 6 18"/>
            <path d="m6 6 12 12"/>
          </svg>
        </span>
      );
    }
    return (
      <span class={`text-sm font-medium ${props.highlight ? 'text-accent' : 'text-ink'}`}>
        {props.value}
      </span>
    );
  };

  const faqs = [
    {
      enQ: "Can I cancel anytime?",
      csQ: "Mohu kdykoliv zrušit?",
      enA: "Yes, you can cancel anytime. If you have an annual subscription, you'll have access until the end of the period. No cancellation fees.",
      csA: "Ano, můžete zrušit kdykoliv. Pokud máte roční předplatné, budete mít přístup do konce období. Žádné poplatky za zrušení.",
    },
    {
      enQ: "What if I exceed my limits?",
      csQ: "Co když překročím limity?",
      enA: "You'll be notified and prompted to upgrade to a higher plan. Your data will be preserved and you can continue using Bookra seamlessly.",
      csA: "Budete upozorněni a vyzváni k upgradu na vyšší plán. Vaše data zůstanou zachována a můžete dál používat Bookra bez přerušení.",
    },
    {
      enQ: "What payment methods do you accept?",
      csQ: "Jaké platební metody přijímáte?",
      enA: "We accept all major credit cards through Stripe. Payments are secure, encrypted, and PCI compliant.",
      csA: "Přijímáme všechny hlavní kreditní karty přes Stripe. Platby jsou zabezpečené, šifrované a splňují PCI standard.",
    },
    {
      enQ: "Can I switch plans?",
      csQ: "Můžu změnit plán?",
      enA: "Yes, you can upgrade or downgrade at any time. When upgrading, we'll prorate the difference. When downgrading, the new rate applies at the next billing cycle.",
      csA: "Ano, můžete kdykoliv upgradovat nebo downgradovat. Při upgradu doplatíte poměrnou částku. Při downgradu se nová cena aplikuje od dalšího fakturačního období.",
    },
    {
      enQ: "Is there a free trial?",
      csQ: "Je k dispozici bezplatná zkouška?",
      enA: "Yes, every plan includes a 15-day free trial. No credit card required to start.",
      csA: "Ano, každý plán obsahuje 15denní bezplatnou zkoušku. Není potřeba zadávat platební kartu.",
    },
    {
      enQ: "Do you offer support?",
      csQ: "Poskytujete podporu?",
      enA: "Absolutely. Starter includes email support, Pro gets priority support, and Business includes a dedicated account manager.",
      csA: "Samozřejmě. Starter obsahuje e-mailovou podporu, Pro má prioritní podporu a Business zahrnuje dedikovaného account managera.",
    },
  ];

  return (
    <div class="min-h-screen bg-gradient-to-br from-canvas-subtle via-canvas to-canvas-subtle">
      {/* Hero */}
      <section class="pt-16 pb-12 sm:pt-24 sm:pb-16 text-center px-4">
        <h1 class="text-4xl sm:text-5xl font-display font-bold text-ink mb-4 animate-slide-up">
          {isCs() ? "Jednoduché a férové ceny" : "Simple, fair pricing"}
        </h1>
        <p class="text-lg text-ink-muted max-w-2xl mx-auto mb-8 animate-slide-up" style={{ "animation-delay": "0.1s" }}>
          {isCs()
            ? "Vyberte si plán, který vyhovuje vašemu podnikání. Žádné skryté poplatky, žádné překvapení."
            : "Choose a plan that fits your business. No hidden fees, no surprises."}
        </p>

        {/* Billing Toggle */}
        <div class="flex items-center justify-center mb-8 animate-slide-up" style={{ "animation-delay": "0.2s" }}>
          <div class="relative inline-flex items-center gap-4">
            <span class={`text-sm font-semibold transition-colors ${!isYearly() ? 'text-ink' : 'text-ink-muted'}`}>
              {isCs() ? "Měsíčně" : "Monthly"}
            </span>
            <button
              type="button"
              onClick={() => setBillingInterval(isYearly() ? "monthly" : "yearly")}
              class={`relative w-14 h-7 rounded-full transition-colors duration-300 cursor-pointer ${isYearly() ? 'bg-accent' : 'bg-ink/30'}`}
              role="switch"
              aria-checked={isYearly()}
            >
              <span class={`absolute top-1 left-1 w-5 h-5 bg-white rounded-full shadow-md transition-transform duration-300 ${isYearly() ? 'translate-x-7' : 'translate-x-0'}`} />
            </button>
            <span class={`text-sm font-semibold transition-colors ${isYearly() ? 'text-ink' : 'text-ink-muted'}`}>
              {isCs() ? "Ročně" : "Yearly"}
            </span>
            <div class="absolute left-full ml-3 top-1/2 -translate-y-1/2">
              <Show when={isYearly()}>
                <span class="inline-flex items-center gap-1 px-2 py-0.5 bg-accent text-white text-xs font-bold rounded-full shadow-sm whitespace-nowrap">
                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
                  -17%
                </span>
              </Show>
            </div>
          </div>
        </div>
      </section>

      {/* Pricing Cards */}
      <section class="pb-16 px-4">
        <div class="grid md:grid-cols-3 gap-6 lg:gap-8 max-w-5xl mx-auto items-center">
          <For each={plans()}>
            {(plan, index) => (
              <div
                class={`group relative p-6 lg:p-8 rounded-card transition-all duration-500 animate-slide-up ${plan.popular ? 'hover:shadow-2xl hover:-translate-y-2 lg:scale-105' : 'hover:shadow-xl hover:-translate-y-1'}`}
                style={{ "animation-delay": `${0.3 + index() * 0.1}s` }}
              >
                <Show when={plan.popular}>
                  <div class="absolute inset-0 bg-gradient-to-b from-ink to-ink/95 rounded-card" />
                </Show>
                <Show when={!plan.popular}>
                  <div class="absolute inset-0 surface-elevated rounded-card" />
                </Show>

                <Show when={plan.popular}>
                  <div class="absolute -top-3 left-1/2 -translate-x-1/2 z-10">
                    <span class="px-3 py-1 bg-accent text-white text-xs font-display font-medium rounded-full shadow-lg">
                      {t("home.pricing.popular")}
                    </span>
                  </div>
                </Show>

                <div class="relative z-10">
                  <div class="mb-6">
                    <h3 class={`font-display text-lg font-semibold mb-1 ${plan.popular ? 'text-canvas' : 'text-ink'}`}>
                      {plan.name}
                    </h3>
                    <p class={plan.popular ? 'text-canvas/70' : 'text-ink-muted'}>{plan.desc}</p>
                  </div>
                  <div class="mb-6">
                    <div class="flex items-baseline gap-1">
                      <span class={`font-display text-4xl font-semibold ${plan.popular ? 'text-canvas' : 'text-ink'}`}>
                        {isYearly() ? plan.yearly : plan.monthly}
                      </span>
                      <span class={plan.popular ? 'text-canvas/60' : 'text-ink-muted'}>
                        {isYearly() ? plan.yearlyPeriod : plan.period}
                      </span>
                    </div>
                    <Show when={isYearly()}>
                      <div class="mt-2 flex items-center gap-1.5">
                        <span class="inline-flex items-center gap-1 px-2 py-0.5 bg-accent-subtle text-accent text-xs font-semibold rounded-full border border-accent/10">
                          <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
                          {plan.savingsPercent}
                        </span>
                        <span class="text-xs text-ink-subtle">{isCs() ? 'sleva při roční platbě' : 'discount on yearly billing'}</span>
                      </div>
                    </Show>
                    <Show when={!isYearly() && plan.trial}>
                      <p class="mt-1 text-xs text-accent font-medium">{plan.trial}</p>
                    </Show>
                  </div>
                  <ul class="space-y-3 mb-8">
                    <For each={plan.features}>
                      {(feature) => (
                        <li class={`flex items-start gap-3 ${plan.popular ? 'text-canvas/80' : 'text-ink-muted'}`}>
                          <span class="mt-0.5 text-accent shrink-0">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                              <path d="M20 6 9 17l-5-5"/>
                            </svg>
                          </span>
                          <span class="text-sm">{feature}</span>
                        </li>
                      )}
                    </For>
                  </ul>
                  <button
                    onClick={() => handleSelectPlan(plan.id)}
                    class={`w-full py-3 px-4 rounded-xl font-semibold text-sm transition-all duration-300 ${
                      plan.popular
                        ? 'bg-accent text-white hover:bg-accent/90 hover:shadow-lg hover:-translate-y-0.5'
                        : 'bg-ink text-canvas hover:bg-ink/90 hover:shadow-lg hover:-translate-y-0.5'
                    }`}
                  >
                    {plan.cta}
                  </button>
                </div>
              </div>
            )}
          </For>
        </div>
      </section>

      {/* Comparison Table */}
      <section class="py-16 px-4">
        <div class="max-w-4xl mx-auto">
          <div class="text-center mb-10">
            <span class="text-sm font-medium text-accent mb-2 block tracking-wide uppercase">
              {isCs() ? "Detailní srovnání" : "Detailed comparison"}
            </span>
            <h2 class="text-2xl sm:text-3xl font-display font-bold text-ink">
              {isCs() ? "Porovnání plánů" : "Compare plans"}
            </h2>
          </div>
          <div class="surface-elevated rounded-card overflow-hidden border border-border/50 shadow-sm">
            {/* Header */}
            <div class="grid grid-cols-[1fr_100px_100px_100px] sm:grid-cols-[1.5fr_1fr_1fr_1fr] gap-2 p-4 sm:p-5 bg-canvas-subtle/60 border-b border-border/50">
              <div class="text-sm font-semibold text-ink-muted self-center">{isCs() ? "Funkce" : "Feature"}</div>
              <div class="text-center font-display font-semibold text-ink text-sm">Starter</div>
              <div class="text-center">
                <span class="inline-block px-3 py-1 bg-accent/10 text-accent font-display font-semibold text-sm rounded-full">
                  Pro
                </span>
              </div>
              <div class="text-center font-display font-semibold text-ink text-sm">Business</div>
            </div>
            {/* Rows */}
            <For each={comparisonFeatures}>
              {(feature, i) => (
                <div class={`grid grid-cols-[1fr_100px_100px_100px] sm:grid-cols-[1.5fr_1fr_1fr_1fr] gap-2 p-4 sm:p-5 items-center border-b border-border/30 last:border-0 transition-colors ${i() % 2 === 0 ? 'bg-canvas/30' : ''} hover:bg-canvas-subtle/40`}>
                  <span class="text-sm text-ink font-medium">{t(feature.key)}</span>
                  <div class="flex justify-center">
                    <ComparisonValue value={feature.starter} />
                  </div>
                  <div class="flex justify-center">
                    <ComparisonValue value={feature.pro} highlight />
                  </div>
                  <div class="flex justify-center">
                    <ComparisonValue value={feature.business} />
                  </div>
                </div>
              )}
            </For>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section class="py-16 px-4 bg-canvas-subtle/30">
        <div class="max-w-2xl mx-auto">
          <div class="text-center mb-10">
            <span class="text-sm font-medium text-accent mb-2 block tracking-wide uppercase">
              {isCs() ? "Máte otázky?" : "Got questions?"}
            </span>
            <h2 class="text-2xl sm:text-3xl font-display font-bold text-ink">
              {isCs() ? "Časté dotazy" : "Frequently asked questions"}
            </h2>
          </div>
          <div class="space-y-3">
            <For each={faqs}>
              {(faq, i) => (
                <div class="surface-elevated rounded-card border border-border/40 overflow-hidden transition-all duration-300 hover:border-border/70 hover:shadow-md">
                  <button
                    type="button"
                    onClick={() => setOpenFaq(openFaq() === i() ? null : i())}
                    class="w-full flex items-center justify-between p-5 text-left group"
                  >
                    <span class="font-semibold text-ink text-sm sm:text-base pr-4 group-hover:text-accent transition-colors">
                      {isCs() ? faq.csQ : faq.enQ}
                    </span>
                    <span class={`shrink-0 w-8 h-8 rounded-full bg-canvas-subtle flex items-center justify-center text-ink-muted group-hover:bg-accent/10 group-hover:text-accent transition-all duration-300 ${openFaq() === i() ? 'rotate-180' : ''}`}>
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="m6 9 6 6 6-6"/>
                      </svg>
                    </span>
                  </button>
                  <div class={`grid transition-all duration-300 ${openFaq() === i() ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'}`}>
                    <div class="overflow-hidden">
                      <div class="px-5 pb-5 text-sm text-ink-muted leading-relaxed border-t border-border/30 pt-4">
                        {isCs() ? faq.csA : faq.enA}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </For>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section class="py-16 px-4">
        <div class="max-w-2xl mx-auto text-center">
          <h2 class="text-2xl font-display font-bold text-ink mb-4">
            {isCs() ? "Stále si nejste jistí?" : "Still not sure?"}
          </h2>
          <p class="text-ink-muted mb-6">
            {isCs() 
              ? "Začněte s bezplatným 15denním trial a rozhodněte se později."
              : "Start with a free 15-day trial and decide later."}
          </p>
          <a
            href="/dashboard?signup=true"
            class="inline-block px-8 py-3 bg-accent text-white font-semibold rounded-xl hover:bg-accent/90 hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
          >
            {isCs() ? "Začít zdarma" : "Start for free"}
          </a>
        </div>
      </section>

      {/* Footer */}
      <footer class="border-t border-border py-8 px-4">
        <div class="max-w-6xl mx-auto flex flex-col sm:flex-row items-center justify-between gap-4">
          <div class="flex items-center gap-2">
            <div class="w-6 h-6 rounded bg-gradient-to-br from-accent to-accent/70 flex items-center justify-center">
              <span class="text-white font-bold text-xs">B</span>
            </div>
            <span class="text-ink-muted text-sm">© 2024 Bookra</span>
          </div>
          <nav class="flex items-center gap-6">
            <a href="/privacy" class="text-ink-muted hover:text-ink text-sm transition-colors">{isCs() ? "Ochrana soukromí" : "Privacy"}</a>
            <a href="/terms" class="text-ink-muted hover:text-ink text-sm transition-colors">{isCs() ? "Podmínky" : "Terms"}</a>
            <a href="/contact" class="text-ink-muted hover:text-ink text-sm transition-colors">{isCs() ? "Kontakt" : "Contact"}</a>
          </nav>
        </div>
      </footer>
    </div>
  );
};

export default PricingRoute;
