import React, { useState } from 'react'
import { usePage } from '@inertiajs/react'
import DocsCallout from '../../components/docs/DocsCallout'
import DocsFaqAccordion from '../../components/docs/DocsFaqAccordion'
import DocsSection from '../../components/docs/DocsSection'
import DocsSidebarNav from '../../components/docs/DocsSidebarNav'
import FaqSearchInput from '../../components/docs/FaqSearchInput'
import QuickstartNextSteps from '../../components/docs/QuickstartNextSteps'
import SeoHead from '../../components/seo/SeoHead'
import { FAQ_CATEGORIES, RELATED_HELP_ITEMS } from './groupFaqContent'

function HeroStat({ label, value, note }) {
  return (
    <div className="rounded-[22px] border border-white/10 bg-black/20 p-4">
      <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">{label}</div>
      <div className="mt-2 text-lg font-semibold text-white">{value}</div>
      <p className="mt-2 text-sm leading-6 text-slate-400">{note}</p>
    </div>
  )
}

function FaqAnswer({ item, links }) {
  return (
    <>
      {Array.isArray(item.paragraphs) ? item.paragraphs.map((paragraph) => (
        <p key={paragraph}>{paragraph}</p>
      )) : null}
      {Array.isArray(item.bullets) && item.bullets.length > 0 ? (
        <ul className="space-y-2">
          {item.bullets.map((bullet) => (
            <li key={bullet} className="flex gap-3">
              <span className="mt-2 h-2 w-2 shrink-0 rounded-full bg-sky-300" />
              <span>{bullet}</span>
            </li>
          ))}
        </ul>
      ) : null}
      {Array.isArray(item.example) && item.example.length > 0 ? (
        <div className="grid gap-3 md:grid-cols-2">
          {item.example.map((entry) => (
            <div key={entry.label} className="rounded-[20px] border border-white/10 bg-white/[0.03] p-3">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500">{entry.label}</div>
              <div className="mt-2 text-sm font-semibold text-white">{entry.value}</div>
            </div>
          ))}
        </div>
      ) : null}
      {Array.isArray(item.links) && item.links.length > 0 ? (
        <div className="flex flex-wrap gap-3 pt-1">
          {item.links.map((link) => (
            <a key={link.label} href={links[link.linkKey] || '#'} className="text-sm font-semibold text-sky-200 underline underline-offset-4">
              {link.label}
            </a>
          ))}
        </div>
      ) : null}
    </>
  )
}

