import type { Metadata } from "next"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { WebinarRegistrationForm } from "./webinar-registration-form"
import {
  CalendarDays,
  CheckCircle2,
  Clock3,
  Mail,
  MessageSquareText,
  Video,
} from "lucide-react"
import { getBackendUrl, type Webinar } from "@/lib/webinar-api"

export const metadata: Metadata = {
  title: "Webinar Registration - CodeframeAI",
  description:
    "Register for the CodeframeAI webinar and receive the Google Meet link by email.",
}

const fallbackWebinarDetails = {
  title: "CodeframeAI Research Intelligence Webinar",
  description:
    "Learn how CodeframeAI turns documents, videos, and research material into structured summaries and visual mind maps with source-grounded AI.",
  date: "Create webinar in admin",
  time: "Schedule pending",
  meetStatus: "Google Meet link will be emailed after registration.",
}

const highlights = [
  "See the document-to-summary workflow",
  "Explore mind maps for research and education",
  "Ask questions about practical use cases",
]

async function getCurrentWebinar() {
  try {
    const response = await fetch(`${getBackendUrl()}/api/webinars`, {
      cache: "no-store",
    })

    if (!response.ok) return null

    const data = await response.json()
    return (data?.data?.[0] as Webinar | undefined) ?? null
  } catch (error) {
    console.error("Failed to fetch webinars:", error)
    return null
  }
}

function formatTime(webinar?: Webinar | null) {
  if (!webinar?.startTime) return fallbackWebinarDetails.time
  return `${webinar.startTime}${webinar.endTime ? ` - ${webinar.endTime}` : ""} ${webinar.timezone || "IST"}`
}

export default async function WebinarPage() {
  const webinar = await getCurrentWebinar()
  const webinarDetails = {
    title: webinar?.title || fallbackWebinarDetails.title,
    description: webinar?.description || fallbackWebinarDetails.description,
    date: webinar?.date || fallbackWebinarDetails.date,
    time: formatTime(webinar),
    meetStatus: webinar?.googleMeetLinkInfo || fallbackWebinarDetails.meetStatus,
  }

  return (
    <main className="min-h-screen bg-background">
      <section className="border-b border-border bg-secondary/30">
        <div className="mx-auto grid max-w-6xl gap-8 px-5 py-12 sm:px-6 lg:grid-cols-[1.05fr_0.95fr] lg:px-8 lg:py-16">
          <div className="flex flex-col justify-center">
            <div className="inline-flex w-fit items-center gap-2 rounded-md border border-primary/20 bg-primary/10 px-3 py-1.5 text-xs font-bold uppercase tracking-[0.08em] text-primary">
              <Video className="h-3.5 w-3.5" />
              Live Webinar
            </div>

            <h1 className="mt-5 max-w-3xl text-4xl font-bold leading-tight tracking-tight text-foreground sm:text-5xl">
              {webinarDetails.title}
            </h1>

            <p className="mt-5 max-w-2xl text-base leading-7 text-muted-foreground sm:text-lg">
              {webinarDetails.description}
            </p>

            <div className="mt-7 grid gap-3 sm:grid-cols-3">
              <div className="border border-border bg-card p-4">
                <CalendarDays className="h-5 w-5 text-primary" />
                <p className="mt-3 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  Date
                </p>
                <p className="mt-1 font-bold text-foreground">{webinarDetails.date}</p>
              </div>
              <div className="border border-border bg-card p-4">
                <Clock3 className="h-5 w-5 text-primary" />
                <p className="mt-3 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  Time
                </p>
                <p className="mt-1 font-bold text-foreground">{webinarDetails.time}</p>
              </div>
              <div className="border border-border bg-card p-4">
                <Mail className="h-5 w-5 text-primary" />
                <p className="mt-3 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
                  Meet Link
                </p>
                <p className="mt-1 text-sm font-bold text-foreground">Sent by email</p>
              </div>
            </div>

            <div className="mt-7 border-l-4 border-primary bg-card px-5 py-4 shadow-sm">
              <p className="text-lg font-bold text-foreground">
                {webinar ? `Join on ${webinar.date} at ${webinar.startTime}` : "Create a webinar to open registration"}
              </p>
              <p className="mt-1 text-sm text-muted-foreground">
                {webinarDetails.meetStatus}
              </p>
            </div>
          </div>

          <WebinarRegistrationForm
            webinarId={webinar?._id || webinar?.slug}
            slots={webinar?.slots || []}
            slotsEnabled={Boolean(webinar?.slotsEnabled)}
          />
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-5 py-10 sm:px-6 lg:px-8">
        <div className="grid gap-6 lg:grid-cols-[0.8fr_1.2fr]">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.08em] text-primary">
              What To Expect
            </p>
            <h2 className="mt-2 text-2xl font-bold tracking-tight text-foreground">
              A practical walkthrough for faster understanding
            </h2>
          </div>

          <div className="grid gap-3 sm:grid-cols-3">
            {highlights.map((highlight) => (
              <div key={highlight} className="border border-border bg-card p-4">
                <CheckCircle2 className="h-5 w-5 text-primary" />
                <p className="mt-3 text-sm font-semibold leading-6 text-foreground">
                  {highlight}
                </p>
              </div>
            ))}
          </div>
        </div>

        <div className="mt-8 flex flex-col gap-3 border border-border bg-secondary/30 p-5 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-start gap-3">
            <MessageSquareText className="mt-0.5 h-5 w-5 text-primary" />
            <div>
              <p className="font-bold text-foreground">Need help before registering?</p>
              <p className="text-sm text-muted-foreground">
                Contact the CodeframeAI team and we will help you choose the right session.
              </p>
            </div>
          </div>
          <Button asChild variant="outline">
            <Link href="/contact">Contact Us</Link>
          </Button>
        </div>
      </section>
    </main>
  )
}
