import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { z } from "zod";
import { PublicPageThemeWrapper, type PublicPageThemeValues } from "@/components/public-content/PublicPageTheme";

const schema = z.object({
  requester_name: z.string().trim().min(1, "Name required").max(200),
  requester_email: z.string().trim().email("Valid email required").max(255),
  requester_phone: z.string().trim().max(40).optional().or(z.literal("")),
  unit_address: z.string().trim().max(255).optional().or(z.literal("")),
  requested_lot_type: z.enum(["rv", "boat", "either"]),
  vehicle_description: z.string().trim().max(500).optional().or(z.literal("")),
  notes: z.string().trim().max(1000).optional().or(z.literal("")),
});

export default function PublicRVBoatWaitlistPage() {
  const { associationId } = useParams<{ associationId: string }>();
  const [associationName, setAssociationName] = useState<string>("");
  const [theme, setTheme] = useState<PublicPageThemeValues | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [position, setPosition] = useState<number | null>(null);

  const [form, setForm] = useState({
    requester_name: "", requester_email: "", requester_phone: "",
    unit_address: "", requested_lot_type: "either",
    vehicle_description: "", notes: ""
  });

  useEffect(() => {
    const fetchAssoc = async () => {
      if (!associationId) return;
      const { data } = await supabase
        .from("association_public_pages")
        .select("association_id, is_published, accent_color, bg_color, section_bg_color, text_color, heading_color, font_family, heading_font_family, associations:association_id(name)")
        .eq("association_id", associationId)
        .eq("is_published", true)
        .maybeSingle();
      if (data) {
        // @ts-ignore
        setAssociationName(data.associations?.name || "Community");
        setTheme(data as any);
      }
      setLoaded(true);
    };
    fetchAssoc();
  }, [associationId]);

  const submit = async () => {
    if (!associationId) return;
    const parsed = schema.safeParse(form);
    if (!parsed.success) {
      const first = Object.values(parsed.error.flatten().fieldErrors)[0]?.[0];
      toast.error(first || "Please complete required fields");
      return;
    }
    setSubmitting(true);
    const { data, error } = await supabase.from("rv_boat_lot_waitlist").insert({
      association_id: associationId,
      requester_name: parsed.data.requester_name,
      requester_email: parsed.data.requester_email,
      requester_phone: parsed.data.requester_phone || null,
      unit_address: parsed.data.unit_address || null,
      requested_lot_type: parsed.data.requested_lot_type,
      vehicle_description: parsed.data.vehicle_description || null,
      notes: parsed.data.notes || null,
      source: "public_form",
      status: "waiting",
      position: 0,
    }).select("position").single();
    setSubmitting(false);
    if (error) { toast.error(error.message); return; }
    setPosition(data.position);
    setSubmitted(true);
  };

  if (!loaded) {
    return <div className="min-h-screen flex items-center justify-center text-muted-foreground">Loading…</div>;
  }

  if (!associationName) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6">
        <Card className="max-w-md w-full">
          <CardHeader><CardTitle>Waitlist unavailable</CardTitle></CardHeader>
          <CardContent><p className="text-sm text-muted-foreground">This community has not published its public page.</p></CardContent>
        </Card>
      </div>
    );
  }

  if (submitted) {
    return (
      <PublicPageThemeWrapper theme={theme} className="min-h-screen flex items-center justify-center p-6">
        <Card className="max-w-md w-full" style={{ backgroundColor: "var(--pp-section)" }}>
          <CardHeader>
            <CardTitle>You're on the list!</CardTitle>
            <CardDescription>{associationName}</CardDescription>
          </CardHeader>
          <CardContent>
            <p className="text-sm">Thanks — we'll contact you when a lot becomes available.</p>
            {position !== null && (
              <p className="mt-3 text-sm">Your current position: <span className="font-semibold">#{position}</span></p>
            )}
          </CardContent>
        </Card>
      </PublicPageThemeWrapper>
    );
  }

  return (
    <PublicPageThemeWrapper theme={theme} className="min-h-screen flex items-center justify-center p-6">
      <Card className="max-w-xl w-full" style={{ backgroundColor: "var(--pp-section)" }}>
        <CardHeader>
          <CardTitle>RV / Boat Lot Waitlist</CardTitle>
          <CardDescription>{associationName} — Join the waitlist for a rental lot.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div><Label>Full name *</Label><Input value={form.requester_name} onChange={e => setForm({ ...form, requester_name: e.target.value })} /></div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div><Label>Email *</Label><Input type="email" value={form.requester_email} onChange={e => setForm({ ...form, requester_email: e.target.value })} /></div>
            <div><Label>Phone</Label><Input value={form.requester_phone} onChange={e => setForm({ ...form, requester_phone: e.target.value })} /></div>
          </div>
          <div><Label>Unit / Address</Label><Input value={form.unit_address} onChange={e => setForm({ ...form, unit_address: e.target.value })} /></div>
          <div>
            <Label>Type of lot</Label>
            <Select value={form.requested_lot_type} onValueChange={v => setForm({ ...form, requested_lot_type: v })}>
              <SelectTrigger><SelectValue /></SelectTrigger>
              <SelectContent>
                <SelectItem value="rv">RV</SelectItem>
                <SelectItem value="boat">Boat</SelectItem>
                <SelectItem value="either">Either</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div><Label>Vehicle description</Label><Input placeholder="e.g. 28ft travel trailer" value={form.vehicle_description} onChange={e => setForm({ ...form, vehicle_description: e.target.value })} /></div>
          <div><Label>Notes</Label><Textarea value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} /></div>
          <Button className="w-full" onClick={submit} disabled={submitting}>{submitting ? "Submitting…" : "Join waitlist"}</Button>
        </CardContent>
      </Card>
    </PublicPageThemeWrapper>
  );
}