export default function GroupFaqPage() {
  const { props } = usePage()
  const links = props.links || {}
  const [query, setQuery] = useState('')
  const normalizedQuery = query.trim().toLowerCase()

  const visibleCategories = FAQ_CATEGORIES.map((category) => {
    const items = category.items.filter((item) => {
      if (!normalizedQuery) return true

      const haystack = [
        item.question,
        ...(item.paragraphs || []),
        ...(item.bullets || []),
        ...(item.example || []).flatMap((entry) => [entry.label, entry.value]),
      ].join(' ').toLowerCase()

      return haystack.includes(normalizedQuery)
    })

    return {
      ...category,
      items,
    }
  }).filter((category) => category.items.length > 0)

  const visibleQuestionCount = visibleCategories.reduce((total, category) => total + category.items.length, 0)
  const relatedHelpItems = RELATED_HELP_ITEMS.map((item) => ({
    ...item,
    href: links[item.linkKey] || '#',
  }))

  const jsonLd = [
    {
      '@context': 'https://schema.org',
      '@type': 'FAQPage',
      mainEntity: FAQ_CATEGORIES.flatMap((category) => category.items).map((item) => ({
        '@type': 'Question',
        name: item.question,
        acceptedAnswer: {
          '@type': 'Answer',
          text: (item.paragraphs || []).join(' '),
        },
      })),
    },
  ]

  return (
    <main className="min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(14,165,233,0.18),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8">
      <SeoHead seo={props.seo || {}} title={props.title} description={props.description} jsonLd={jsonLd} />

      <div className="mx-auto max-w-[1450px]">
        <section id="introduction" className="rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10">
          <div className="grid gap-8 xl:grid-cols-[minmax(0,1fr)_340px]">
            <div>
              <p className="text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80">Groups FAQ</p>
              <h1 className="mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl">Find quick answers about Groups without digging through the full guide.</h1>
              <p className="mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg">This page answers the most common practical questions about Groups, roles, publishing, contributor credit, invites, workflows, and troubleshooting. Use it when you want fast answers first, then go deeper only if you need to.</p>
              <div className="mt-6 flex flex-wrap gap-3">
                <a href={links.full_documentation} className="rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18">Read full Groups documentation</a>
                <a href={links.quickstart} className="rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]">Open Groups Quickstart</a>
                <a href={links.group_studio} className="rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]">Open Group Studio</a>
              </div>
            </div>

            <div className="grid gap-3 sm:grid-cols-3 xl:grid-cols-1">
              <HeroStat label="Best for" value="Fast practical questions" note="Use the FAQ when you need answers quickly instead of reading the longer guide front to back." />
              <HeroStat label="Core idea" value="Shared identity, preserved credit" note="Groups publish together under one identity, but the people behind the work still matter and stay visible." />
              <HeroStat label="If you need more" value="Jump deeper anytime" note="This page links back to the quickstart, the full guide, Group Studio, and the creation flow." />
            </div>
          </div>

          <div className="mt-6 max-w-3xl">
            <FaqSearchInput
              value={query}
              onChange={setQuery}
              onClear={() => setQuery('')}
              resultCount={visibleQuestionCount}
            />
          </div>
        </section>

        <div className="mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]">
          <DocsSidebarNav sections={visibleCategories.map((category) => ({ id: category.id, label: category.label }))} />

          <div className="space-y-6">
            <DocsCallout tone="note" title="How to use this page">
              Start with the category closest to your problem. If you only need the fastest route to first success, use the quickstart. If you need broader reference or advanced workflows, open the full Groups guide.
            </DocsCallout>

            {visibleCategories.length === 0 ? (
              <section className="rounded-[32px] border border-white/10 bg-white/[0.03] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.22)] md:p-7">
                <h2 className="text-2xl font-semibold text-white">No matching questions</h2>
                <p className="mt-3 text-sm leading-7 text-slate-300">Try a broader search term like roles, invite, publish, contributor, review, or Studio.</p>
              </section>
            ) : null}

            {visibleCategories.map((category) => (
              <DocsSection
                key={category.id}
                id={category.id}
                eyebrow="FAQ category"
                title={category.title}
                summary={category.summary}
              >
                <DocsFaqAccordion items={category.items} renderAnswer={(item) => <FaqAnswer item={item} links={links} />} />
              </DocsSection>
            ))}

            <DocsSection
              id="related-help"
              eyebrow="Related help"
              title="Need the next step, not just the answer?"
              summary="Use these links when the FAQ has answered the question and you are ready to act, learn more, or get support."
            >
              <QuickstartNextSteps items={relatedHelpItems} />

              <div className="mt-6 grid gap-4 md:grid-cols-2">
                <a href={links.contact_support} className="rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]">
                  <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Contact</div>
                  <div className="mt-2 text-lg font-semibold text-white">Contact support</div>
                  <p className="mt-3 text-sm leading-6 text-slate-300">Use this if your question is not answered here or if you need help with an account or workflow issue.</p>
                </a>
                <a href={links.report_issue} className="rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]">
                  <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500">Report</div>
                  <div className="mt-2 text-lg font-semibold text-white">Report a problem</div>
                  <p className="mt-3 text-sm leading-6 text-slate-300">Use this if a route, role, contributor record, or Group workflow appears broken rather than just unclear.</p>
                </a>
              </div>
            </DocsSection>
          </div>

          <aside className="hidden xl:block xl:sticky xl:top-24 xl:self-start">
            <div className="space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">Support flow</p>
                <div className="mt-4 space-y-2">
                  <a href={links.quickstart} className="block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]">Open Quickstart</a>
                  <a href={links.full_documentation} className="block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]">Read full documentation</a>
                  <a href={links.group_studio} className="block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]">Open Group Studio</a>
                  <a href={links.create_group} className="block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]">Create a Group</a>
                </div>
              </div>

              <div className="rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80">Quick troubleshooting rule</div>
                <p className="mt-2 text-sm leading-6 text-amber-50/85">If something feels wrong, check three things first: are you in the right Group context, do you have the right role, and is the content public or internal?</p>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </main>
  )
}