"use client";
import { useEffect } from "react";
import { useAuth } from "@/hooks/use-auth";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Calendar, Users, MessageSquare, BookOpen, Clock } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Booking } from "../../../models/Booking";
import { Post } from "../../../models/Post";
import { formatDate } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import Head from "next/head";
import { useRouter } from "next/navigation";
import { USER_TYPE } from "@/lib/constants";

const DashboardPage = () => {
  const { user } = useAuth();
  const navigate = useRouter();

  // 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: isLoadingBooking,
    isFetching: isFetchingBooking,
    error: errorBooking,
  } = useQuery<{
    data: Booking[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: ["/bookings"],
    enabled:
      !!user &&
      (user.userType === USER_TYPE.ATTENDANT ||
        user.userType === USER_TYPE.ADMIN),
  });

  // Fetch recent posts
  const {
    data: posts,
    isLoading: isLoadingPost,
    isFetching: isFetchingPost,
    error: errorPost,
  } = useQuery<{
    data: Post[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: ["/posts"],
    enabled:
      !!user &&
      (user.userType === USER_TYPE.ATTENDANT ||
        user.userType === USER_TYPE.ADMIN),
  });

  if (
    isLoadingBooking ||
    isFetchingBooking ||
    isLoadingPost ||
    isFetchingPost ||
    errorPost ||
    errorBooking
  ) {
    return (
      <div className="py-16 text-center">
        <p className="text-destructive">
          Error loading gallery items. Please try again later.
        </p>
      </div>
    );
  }

  // Count pending bookings
  const pendingBookings = bookings?.data.filter(
    (booking) => booking.status === "pending"
  );

  // Get upcoming bookings (next 7 days)
  const now = new Date();
  const oneWeekLater = new Date(now);
  oneWeekLater.setDate(now.getDate() + 7);

  const upcomingBookings = bookings?.data
    .filter((booking) => {
      const visitDate = new Date(booking.visitDate);
      return (
        visitDate >= now &&
        visitDate <= oneWeekLater &&
        booking.status === "confirmed"
      );
    })
    .sort(
      (a, b) =>
        new Date(a.visitDate).getTime() - new Date(b.visitDate).getTime()
    );

  // Get recent posts
  const recentPosts = [...(posts?.data || [])]
    .sort(
      (a, b) =>
        new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    )
    .slice(0, 5);

  return (
    <>
      <Head>
        <title>Dashboard | 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="flex flex-col md:flex-row justify-between items-start md:items-center mb-8">
            <div>
              <h1 className="text-3xl font-bold text-primary font-heading">
                Welcome, {user?.fullName}
              </h1>
              <p className="text-gray-600">
                {user?.userType === USER_TYPE.ADMIN
                  ? "Museum Administrator Dashboard"
                  : "Museum Attendant Dashboard"}
              </p>
            </div>
            <div className="mt-4 md:mt-0">
              <p className="text-sm text-gray-500">
                {new Date().toLocaleDateString("en-US", {
                  weekday: "long",
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </p>
            </div>
          </div>

          {/* Dashboard quick stats */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center space-x-4">
                  <div className="p-2 bg-primary/10 rounded-full">
                    <Calendar className="h-6 w-6 text-primary" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      Pending Bookings
                    </p>
                    <h3 className="text-2xl font-bold">
                      {(pendingBookings || []).length}
                    </h3>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center space-x-4">
                  <div className="p-2 bg-accent/10 rounded-full">
                    <Clock className="h-6 w-6 text-accent" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      Upcoming Tours
                    </p>
                    <h3 className="text-2xl font-bold">
                      {(upcomingBookings || []).length}
                    </h3>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center space-x-4">
                  <div className="p-2 bg-primary-light/10 rounded-full">
                    <MessageSquare className="h-6 w-6 text-primary-light" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      New Forum Posts
                    </p>
                    <h3 className="text-2xl font-bold">{recentPosts.length}</h3>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="pt-6">
                <div className="flex items-center space-x-4">
                  <div className="p-2 bg-primary-dark/10 rounded-full">
                    <Users className="h-6 w-6 text-primary-dark" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-500">
                      Total Visitors
                    </p>
                    <h3 className="text-2xl font-bold">
                      {bookings?.data.length}
                    </h3>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          <Tabs defaultValue="overview">
            <TabsList className="mb-6">
              <TabsTrigger value="overview">Overview</TabsTrigger>
              <TabsTrigger value="bookings">Bookings</TabsTrigger>
              <TabsTrigger value="community">Community</TabsTrigger>
            </TabsList>

            <TabsContent value="overview">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Upcoming Bookings */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center">
                      <Calendar className="h-5 w-5 mr-2 text-primary" />
                      Upcoming Bookings
                    </CardTitle>
                    <CardDescription>
                      Tours scheduled for the next 7 days
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    {(upcomingBookings || []).length === 0 ? (
                      <p className="text-gray-500 text-center py-4">
                        No upcoming bookings for the next 7 days
                      </p>
                    ) : (
                      <ul className="space-y-4">
                        {(upcomingBookings || []).slice(0, 5).map((booking) => (
                          <li
                            key={booking.id}
                            className="border-b border-gray-100 pb-3 last:border-0 last:pb-0"
                          >
                            <div className="flex justify-between">
                              <div>
                                <p className="font-medium">
                                  {booking.fullName}
                                </p>
                                <p className="text-sm text-gray-500">
                                  {booking.email}
                                </p>
                              </div>
                              <div className="text-right">
                                <p className="text-sm font-medium">
                                  {formatDate(booking.visitDate)}
                                </p>
                                <p className="text-xs text-gray-500">
                                  Group: {booking.groupSize}
                                </p>
                              </div>
                            </div>
                            <p className="text-xs mt-1">
                              <span className="font-medium">Tour Type:</span>{" "}
                              {booking.tourType.charAt(0).toUpperCase() +
                                booking.tourType.slice(1)}
                            </p>
                          </li>
                        ))}
                      </ul>
                    )}

                    <div className="mt-4 text-right">
                      <Link
                        href="/dashboard/bookings"
                        className="text-sm text-primary hover:text-primary-dark font-medium"
                      >
                        View all bookings
                      </Link>
                    </div>
                  </CardContent>
                </Card>

                {/* Recent Forum Activity */}
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center">
                      <MessageSquare className="h-5 w-5 mr-2 text-primary" />
                      Recent Forum Activity
                    </CardTitle>
                    <CardDescription>
                      Latest posts from the community
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    {recentPosts.length === 0 ? (
                      <p className="text-gray-500 text-center py-4">
                        No recent forum activity
                      </p>
                    ) : (
                      <ul className="space-y-4">
                        {recentPosts.slice(0, 5).map((post) => (
                          <li
                            key={post.id}
                            className="border-b border-gray-100 pb-3 last:border-0 last:pb-0"
                          >
                            <div className="flex justify-between">
                              <p className="font-medium">{post.title}</p>
                              <p className="text-xs text-gray-500">
                                {new Date(post.createdAt).toLocaleDateString()}
                              </p>
                            </div>
                            <p className="text-sm mt-1 text-gray-600 line-clamp-1">
                              {post.content}
                            </p>
                            <p className="text-xs mt-1 text-gray-500">
                              by {post.author?.fullName || "Unknown"}
                              {post.isAttendantOnly && " (Attendants Only)"}
                            </p>
                          </li>
                        ))}
                      </ul>
                    )}

                    <div className="mt-4 text-right">
                      <Link
                        href="/dashboard/posts"
                        className="text-sm text-primary hover:text-primary-dark font-medium"
                      >
                        View all posts
                      </Link>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </TabsContent>

            <TabsContent value="bookings">
              <Card>
                <CardHeader>
                  <CardTitle>Bookings Management</CardTitle>
                  <CardDescription>
                    View and manage all museum visit bookings. For more details
                    and actions, visit the full bookings page.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-center py-8">
                    <BookOpen className="h-12 w-12 mx-auto text-primary opacity-50 mb-4" />
                    <h3 className="text-lg font-medium mb-2">
                      Detailed Booking Management
                    </h3>
                    <p className="text-gray-500 mb-4">
                      Access the full booking management interface to view,
                      confirm, or cancel bookings.
                    </p>
                    <Link href="/dashboard/bookings">
                      <Button className="bg-primary hover:bg-primary-dark">
                        Go to Bookings Management
                      </Button>
                    </Link>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>

            <TabsContent value="community">
              <Card>
                <CardHeader>
                  <CardTitle>Community Management</CardTitle>
                  <CardDescription>
                    Manage forum posts and engage with the community. For more
                    options, visit the community management page.
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-center py-8">
                    <MessageSquare className="h-12 w-12 mx-auto text-primary opacity-50 mb-4" />
                    <h3 className="text-lg font-medium mb-2">
                      Forum Moderation
                    </h3>
                    <p className="text-gray-500 mb-4">
                      Access the full community management interface to moderate
                      posts and participate in discussions.
                    </p>
                    <Link href="/dashboard/posts">
                      <Button className="bg-primary hover:bg-primary-dark">
                        Go to Community Management
                      </Button>
                    </Link>
                  </div>
                </CardContent>
              </Card>
            </TabsContent>
          </Tabs>
        </div>
      </section>
    </>
  );
};

export default DashboardPage;
