import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import { ArrowLeft, ArrowRight, CheckCircle2, Sparkles, ShieldCheck, TrendingUp, Users } from "lucide-react";
import { SiteLayout } from "@/components/SiteLayout";
import { offers } from "@/data/site";

export const Route = createFileRoute("/ofertas/$slug")({
  loader: ({ params }): import("@/data/site").Offer => {
    const offer = offers.find((o) => o.slug === params.slug);
    if (!offer) throw notFound();
    return offer;
  },
  head: ({ loaderData }) => ({
    meta: loaderData
      ? [
          { title: `${loaderData.name} — InvestPlus` },
          { name: "description", content: loaderData.short },
          { property: "og:title", content: `${loaderData.name} — InvestPlus` },
          { property: "og:description", content: loaderData.short },
        ]
      : [],
  }),
  notFoundComponent: () => (
    <SiteLayout>
      <div className="mx-auto max-w-3xl px-6 py-32 text-center">
        <h1 className="text-4xl font-bold">Oferta não encontrada</h1>
        <Link to="/ofertas" className="mt-6 inline-flex items-center gap-2 text-sm text-foreground/70 hover:text-foreground">
          <ArrowLeft className="size-4" /> Voltar para ofertas
        </Link>
      </div>
    </SiteLayout>
  ),
  errorComponent: ({ error }) => (
    <SiteLayout>
      <div className="mx-auto max-w-3xl px-6 py-32 text-center">
        <h1 className="text-2xl font-semibold">Algo deu errado</h1>
        <p className="mt-2 text-sm text-foreground/60">{error.message}</p>
      </div>
    </SiteLayout>
  ),
  component: OfferDetail,
});

