"use client";

import { useEffect, useState } from "react";
import { BookingCard } from "@/components/booking-card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2, Calendar } from "lucide-react";
import {
  Empty,
  EmptyHeader,
  EmptyTitle,
  EmptyDescription,
  EmptyContent,
  EmptyMedia,
} from "@/components/ui/empty";
import { Button } from "@/components/ui/button";
import Link from "next/link";

interface Booking {
  id: string;
  date: string;
  numberOfGuests: number;
  totalPrice: number;
  status: "PENDING" | "CONFIRMED" | "REJECTED";
  notes?: string | null;
  tour: {
    id: string;
    title: string;
    slug: string;
    city: string;
    meetingPoint?: string | null;
    durationMin?: number | null;
    priceCents?: number | null;
    images: { url: string }[];
    createdBy: {
      id: string;
      name: string | null;
      email: string;
      image: string | null;
    };
  };
  user: {
    id: string;
    name: string | null;
    email: string;
    image: string | null;
  };
}

interface BookingsContentProps {
  userId: string;
}

export function BookingsContent({ userId }: BookingsContentProps) {
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const fetchBookings = async () => {
    try {
      const response = await fetch("/api/bookings");
      const data = await response.json();
      if (response.ok) {
        setBookings(data.bookings || []);
      }
    } catch (error) {
      console.error("Error fetching bookings:", error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchBookings();
  }, []);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const pendingBookings = bookings.filter((b) => b.status === "PENDING");
  const confirmedBookings = bookings.filter((b) => b.status === "CONFIRMED");
  const rejectedBookings = bookings.filter((b) => b.status === "REJECTED");

  return (
    <Tabs defaultValue="all" className="w-full">
      <TabsList className="grid w-full grid-cols-4">
        <TabsTrigger value="all">
          All ({bookings.length})
        </TabsTrigger>
        <TabsTrigger value="pending">
          Pending ({pendingBookings.length})
        </TabsTrigger>
        <TabsTrigger value="confirmed">
          Confirmed ({confirmedBookings.length})
        </TabsTrigger>
        <TabsTrigger value="rejected">
          Rejected ({rejectedBookings.length})
        </TabsTrigger>
      </TabsList>

      <TabsContent value="all" className="mt-6 space-y-4">
        {bookings.length === 0 ? (
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <Calendar className="size-6" />
              </EmptyMedia>
              <EmptyTitle>No bookings yet</EmptyTitle>
              <EmptyDescription>
                You haven&apos;t made any bookings. Browse tours to get started!
              </EmptyDescription>
            </EmptyHeader>
            <EmptyContent>
              <Link href="/tours">
                <Button>Browse Tours</Button>
              </Link>
            </EmptyContent>
          </Empty>
        ) : (
          bookings.map((booking) => (
            <BookingCard
              key={booking.id}
              booking={booking}
              currentUserId={userId}
              onUpdate={fetchBookings}
            />
          ))
        )}
      </TabsContent>

      <TabsContent value="pending" className="mt-6 space-y-4">
        {pendingBookings.length === 0 ? (
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <Calendar className="size-6" />
              </EmptyMedia>
              <EmptyTitle>No pending bookings</EmptyTitle>
              <EmptyDescription>
                You don&apos;t have any pending bookings at the moment.
              </EmptyDescription>
            </EmptyHeader>
          </Empty>
        ) : (
          pendingBookings.map((booking) => (
            <BookingCard
              key={booking.id}
              booking={booking}
              currentUserId={userId}
              onUpdate={fetchBookings}
            />
          ))
        )}
      </TabsContent>

      <TabsContent value="confirmed" className="mt-6 space-y-4">
        {confirmedBookings.length === 0 ? (
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <Calendar className="size-6" />
              </EmptyMedia>
              <EmptyTitle>No confirmed bookings</EmptyTitle>
              <EmptyDescription>
                You don&apos;t have any confirmed bookings yet.
              </EmptyDescription>
            </EmptyHeader>
          </Empty>
        ) : (
          confirmedBookings.map((booking) => (
            <BookingCard
              key={booking.id}
              booking={booking}
              currentUserId={userId}
              onUpdate={fetchBookings}
            />
          ))
        )}
      </TabsContent>

      <TabsContent value="rejected" className="mt-6 space-y-4">
        {rejectedBookings.length === 0 ? (
          <Empty>
            <EmptyHeader>
              <EmptyMedia variant="icon">
                <Calendar className="size-6" />
              </EmptyMedia>
              <EmptyTitle>No rejected bookings</EmptyTitle>
              <EmptyDescription>
                None of your bookings have been rejected.
              </EmptyDescription>
            </EmptyHeader>
          </Empty>
        ) : (
          rejectedBookings.map((booking) => (
            <BookingCard
              key={booking.id}
              booking={booking}
              currentUserId={userId}
              onUpdate={fetchBookings}
            />
          ))
        )}
      </TabsContent>
    </Tabs>
  );
}
