"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { CalendarIcon, Users, Loader2 } from "lucide-react";
import { format } from "date-fns";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

interface BookingFormProps {
  tourId: string;
  tourTitle: string;
  pricePerPerson: number; // in cents
  maxGuests?: number;
  onSuccess?: () => void;
}

export function BookingForm({
  tourId,
  tourTitle,
  pricePerPerson,
  maxGuests = 10,
  onSuccess,
}: BookingFormProps) {
  const router = useRouter();
  const [date, setDate] = useState<Date>();
  const [numberOfGuests, setNumberOfGuests] = useState(1);
  const [notes, setNotes] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  const totalPrice = (pricePerPerson * numberOfGuests) / 100;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!date) {
      toast.error("Please select a date");
      return;
    }

    if (numberOfGuests < 1 || numberOfGuests > maxGuests) {
      toast.error(`Number of guests must be between 1 and ${maxGuests}`);
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await fetch("/api/bookings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          tourId,
          date: date.toISOString(),
          numberOfGuests,
          notes: notes || undefined,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to create booking");
      }

      toast.success("Booking request sent successfully!");
      
      if (onSuccess) {
        onSuccess();
      } else {
        router.push("/bookings");
      }
    } catch (error) {
      console.error("Booking error:", error);
      toast.error(
        error instanceof Error ? error.message : "Failed to create booking"
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div>
        <h3 className="text-lg font-semibold mb-4">Book {tourTitle}</h3>
      </div>

      {/* Date Picker */}
      <div className="space-y-2">
        <Label htmlFor="date">Select Date</Label>
        <Popover>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              className={`w-full justify-start text-left font-normal ${
                !date && "text-muted-foreground"
              }`}
            >
              <CalendarIcon className="mr-2 h-4 w-4" />
              {date ? format(date, "PPP") : "Pick a date"}
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-auto p-0" align="start">
            <Calendar
              mode="single"
              selected={date}
              onSelect={setDate}
              disabled={(date) => date < new Date()}
              initialFocus
            />
          </PopoverContent>
        </Popover>
      </div>

      {/* Number of Guests */}
      <div className="space-y-2">
        <Label htmlFor="guests">Number of Guests</Label>
        <div className="relative">
          <Users className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            id="guests"
            type="number"
            min={1}
            max={maxGuests}
            value={numberOfGuests}
            onChange={(e) => setNumberOfGuests(parseInt(e.target.value) || 1)}
            className="pl-10"
          />
        </div>
        <p className="text-sm text-muted-foreground">
          Maximum {maxGuests} guests
        </p>
      </div>

      {/* Notes */}
      <div className="space-y-2">
        <Label htmlFor="notes">Special Requests (Optional)</Label>
        <Textarea
          id="notes"
          placeholder="Any special requests or dietary requirements..."
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={3}
        />
      </div>

      {/* Price Summary */}
      <div className="bg-muted p-4 rounded-lg space-y-2">
        <div className="flex justify-between text-sm">
          <span>
            CHF {(pricePerPerson / 100).toFixed(2)} × {numberOfGuests} guest
            {numberOfGuests !== 1 ? "s" : ""}
          </span>
          <span>CHF {totalPrice.toFixed(2)}</span>
        </div>
        <div className="flex justify-between font-bold text-lg pt-2 border-t">
          <span>Total</span>
          <span>CHF {totalPrice.toFixed(2)}</span>
        </div>
      </div>

      {/* Submit Button */}
      <Button
        type="submit"
        className="w-full"
        size="lg"
        disabled={isSubmitting || !date}
      >
        {isSubmitting ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            Sending Request...
          </>
        ) : (
          "Request Booking"
        )}
      </Button>

      <p className="text-xs text-muted-foreground text-center">
        You won&apos;t be charged yet. The guide will review your request.
      </p>
    </form>
  );
}
