import { useEffect, useState } from "react";
import { useParams, Link } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { CalendarDays, CheckCircle, Clock, Loader2, MapPin, ArrowLeft } from "lucide-react";
import { format, parseISO } from "date-fns";

interface BookingDetails {
  id: string;
  guest_name: string | null;
  guest_email: string | null;
  booking_date: string | null;
  start_time: string | null;
  end_time: string | null;
  status: string | null;
  title: string | null;
  amenity_name: string | null;
  association_name: string | null;
  association_slug: string | null;
}

export default function BookingConfirmationPage() {
  const { bookingId } = useParams<{ bookingId: string }>();
  const [loading, setLoading] = useState(true);
  const [booking, setBooking] = useState<BookingDetails | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!bookingId) return;
    (async () => {
      const { data, error: rpcError } = await (supabase as any).rpc(
        "get_public_booking_confirmation",
        { p_booking_id: bookingId }
      );
      if (rpcError) {
        setError("Unable to load booking details.");
      } else if (!data || data.length === 0) {
        setError("Booking not found.");
      } else {
        setBooking(data[0] as BookingDetails);
      }
      setLoading(false);
    })();
  }, [bookingId]);

  const formatDate = (d?: string | null) =>
    d ? format(parseISO(`${d}T12:00:00`), "EEEE, MMMM d, yyyy") : "—";

  const formatTime = (t?: string | null) => {
    if (!t) return "";
    // Handles "HH:mm" or "HH:mm:ss"
    const parts = t.split(":");
    if (parts.length < 2) return t;
    const hh = parseInt(parts[0], 10);
    const mm = parts[1];
    const period = hh >= 12 ? "PM" : "AM";
    const hour12 = hh % 12 === 0 ? 12 : hh % 12;
    return `${hour12}:${mm} ${period}`;
  };

  const statusLabel = booking?.status?.replace(/_/g, " ") || "Pending";
  const isConfirmed =
    booking?.status === "confirmed" || booking?.status === "approved";

  return (
    <div className="min-h-screen bg-secondary/30 py-12 px-4">
      <div className="max-w-xl mx-auto">
        {loading ? (
          <div className="flex justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : error ? (
          <Card>
            <CardContent className="py-12 text-center space-y-3">
              <p className="text-lg font-semibold text-foreground">{error}</p>
              <p className="text-sm text-muted-foreground">
                The link may be invalid or the booking has been removed.
              </p>
            </CardContent>
          </Card>
        ) : booking ? (
          <Card>
            <CardHeader className="text-center space-y-2">
              <div className="mx-auto rounded-full bg-primary/10 p-3 w-fit">
                <CheckCircle className="h-10 w-10 text-primary" />
              </div>
              <CardTitle className="text-2xl">
                {isConfirmed ? "Booking Confirmed" : "Booking Request Received"}
              </CardTitle>
              <Badge
                variant={isConfirmed ? "default" : "secondary"}
                className="capitalize w-fit mx-auto"
              >
                {statusLabel}
              </Badge>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-lg border bg-card p-4 space-y-3">
                {booking.amenity_name && (
                  <div className="flex items-start gap-3">
                    <MapPin className="h-4 w-4 mt-0.5 text-muted-foreground" />
                    <div>
                      <p className="text-xs uppercase tracking-wide text-muted-foreground">
                        Amenity
                      </p>
                      <p className="font-semibold text-foreground">
                        {booking.amenity_name}
                      </p>
                      {booking.association_name && (
                        <p className="text-sm text-muted-foreground">
                          {booking.association_name}
                        </p>
                      )}
                    </div>
                  </div>
                )}
                <div className="flex items-start gap-3">
                  <CalendarDays className="h-4 w-4 mt-0.5 text-muted-foreground" />
                  <div>
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">
                      Date
                    </p>
                    <p className="font-semibold text-foreground">
                      {formatDate(booking.booking_date)}
                    </p>
                  </div>
                </div>
                {(booking.start_time || booking.end_time) && (
                  <div className="flex items-start gap-3">
                    <Clock className="h-4 w-4 mt-0.5 text-muted-foreground" />
                    <div>
                      <p className="text-xs uppercase tracking-wide text-muted-foreground">
                        Time
                      </p>
                      <p className="font-semibold text-foreground">
                        {formatTime(booking.start_time)}
                        {booking.start_time && booking.end_time ? " – " : ""}
                        {formatTime(booking.end_time)}
                      </p>
                    </div>
                  </div>
                )}
                {booking.guest_name && (
                  <div className="border-t pt-3">
                    <p className="text-xs uppercase tracking-wide text-muted-foreground">
                      Booked under
                    </p>
                    <p className="font-medium text-foreground">
                      {booking.guest_name}
                    </p>
                    {booking.guest_email && (
                      <p className="text-sm text-muted-foreground">
                        {booking.guest_email}
                      </p>
                    )}
                  </div>
                )}
              </div>

              <p className="text-sm text-muted-foreground text-center">
                A confirmation email has been sent to you. Please save this
                page for your records.
              </p>

              {booking.association_slug && (
                <Button asChild variant="outline" className="w-full">
                  <Link to={`/community/${booking.association_slug}`}>
                    <ArrowLeft className="h-4 w-4 mr-2" />
                    Back to community page
                  </Link>
                </Button>
              )}
            </CardContent>
          </Card>
        ) : null}
      </div>
    </div>
  );
}
