"use client"

import { useState, type FormEvent } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { CheckCircle2, Mail, Phone, User } from "lucide-react"
import { getBackendUrl, readApiMessage, type WebinarSlot } from "@/lib/webinar-api"

type WebinarRegistrationFormProps = {
  webinarId?: string
  slots?: WebinarSlot[]
  slotsEnabled?: boolean
}

export function WebinarRegistrationForm({
  webinarId,
  slots = [],
  slotsEnabled = false,
}: WebinarRegistrationFormProps) {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    slotId: slots[0]?.slotId || "",
  })
  const [submitted, setSubmitted] = useState(false)
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<{ title: string; desc: string; isError: boolean } | null>(null)

  const selectedSlot = slots.find((slot) => slot.slotId === formData.slotId)

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    setResult(null)

    if (!webinarId) {
      setResult({
        title: "Registration unavailable",
        desc: "No scheduled webinar is available yet. Please create one from the admin dashboard.",
        isError: true,
      })
      return
    }

    setLoading(true)

    try {
      const response = await fetch(`${getBackendUrl()}/api/webinars/${webinarId}/registrations`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: formData.email.trim(),
          name: formData.name.trim(),
          phone: formData.phone.trim(),
          slotId: slotsEnabled ? formData.slotId : undefined,
        }),
      })

      if (!response.ok) {
        setResult({
          title: "Registration failed",
          desc: await readApiMessage(response),
          isError: true,
        })
        return
      }

      setSubmitted(true)
      setResult(null)
    } catch (error) {
      console.error("Webinar registration error:", error)
      setResult({
        title: "Registration failed",
        desc: "Could not connect to the webinar backend. Please make sure the backend is running.",
        isError: true,
      })
    } finally {
      setLoading(false)
    }
  }

  if (submitted) {
    return (
      <div className="border border-primary/20 bg-primary/5 p-6 shadow-sm">
        <div className="flex items-start gap-4">
          <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
            <CheckCircle2 className="h-6 w-6" />
          </span>
          <div>
            <h2 className="text-xl font-bold text-foreground">Registration received</h2>
            <p className="mt-2 text-sm leading-6 text-muted-foreground">
              You are successfully registered{selectedSlot?.label ? ` for ${selectedSlot.label}` : ""}.
              The Google Meet link and timing will be sent by email.
            </p>
            <Button
              type="button"
              variant="outline"
              className="mt-5"
              onClick={() => setSubmitted(false)}
            >
              Edit details
            </Button>
          </div>
        </div>
      </div>
    )
  }

  return (
    <form onSubmit={handleSubmit} className="border border-border bg-card p-5 shadow-sm sm:p-6">
      <div>
        <p className="text-sm font-semibold uppercase tracking-[0.08em] text-primary">
          Reserve Your Seat
        </p>
        <h2 className="mt-2 text-2xl font-bold tracking-tight text-foreground">
          Get the webinar link
        </h2>
        <p className="mt-2 text-sm leading-6 text-muted-foreground">
          Enter your email to receive the Google Meet link and webinar timing.
        </p>
      </div>

      <div className="mt-6 space-y-4">
        <div className="space-y-1.5">
          <label className="flex items-center gap-2 text-xs font-semibold text-foreground">
            <Mail className="h-3.5 w-3.5 text-muted-foreground" />
            Email Address *
          </label>
          <Input
            required
            type="email"
            placeholder="you@example.com"
            value={formData.email}
            onChange={(event) => setFormData({ ...formData, email: event.target.value })}
            className="h-10"
          />
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="space-y-1.5">
            <label className="flex items-center gap-2 text-xs font-semibold text-foreground">
              <User className="h-3.5 w-3.5 text-muted-foreground" />
              Name
            </label>
            <Input
              placeholder="Your name"
              value={formData.name}
              onChange={(event) => setFormData({ ...formData, name: event.target.value })}
              className="h-10"
            />
          </div>

          <div className="space-y-1.5">
            <label className="flex items-center gap-2 text-xs font-semibold text-foreground">
              <Phone className="h-3.5 w-3.5 text-muted-foreground" />
              Phone
            </label>
            <Input
              type="tel"
              placeholder="+91 00000 00000"
              value={formData.phone}
              onChange={(event) => setFormData({ ...formData, phone: event.target.value })}
              className="h-10"
            />
          </div>
        </div>

        {slotsEnabled && slots.length > 0 && (
          <div className="space-y-1.5">
            <label className="text-xs font-semibold text-foreground">Available Slot</label>
            <Select
              value={formData.slotId}
              onValueChange={(slotId) => setFormData({ ...formData, slotId })}
            >
              <SelectTrigger className="h-10 w-full bg-background">
                <SelectValue placeholder="Select a slot" />
              </SelectTrigger>
              <SelectContent>
                {slots.map((slot) => (
                  <SelectItem key={slot.slotId} value={slot.slotId}>
                    {slot.label || `${slot.date} ${slot.startTime}`}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}
      </div>

      {result && (
        <div
          className={`mt-5 border p-3 text-sm ${
            result.isError
              ? "border-destructive/20 bg-destructive/10 text-destructive"
              : "border-primary/20 bg-primary/10 text-primary"
          }`}
        >
          <strong>{result.title}</strong>
          <p className="mt-1">{result.desc}</p>
        </div>
      )}

      <Button
        type="submit"
        size="lg"
        className="mt-6 h-11 w-full font-semibold"
        disabled={loading || !webinarId}
      >
        {loading ? "Registering..." : "Get Webinar Link"}
      </Button>

      <p className="mt-3 text-center text-[11px] leading-5 text-muted-foreground">
        Confirmation and reminder emails are handled by the webinar backend.
      </p>
    </form>
  )
}
