"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
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 { Separator } from "@/components/ui/separator";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Spinner } from "@/components/ui/spinner";
import {
  Clock,
  Users,
  MapPin,
  Calendar as CalendarIcon,
  CheckCircle2,
} from "lucide-react";

interface BookingFormProps {
  tour: {
    id: string;
    title: string;
    slug: string;
    description: string;
    city: string;
    priceCents: number | null;
    durationMin: number | null;
    maxGuests: number | null;
    meetingPoint: string | null;
    createdBy: {
      name: string | null;
      email: string;
    };
  };
  user: {
    id: string;
    name: string | null;
    email: string;
  };
}

export function BookingForm({ tour, user }: BookingFormProps) {
  const router = useRouter();
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
  const [numberOfGuests, setNumberOfGuests] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const formatPrice = (priceInCents: number | null) => {
    if (!priceInCents) return "Free";
    return `CHF ${(priceInCents / 100).toFixed(0)}`;
  };

  const formatDuration = (minutes: number | null) => {
    if (!minutes) return "N/A";
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (mins === 0) return `${hours}h`;
    return `${hours}h ${mins}m`;
  };

  const calculateTotal = () => {
    if (!tour.priceCents) return 0;
    return (tour.priceCents * numberOfGuests) / 100;
  };

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

    if (!selectedDate) {
      setError("Please select a date");
      return;
    }

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

    setIsSubmitting(true);

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

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

      // Success - redirect to bookings page
      router.push("/dashboard?tab=bookings");
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4 max-w-4xl">
        {/* Back Button */}
        <Button
          variant="ghost"
          onClick={() => router.push(`/tours/${tour.slug}`)}
          className="mb-4"
        >
          ← Back to Tour
        </Button>

        <div className="grid lg:grid-cols-3 gap-6">
          {/* Left Column - Booking Form */}
          <div className="lg:col-span-2">
            <Card>
              <CardHeader>
                <CardTitle>Book Your Tour</CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSubmit} className="space-y-6">
                  {error && (
                    <Alert variant="destructive">
                      <AlertDescription>{error}</AlertDescription>
                    </Alert>
                  )}

                  {/* Tour Info */}
                  <div className="space-y-2">
                    <h3 className="font-semibold text-lg">{tour.title}</h3>
                    <div className="flex items-center gap-2 text-sm text-gray-600">
                      <MapPin className="h-4 w-4" />
                      <span>{tour.city}</span>
                    </div>
                    <div className="flex items-center gap-4 text-sm text-gray-600">
                      <div className="flex items-center gap-1">
                        <Clock className="h-4 w-4" />
                        <span>{formatDuration(tour.durationMin)}</span>
                      </div>
                      {tour.maxGuests && (
                        <div className="flex items-center gap-1">
                          <Users className="h-4 w-4" />
                          <span>Max {tour.maxGuests} guests</span>
                        </div>
                      )}
                    </div>
                  </div>

                  <Separator />

                  {/* Date Selection */}
                  <div className="space-y-2">
                    <Label>Select Date</Label>
                    <Calendar
                      mode="single"
                      selected={selectedDate}
                      onSelect={setSelectedDate}
                      disabled={(date) => date < new Date()}
                      className="rounded-md border"
                    />
                  </div>

                  {/* Number of Guests */}
                  <div className="space-y-2">
                    <Label htmlFor="guests">Number of Guests</Label>
                    <Input
                      id="guests"
                      type="number"
                      min={1}
                      max={tour.maxGuests || 100}
                      value={numberOfGuests}
                      onChange={(e) => setNumberOfGuests(parseInt(e.target.value) || 1)}
                      required
                    />
                    {tour.maxGuests && (
                      <p className="text-sm text-gray-500">
                        Maximum {tour.maxGuests} guests per booking
                      </p>
                    )}
                  </div>

                  {/* User Info */}
                  <div className="space-y-2">
                    <Label>Your Details</Label>
                    <div className="bg-gray-50 p-3 rounded-md space-y-1">
                      <p className="text-sm font-medium">{user.name}</p>
                      <p className="text-sm text-gray-600">{user.email}</p>
                    </div>
                  </div>

                  <Button
                    type="submit"
                    className="w-full"
                    size="lg"
                    disabled={isSubmitting || !selectedDate}
                  >
                    {isSubmitting ? (
                      <>
                        <Spinner className="mr-2" />
                        Processing...
                      </>
                    ) : (
                      <>
                        <CalendarIcon className="mr-2 h-5 w-5" />
                        Confirm Booking
                      </>
                    )}
                  </Button>
                </form>
              </CardContent>
            </Card>
          </div>

          {/* Right Column - Booking Summary */}
          <div className="lg:col-span-1">
            <Card className="sticky top-4">
              <CardHeader>
                <CardTitle>Booking Summary</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600">Price per person</span>
                    <span className="font-semibold">{formatPrice(tour.priceCents)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-gray-600">Number of guests</span>
                    <span className="font-semibold">{numberOfGuests}</span>
                  </div>
                  {selectedDate && (
                    <div className="flex justify-between text-sm">
                      <span className="text-gray-600">Date</span>
                      <span className="font-semibold">
                        {selectedDate.toLocaleDateString()}
                      </span>
                    </div>
                  )}
                </div>

                <Separator />

                <div className="flex justify-between">
                  <span className="font-semibold">Total</span>
                  <span className="text-2xl font-bold">
                    CHF {calculateTotal().toFixed(2)}
                  </span>
                </div>

                <div className="space-y-2 pt-4">
                  <div className="flex items-start gap-2 text-sm text-gray-600">
                    <CheckCircle2 className="h-4 w-4 text-green-600 mt-0.5 shrink-0" />
                    <span>Free cancellation up to 24h before</span>
                  </div>
                  <div className="flex items-start gap-2 text-sm text-gray-600">
                    <CheckCircle2 className="h-4 w-4 text-green-600 mt-0.5 shrink-0" />
                    <span>Instant confirmation</span>
                  </div>
                  <div className="flex items-start gap-2 text-sm text-gray-600">
                    <CheckCircle2 className="h-4 w-4 text-green-600 mt-0.5 shrink-0" />
                    <span>Mobile ticket accepted</span>
                  </div>
                </div>

                {tour.meetingPoint && (
                  <>
                    <Separator />
                    <div className="space-y-1">
                      <p className="text-sm font-semibold">Meeting Point</p>
                      <p className="text-sm text-gray-600">{tour.meetingPoint}</p>
                    </div>
                  </>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
