"use client";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { useQuery, useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Booking } from "../../../models/Booking";
import { formatDate } from "@/lib/utils";

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2, Search, ArrowLeft } from "lucide-react";
import Link from "next/link";
import Head from "next/head";
import { useRouter } from "next/navigation";
import { USER_TYPE } from "@/lib/constants";

const BookingDashboard = () => {
  const { user } = useAuth();
  const navigate = useRouter();
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");

  // Redirect if not an attendant or admin
  useEffect(() => {
    if (
      user &&
      user.userType !== USER_TYPE.ATTENDANT &&
      user.userType !== USER_TYPE.ADMIN
    ) {
      navigate.push("/");
    }
  }, [user, navigate]);

  // Fetch bookings
  const { data: bookings, isLoading } = useQuery<{
    data: Booking[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: ["/bookings"],
    enabled:
      !!user &&
      (user.userType === USER_TYPE.ATTENDANT ||
        user.userType === USER_TYPE.ADMIN),
  });

  // Update booking status mutation
  const updateBookingStatusMutation = useMutation({
    mutationFn: async ({ id, status }: { id: number; status: string }) => {
      const res = await apiRequest(
        "PATCH",
        `/attendant/bookings/${id}/status`,
        { status }
      );
      return res;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/bookings"] });
    },
  });

  // Apply filters
  const filteredBookings = bookings?.data.filter((booking) => {
    // Apply status filter
    if (statusFilter !== "all" && booking.status !== statusFilter) {
      return false;
    }

    // Apply search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        booking.fullName.toLowerCase().includes(query) ||
        booking.email.toLowerCase().includes(query) ||
        booking.phone.toLowerCase().includes(query)
      );
    }

    return true;
  });

  // Sort bookings by date (most recent first)
  const sortedBookings = [...(filteredBookings || [])].sort(
    (a, b) => new Date(b.visitDate).getTime() - new Date(a.visitDate).getTime()
  );

  // Handle status change
  const handleStatusChange = (bookingId: number, newStatus: string) => {
    updateBookingStatusMutation.mutate({ id: bookingId, status: newStatus });
  };

  // Get status badge color
  const getStatusBadge = (status: string) => {
    switch (status) {
      case "confirmed":
        return (
          <Badge className="bg-green-500 hover:bg-green-600">Confirmed</Badge>
        );
      case "pending":
        return (
          <Badge className="bg-yellow-500 hover:bg-yellow-600">Pending</Badge>
        );
      case "cancelled":
        return <Badge className="bg-red-500 hover:bg-red-600">Cancelled</Badge>;
      default:
        return <Badge>{status}</Badge>;
    }
  };

  return (
    <>
      <Head>
        <title>Booking Management | Badagry Museum</title>
        <meta name="robots" content="noindex, nofollow" />
      </Head>

      <section className="">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="mb-8">
            <Link href="/dashboard">
              <Button
                variant="ghost"
                className="text-primary hover:text-primary-dark"
              >
                <ArrowLeft className="mr-2 h-4 w-4" /> Back to Dashboard
              </Button>
            </Link>
          </div>

          <Card>
            <CardHeader>
              <CardTitle className="text-2xl font-heading">
                Booking Management
              </CardTitle>
              <CardDescription>
                View and manage all museum visit bookings. Use the filters to
                narrow down results.
              </CardDescription>
            </CardHeader>

            <CardContent>
              <div className="flex flex-col md:flex-row justify-between mb-6 space-y-4 md:space-y-0">
                <div className="flex flex-col md:flex-row gap-4">
                  <div>
                    <Select
                      value={statusFilter}
                      onValueChange={setStatusFilter}
                    >
                      <SelectTrigger className="w-[180px]">
                        <SelectValue placeholder="Filter by status" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">All Statuses</SelectItem>
                        <SelectItem value="pending">Pending</SelectItem>
                        <SelectItem value="confirmed">Confirmed</SelectItem>
                        <SelectItem value="cancelled">Cancelled</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="relative">
                    <Search
                      className="absolute top-32 left-2 h-5 w-5 text-muted-foreground"
                      style={{ top: 9 }}
                    />
                    <Input
                      placeholder="Search by name or email"
                      className="pl-8 w-full md:w-[300px]"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                    />
                  </div>
                </div>

                <div>
                  <p className="text-sm text-muted-foreground">
                    Showing {sortedBookings.length} of {bookings?.data.length}{" "}
                    bookings
                  </p>
                </div>
              </div>

              <Tabs defaultValue="table" className="w-full">
                <TabsList className="mb-4">
                  <TabsTrigger value="table">Table View</TabsTrigger>
                  <TabsTrigger value="upcoming">Upcoming Visits</TabsTrigger>
                </TabsList>

                <TabsContent value="table">
                  {isLoading ? (
                    <div className="flex justify-center items-center py-8">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    </div>
                  ) : sortedBookings.length === 0 ? (
                    <div className="text-center py-8">
                      <p className="text-muted-foreground">
                        No bookings found matching your filters
                      </p>
                    </div>
                  ) : (
                    <div className="rounded-md border">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead>Visit Date</TableHead>
                            <TableHead>Name</TableHead>
                            <TableHead>Contact</TableHead>
                            <TableHead>Group Size</TableHead>
                            <TableHead>Tour Type</TableHead>
                            <TableHead>Status</TableHead>
                            <TableHead>Actions</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {sortedBookings.map((booking) => (
                            <TableRow key={booking.id}>
                              <TableCell className="font-medium">
                                {formatDate(booking.visitDate)}
                              </TableCell>
                              <TableCell>{booking.fullName}</TableCell>
                              <TableCell>
                                <div>{booking.email}</div>
                                <div className="text-sm text-muted-foreground">
                                  {booking.phone}
                                </div>
                              </TableCell>
                              <TableCell>{booking.groupSize}</TableCell>
                              <TableCell>
                                {booking.tourType.charAt(0).toUpperCase() +
                                  booking.tourType.slice(1)}
                              </TableCell>
                              <TableCell>
                                {getStatusBadge(booking.status)}
                              </TableCell>
                              <TableCell>
                                <Select
                                  value={booking.status}
                                  onValueChange={(value) =>
                                    handleStatusChange(booking.id, value)
                                  }
                                  disabled={
                                    updateBookingStatusMutation.isPending
                                  }
                                >
                                  <SelectTrigger className="w-[130px]">
                                    <SelectValue placeholder="Change status" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="pending">
                                      Pending
                                    </SelectItem>
                                    <SelectItem value="confirmed">
                                      Confirm
                                    </SelectItem>
                                    <SelectItem value="cancelled">
                                      Cancel
                                    </SelectItem>
                                  </SelectContent>
                                </Select>
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="upcoming">
                  {isLoading ? (
                    <div className="flex justify-center items-center py-8">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {sortedBookings
                        .filter(
                          (booking) =>
                            booking.status === "confirmed" &&
                            new Date(booking.visitDate) >= new Date()
                        )
                        .map((booking) => (
                          <Card key={booking.id} className="overflow-hidden">
                            <div className="bg-primary h-2" />
                            <CardContent className="pt-6">
                              <div className="flex justify-between items-start mb-4">
                                <div>
                                  <h3 className="font-medium">
                                    {booking.fullName}
                                  </h3>
                                  <p className="text-sm text-muted-foreground">
                                    {booking.email}
                                  </p>
                                </div>
                                {getStatusBadge(booking.status)}
                              </div>

                              <div className="space-y-2 text-sm">
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">
                                    Visit Date:
                                  </span>
                                  <span className="font-medium">
                                    {formatDate(booking.visitDate)}
                                  </span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">
                                    Group Size:
                                  </span>
                                  <span>{booking.groupSize}</span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">
                                    Tour Type:
                                  </span>
                                  <span>
                                    {booking.tourType.charAt(0).toUpperCase() +
                                      booking.tourType.slice(1)}
                                  </span>
                                </div>
                                <div className="flex justify-between">
                                  <span className="text-muted-foreground">
                                    Phone:
                                  </span>
                                  en
                                  <span>{booking.phone}</span>
                                </div>
                              </div>

                              {booking.specialRequests && (
                                <div className="mt-4 pt-4 border-t">
                                  <p className="text-xs text-muted-foreground mb-1">
                                    Special Requests:
                                  </p>
                                  <p className="text-sm">
                                    {booking.specialRequests}
                                  </p>
                                </div>
                              )}

                              <div className="mt-4 pt-4 border-t flex justify-end">
                                <Select
                                  value={booking.status}
                                  onValueChange={(value) =>
                                    handleStatusChange(booking.id, value)
                                  }
                                  disabled={
                                    updateBookingStatusMutation.isPending
                                  }
                                >
                                  <SelectTrigger className="w-[130px]">
                                    <SelectValue placeholder="Change status" />
                                  </SelectTrigger>
                                  <SelectContent>
                                    <SelectItem value="pending">
                                      Pending
                                    </SelectItem>
                                    <SelectItem value="confirmed">
                                      Confirm
                                    </SelectItem>
                                    <SelectItem value="cancelled">
                                      Cancel
                                    </SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </CardContent>
                          </Card>
                        ))}

                      {sortedBookings.filter(
                        (booking) =>
                          booking.status === "confirmed" &&
                          new Date(booking.visitDate) >= new Date()
                      ).length === 0 && (
                        <div className="col-span-full text-center py-8">
                          <p className="text-muted-foreground">
                            No upcoming confirmed visits
                          </p>
                        </div>
                      )}
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>
        </div>
      </section>
    </>
  );
};

export default BookingDashboard;