function OfferDetail() {
  const o: import("@/data/site").Offer = Route.useLoaderData();
  const isOpen = o.status === "open" || o.status === "alt";
  const related = offers.filter((x) => x.slug !== o.slug && (x.status === "open" || x.status === "alt")).slice(0, 3);

  return (
    <SiteLayout>
      <section className="hero-bg py-20">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <Link to="/ofertas" className="inline-flex items-center gap-2 text-sm text-white/70 hover:text-white">
            <ArrowLeft className="size-4" /> Todas as ofertas
          </Link>
          <div className="mt-6 flex flex-wrap items-center gap-3">
            <span className="rounded-full bg-white/10 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-white">
              {o.type}
            </span>
            {isOpen ? (
              <span className="rounded-full bg-[oklch(0.82_0.14_205)]/20 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-[oklch(0.85_0.14_205)]">
                Em captação
              </span>
            ) : (
              <span className="rounded-full bg-emerald-500/15 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-emerald-300">
                Encerrado com sucesso
              </span>
            )}
          </div>
          <h1 className="mt-4 text-5xl font-bold text-white sm:text-6xl">{o.name}</h1>
          {o.tagline && <p className="mt-4 max-w-3xl text-xl text-white/85">{o.tagline}</p>}
          <p className="mt-3 max-w-3xl text-base text-white/65">{o.short}</p>

          {o.metrics && o.metrics.length > 0 && (
            <div className="mt-10 grid max-w-4xl gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {o.metrics.map((m) => (
                <div key={m.label} className="rounded-2xl border border-white/10 bg-white/5 p-4 backdrop-blur">
                  <p className="text-2xl font-bold text-white">{m.value}</p>
                  <p className="mt-1 text-xs uppercase tracking-wider text-white/60">{m.label}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      <section className="py-20">
        <div className="mx-auto grid max-w-7xl gap-12 px-4 sm:px-6 lg:grid-cols-3 lg:px-8">
          <div className="lg:col-span-2 space-y-14">
            <div>
              <h2 className="text-2xl font-bold sm:text-3xl">Sobre a operação</h2>
              <p className="mt-4 whitespace-pre-line text-base leading-relaxed text-foreground/80">{o.long}</p>
            </div>

            {o.thesis && (
              <div className="card-soft rounded-2xl border border-border/60 p-6">
                <div className="flex items-center gap-2 text-[oklch(0.5_0.16_210)]">
                  <Sparkles className="size-5" />
                  <span className="text-xs font-semibold uppercase tracking-widest">Tese de investimento</span>
                </div>
                <p className="mt-3 text-lg leading-relaxed text-foreground/85">{o.thesis}</p>
              </div>
            )}

            {o.pillars && o.pillars.length > 0 && (
              <div>
                <h3 className="text-xl font-bold sm:text-2xl">Pilares estratégicos</h3>
                <div className="mt-6 grid gap-4 sm:grid-cols-2">
                  {o.pillars.map((p) => (
                    <div key={p.title} className="card-soft rounded-2xl border border-border/60 p-5">
                      <h4 className="font-semibold">{p.title}</h4>
                      <p className="mt-2 text-sm text-foreground/70">{p.description}</p>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {o.sections?.map((s) => (
              <div key={s.title}>
                <h3 className="text-xl font-bold sm:text-2xl">{s.title}</h3>
                <p className="mt-3 whitespace-pre-line text-base leading-relaxed text-foreground/80">{s.body}</p>
              </div>
            ))}

            {o.whyInvest && o.whyInvest.length > 0 && (
              <div>
                <h3 className="text-xl font-bold sm:text-2xl">Por que investir</h3>
                <ul className="mt-6 space-y-3">
                  {o.whyInvest.map((w) => (
                    <li key={w} className="flex items-start gap-3 rounded-xl border border-border/60 bg-card p-4">
                      <CheckCircle2 className="mt-0.5 size-5 shrink-0 text-[oklch(0.5_0.16_210)]" />
                      <span className="text-sm leading-relaxed text-foreground/80">{w}</span>
                    </li>
                  ))}
                </ul>
              </div>
            )}

            <div>
              <h3 className="text-xl font-bold sm:text-2xl">Diferenciais InvestPlus</h3>
              <div className="mt-6 grid gap-4 sm:grid-cols-2">
                {[
                  { i: ShieldCheck, t: "Estruturada via CVM 88", d: "Operação respaldada pela regulamentação de equity crowdfunding." },
                  { i: Users, t: "Curadoria FCJ Group", d: "Selecionada pela maior rede de Corporate Venture Builders da América Latina." },
                  { i: TrendingUp, t: "Potencial de crescimento", d: "Tese de investimento alinhada a tendências de mercado de longo prazo." },
                  { i: ShieldCheck, t: "Due diligence rigorosa", d: "Análise jurídica, contábil e estratégica antes de subir à plataforma." },
                ].map((b) => (
                  <div key={b.t} className="card-soft rounded-2xl border border-border/60 p-5">
                    <b.i className="size-5 text-[oklch(0.5_0.16_210)]" />
                    <h4 className="mt-3 font-semibold">{b.t}</h4>
                    <p className="mt-1 text-sm text-foreground/70">{b.d}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <aside className="lg:sticky lg:top-24 lg:self-start">
            <div className="card-soft rounded-2xl border border-border/60 p-6">
              <p className="text-xs uppercase tracking-widest text-foreground/50">Resumo da oferta</p>
              <h3 className="mt-2 font-display text-xl font-semibold">{o.name}</h3>
              <dl className="mt-5 space-y-3 border-y border-border/60 py-5 text-sm">
                <Row label="Modalidade" value={o.type} />
                <Row label="Status" value={isOpen ? "Em captação" : "Encerrada"} />
                {o.highlight?.map((h) => <Row key={h.label} label={h.label} value={h.value} />)}
              </dl>
              {isOpen ? (
                <a
                  href="https://www.platform.investplus.vc/auth/login"
                  className="brand-gradient mt-6 inline-flex w-full items-center justify-center gap-2 rounded-full px-6 py-3 text-sm font-semibold text-[oklch(0.15_0.02_250)]"
                >
                  Investir agora <ArrowRight className="size-4" />
                </a>
              ) : (
                <Link
                  to="/ofertas"
                  className="mt-6 inline-flex w-full items-center justify-center gap-2 rounded-full border border-border bg-background px-6 py-3 text-sm font-semibold text-foreground"
                >
                  Ver outras ofertas
                </Link>
              )}
              <a
                href="https://wa.me/551152863746"
                className="mt-3 inline-flex w-full items-center justify-center gap-2 rounded-full border border-border bg-background px-6 py-3 text-sm font-semibold text-foreground hover:bg-secondary"
              >
                Falar com especialista
              </a>
              <p className="mt-4 text-xs text-foreground/50">
                Investimentos em startups envolvem riscos, inclusive perda total do capital.
              </p>
            </div>
          </aside>
        </div>
      </section>

      {related.length > 0 && (
        <section className="border-t border-border/60 bg-secondary/30 py-20">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="flex items-end justify-between gap-6">
              <div>
                <div className="h-1 w-12 brand-gradient rounded-full" />
                <h2 className="mt-3 text-2xl font-bold sm:text-3xl">Outras ofertas disponíveis</h2>
              </div>
              <Link to="/ofertas" className="text-sm font-semibold text-[oklch(0.5_0.16_210)]">
                Ver todas →
              </Link>
            </div>
            <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
              {related.map((r) => (
                <Link
                  key={r.slug}
                  to="/ofertas/$slug"
                  params={{ slug: r.slug }}
                  className="card-soft group flex flex-col overflow-hidden rounded-2xl border border-border/60 transition hover:-translate-y-1"
                >
                  <div className="hero-bg flex aspect-[16/10] items-center justify-center">
                    <span className="font-display text-xl font-bold text-white/90">{r.name}</span>
                  </div>
                  <div className="flex flex-1 flex-col p-5">
                    <span className="text-[10px] font-semibold uppercase tracking-wider text-foreground/50">{r.type}</span>
                    <h3 className="mt-1 font-display text-lg font-semibold">{r.name}</h3>
                    <p className="mt-2 line-clamp-2 text-sm text-foreground/70">{r.short}</p>
                    <span className="mt-auto inline-flex items-center gap-1 pt-4 text-sm font-semibold group-hover:text-[oklch(0.5_0.16_210)]">
                      Ver oferta <ArrowRight className="size-4" />
                    </span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}
    </SiteLayout>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-4">
      <dt className="text-foreground/60">{label}</dt>
      <dd className="text-right font-medium">{value}</dd>
    </div>
  );
}
