import { useState } from "react";
import { Link } from "@tanstack/react-router";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { ArrowLeft, ArrowRight, CheckCircle2, Sparkles, ShieldCheck, Users, MessageCircle, User } from "lucide-react";
import { SiteLayout } from "@/components/SiteLayout";
import type { OfferPage, Person } from "@/data/offer-pages";
import { offerBgBySlug } from "@/data/offer-images";

const tabs = [
  { key: "visaoGeral", label: "Visão Geral" },
  { key: "realizacoes", label: "Realizações" },
  { key: "sobreMercado", label: "Sobre o mercado" },
  { key: "meta12Meses", label: "Meta 12 meses" },
] as const;

export function OfferPageView({ data }: { data: OfferPage }) {
  const [active, setActive] = useState<(typeof tabs)[number]["key"]>("visaoGeral");
  const heroBg = offerBgBySlug[data.slug];



  return (
    <SiteLayout>
      {/* HERO */}
      <section className="hero-bg relative overflow-hidden py-20">
        {heroBg && (
          <>
            <img src={heroBg} alt="" className="absolute inset-0 h-full w-full object-cover opacity-40" />
            <div className="absolute inset-0 bg-gradient-to-b from-[oklch(0.15_0.03_250)]/60 via-[oklch(0.15_0.03_250)]/70 to-[oklch(0.15_0.03_250)]/95" />
          </>
        )}
        <div className="relative 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">
              {data.type}
            </span>
            <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>
          </div>
          <h1 className="mt-4 text-5xl font-bold text-white sm:text-6xl">{data.name}</h1>
          <p className="mt-4 max-w-3xl text-xl text-white/85">{data.tagline}</p>
        </div>
      </section>

      {/* INTRO + TESES + OFFER CARD */}
      <section className="py-16">
        <div className="mx-auto grid max-w-7xl gap-12 px-4 sm:px-6 lg:grid-cols-3 lg:px-8">
          <div className="space-y-6 lg:col-span-2">
            {data.intro.map((p, i) => (
              <p key={i} className="text-base leading-relaxed text-foreground/80">{p}</p>
            ))}
            {data.teses && data.teses.length > 0 && (
              <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">Teses de atuação</span>
                </div>
                <ul className="mt-4 grid gap-3 sm:grid-cols-2">
                  {data.teses.map((t) => (
                    <li key={t} className="flex items-start gap-2 text-sm text-foreground/80">
                      <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-[oklch(0.5_0.16_210)]" />
                      {t}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          <aside className="lg:sticky lg:top-24 lg:self-start">
            <OfferInfoCard data={data} />
          </aside>
        </div>
      </section>

      {/* TABS */}
      <section className="border-t border-border/60 bg-secondary/30 py-16">
        <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
          <div className="flex flex-wrap gap-2 border-b border-border/60">
            {tabs.map((t) => (
              <button
                key={t.key}
                onClick={() => setActive(t.key)}
                className={`relative px-4 py-3 text-sm font-semibold transition ${
                  active === t.key
                    ? "text-[oklch(0.5_0.16_210)]"
                    : "text-foreground/60 hover:text-foreground"
                }`}
              >
                {t.label}
                {active === t.key && (
                  <span className="absolute inset-x-0 -bottom-px h-0.5 brand-gradient rounded-full" />
                )}
              </button>
            ))}
          </div>
          <article className="prose prose-neutral mt-8 max-w-none prose-headings:font-display prose-headings:font-bold prose-h2:text-2xl prose-h3:text-lg prose-h3:mt-6 prose-p:text-foreground/80 prose-li:text-foreground/80 prose-strong:text-foreground prose-a:text-[oklch(0.5_0.16_210)]">
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{data.tabs[active]}</ReactMarkdown>
          </article>
        </div>
      </section>

      {/* TEAM */}
      {(data.team || data.conselho || data.advisors) && (
        <section className="py-16">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            {data.team && <PeopleGrid title="Time" people={data.team} />}
            {data.conselho && <PeopleGrid title="Conselho" people={data.conselho} className="mt-12" />}
            {data.advisors && <PeopleGrid title="Advisors" people={data.advisors} className="mt-12" />}
          </div>
        </section>
      )}

      {/* CTA FINAL */}
      <section className="hero-bg py-20">
        <div className="mx-auto max-w-3xl px-4 text-center sm:px-6 lg:px-8">
          <h2 className="text-3xl font-bold text-white sm:text-4xl">Pronto para investir na {data.name}?</h2>
          <p className="mt-4 text-white/75">
            Investimento mínimo de <strong className="text-white">{data.offerInfo.investimentoMinimo}</strong>. Acesse a plataforma para conhecer todos os detalhes da oferta.
          </p>
          <div className="mt-8 flex flex-wrap justify-center gap-3">
            <a
              href={data.offerInfo.ctaUrl}
              className="brand-gradient inline-flex items-center gap-2 rounded-full px-7 py-3 text-sm font-semibold text-[oklch(0.15_0.02_250)]"
            >
              Conhecer esta oportunidade <ArrowRight className="size-4" />
            </a>
            <Link
              to="/ofertas"
              className="inline-flex items-center gap-2 rounded-full border border-white/20 bg-white/5 px-7 py-3 text-sm font-semibold text-white hover:bg-white/10"
            >
              Ver outras ofertas
            </Link>
          </div>
          <p className="mt-6 text-xs text-white/50">Não invista antes de entender as informações essenciais da oferta.</p>
        </div>
      </section>
    </SiteLayout>
  );
}

function OfferInfoCard({ data }: { data: OfferPage }) {
  const o = data.offerInfo;
  const rows: { label: string; value?: string }[] = [
    { label: "Investimento mínimo", value: o.investimentoMinimo },
    { label: "Valor da cota", value: o.valorCota },
    { label: "Ações por cota", value: o.acoesPorCota },
    { label: "Total de cotas", value: o.totalCotas },
    { label: "Modelo de investimento", value: o.modeloInvestimento },
    { label: "Prazo final", value: o.prazoFinal },
    { label: "Investidores", value: o.investidores },
    { label: "Objetivo de captação", value: o.objetivoCaptacao },
  ];
  const pct = o.percentualAlcancado;

  return (
    <div className="card-soft rounded-2xl border border-border/60 p-6">
      <p className="text-xs uppercase tracking-widest text-foreground/50">Informações da oferta</p>
      <h3 className="mt-2 font-display text-xl font-semibold">{data.name}</h3>
      <dl className="mt-5 space-y-3 border-y border-border/60 py-5 text-sm">
        {rows.filter((r) => r.value).map((r) => (
          <div key={r.label} className="flex items-center justify-between gap-4">
            <dt className="text-foreground/60">{r.label}</dt>
            <dd className="text-right font-medium">{r.value}</dd>
          </div>
        ))}
      </dl>
      {pct && (
        <div className="mt-5">
          <div className="flex items-center justify-between text-xs">
            <span className="text-foreground/60">Alcançado</span>
            <span className="font-semibold">{pct}</span>
          </div>
          <div className="mt-2 h-2 overflow-hidden rounded-full bg-secondary">
            <div className="brand-gradient h-full" style={{ width: pct }} />
          </div>
        </div>
      )}
      <a
        href={o.ctaUrl}
        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)]"
      >
        Conheça esta oportunidade <ArrowRight className="size-4" />
      </a>
      <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"
      >
        <MessageCircle className="size-4" /> Falar com especialista
      </a>
      <div className="mt-5 grid gap-2 text-xs text-foreground/60">
        <div className="flex items-start gap-2">
          <ShieldCheck className="mt-0.5 size-4 text-[oklch(0.5_0.16_210)]" />
          Oferta pública por FCJ Invest Ltda — CVM 88/2022
        </div>
        <div className="flex items-start gap-2">
          <Users className="mt-0.5 size-4 text-[oklch(0.5_0.16_210)]" />
          Curadoria FCJ Group
        </div>
      </div>
      <p className="mt-4 text-[11px] leading-relaxed text-foreground/50">
        Não invista antes de entender as informações essenciais da oferta. Investimentos em startups envolvem riscos, inclusive perda total do capital.
      </p>
    </div>
  );
}

function PeopleGrid({ title, people, className = "" }: { title: string; people: Person[]; className?: string }) {
  return (
    <div className={className}>
      <div className="h-1 w-12 brand-gradient rounded-full" />
      <h2 className="mt-3 text-2xl font-bold sm:text-3xl">{title}</h2>
      <div className="mt-8 grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
        {people.map((p) => (
          <div key={p.name} className="card-soft rounded-2xl border border-border/60 p-5 text-center">
            <div className="mx-auto flex size-20 items-center justify-center overflow-hidden rounded-full bg-secondary text-foreground/40">
              {p.avatar ? (
                <img src={p.avatar} alt={p.name} loading="lazy" className="h-full w-full object-cover" />
              ) : (
                <User className="size-8" />
              )}
            </div>
            <h4 className="mt-4 font-display font-semibold">{p.name}</h4>
            {p.role && <p className="mt-1 text-xs text-foreground/60">{p.role}</p>}
          </div>
        ))}
      </div>
    </div>
  );
}
