"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 { formatDate, timeAgo } 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 { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Loader2,
  Search,
  ArrowLeft,
  MessageSquare,
  Plus,
  Eye,
  AlertTriangle,
} from "lucide-react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/hooks/use-toast";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import Link from "next/link";
import { CreatePostFormValues, createPostSchema, Post } from "@/models/Post";
import { Comment } from "@/models/Comment";
import Head from "next/head";
import { useRouter } from "next/navigation";
import { CloudinaryUpload } from "@/components/shared/CloudinaryUploader";
import { USER_TYPE } from "@/lib/constants";

const PostsDashboard = () => {
  const { user } = useAuth();
  const navigate = useRouter();
  const { toast } = useToast();
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [forumType, setForumType] = useState<"public" | "attendant">("public");
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);

  // 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 posts based on forum type
  const { data: posts, isLoading } = useQuery<{
    data: Post[];
    total: number;
    hasMore: boolean;
  }>({
    queryKey: ["/posts", forumType === "public" ? "false" : "true"],
    queryFn: async ({ queryKey }) => {
      const attendantOnly = queryKey[1];
      const response = await fetch(`/posts?attendantOnly=${attendantOnly}`);
      if (!response.ok) {
        throw new Error("Failed to fetch posts");
      }
      return response.json();
    },
    enabled:
      !!user &&
      (user.userType === USER_TYPE.ATTENDANT ||
        user.userType === USER_TYPE.ADMIN),
  });

  // Create post mutation
  const createPostMutation = useMutation({
    mutationFn: async (data: CreatePostFormValues) => {
      const res = await apiRequest("POST", "/posts", data);
      return res;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/posts"] });
      setIsCreateDialogOpen(false);
      toast({
        title: "Post created successfully!",
        description: "Your post has been published to the forum.",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to create post",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  // Create post form
  const form = useForm<CreatePostFormValues | any>({
    resolver: zodResolver(createPostSchema),
    defaultValues: {
      title: "",
      content: "",
      isAttendantOnly: forumType === USER_TYPE.ATTENDANT,
    },
  });

  // Reset form when forum type changes
  useEffect(() => {
    form.setValue("isAttendantOnly", forumType === USER_TYPE.ATTENDANT);
  }, [forumType, form]);

  // Apply search filter
  const filteredPosts = posts?.data.filter((post) => {
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        post.title.toLowerCase().includes(query) ||
        post.content.toLowerCase().includes(query) ||
        post.author?.fullName?.toLowerCase().includes(query) ||
        post.author?.username?.toLowerCase().includes(query)
      );
    }
    return true;
  });

  // Sort posts by date (most recent first)
  const sortedPosts = [...(filteredPosts || [])].sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  );

  // Handle post form submission
  const onSubmit = (data: CreatePostFormValues) => {
    createPostMutation.mutate(data);
  };

  return (
    <>
      <Head>
        <title>Community 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>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle className="text-2xl font-heading">
                    Community Management
                  </CardTitle>
                  <CardDescription>
                    Manage forum posts and engage with the community. Create
                    educational content and respond to visitor inquiries.
                  </CardDescription>
                </div>
                <Button
                  onClick={() => setIsCreateDialogOpen(true)}
                  className="bg-primary hover:bg-primary-dark"
                >
                  <Plus className="mr-2 h-4 w-4" /> Create Post
                </Button>
              </div>
            </CardHeader>

            <CardContent>
              <Tabs
                defaultValue="public"
                value={forumType}
                onValueChange={(value) =>
                  setForumType(value as "public" | "attendant")
                }
                className="w-full"
              >
                <div className="flex flex-col md:flex-row justify-between mb-6 space-y-4 md:space-y-0">
                  <TabsList className="mb-0">
                    <TabsTrigger value="public">Public Forum</TabsTrigger>
                    <TabsTrigger value="attendant">
                      Attendants' Forum
                    </TabsTrigger>
                  </TabsList>

                  <div className="relative">
                    <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search posts..."
                      className="pl-8 w-full md:w-[300px]"
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                    />
                  </div>
                </div>

                <TabsContent value="public">
                  {isLoading ? (
                    <div className="flex justify-center items-center py-8">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    </div>
                  ) : sortedPosts.length === 0 ? (
                    <div className="text-center py-8">
                      <MessageSquare className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                      <p className="text-muted-foreground">
                        No public forum posts found
                      </p>
                      <Button
                        onClick={() => setIsCreateDialogOpen(true)}
                        className="mt-4 bg-primary hover:bg-primary-dark"
                      >
                        Create Your First Post
                      </Button>
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {sortedPosts.map((post) => (
                        <Card
                          key={post.id}
                          className="hover:shadow-md transition-shadow"
                        >
                          <CardContent className="p-6">
                            <div className="flex justify-between items-start mb-2">
                              <div className="flex items-center">
                                <Avatar className="h-10 w-10 mr-3">
                                  <AvatarImage
                                    src={`${post.author?.profileImage}`}
                                    alt={post.author?.fullName || "User"}
                                  />
                                  <AvatarFallback className="bg-primary text-white">
                                    {post.author?.fullName
                                      ?.charAt(0)
                                      .toUpperCase() || "U"}
                                  </AvatarFallback>
                                </Avatar>
                                <div>
                                  <h3 className="font-medium">
                                    {post.author?.fullName || "Anonymous"}
                                  </h3>
                                  <p className="text-xs text-muted-foreground">
                                    {timeAgo(post.createdAt)}
                                  </p>
                                </div>
                              </div>
                              {post.isAttendantOnly && (
                                <Badge
                                  variant="outline"
                                  className="bg-primary/10 text-primary"
                                >
                                  Attendants Only
                                </Badge>
                              )}
                            </div>

                            <h3 className="text-lg font-bold mb-2">
                              {post.title}
                            </h3>
                            <p className="text-gray-600 line-clamp-3">
                              {post.content}
                            </p>

                            <div className="mt-4 flex justify-between items-center">
                              <div className="flex items-center text-sm text-muted-foreground">
                                <MessageSquare className="h-4 w-4 mr-1" />
                                <span>
                                  {post.comments?.length || 0} comments
                                </span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="text-primary hover:text-primary-dark"
                                onClick={() => setSelectedPost(post)}
                              >
                                <Eye className="h-4 w-4 mr-2" /> View Details
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}
                </TabsContent>

                <TabsContent value="attendant">
                  {isLoading ? (
                    <div className="flex justify-center items-center py-8">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                    </div>
                  ) : sortedPosts.length === 0 ? (
                    <div className="text-center py-8">
                      <MessageSquare className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
                      <p className="text-muted-foreground">
                        No attendant forum posts found
                      </p>
                      <Button
                        onClick={() => setIsCreateDialogOpen(true)}
                        className="mt-4 bg-primary hover:bg-primary-dark"
                      >
                        Create Your First Post
                      </Button>
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {sortedPosts.map((post) => (
                        <Card
                          key={post.id}
                          className="hover:shadow-md transition-shadow"
                        >
                          <CardContent className="p-6">
                            <div className="flex justify-between items-start mb-2">
                              <div className="flex items-center">
                                <Avatar className="h-10 w-10 mr-3">
                                  <AvatarImage
                                    src={`${post.author?.profileImage}`}
                                    alt={post.author?.fullName || "User"}
                                  />
                                  <AvatarFallback className="bg-primary text-white">
                                    {post.author?.fullName
                                      ?.charAt(0)
                                      .toUpperCase() || "U"}
                                  </AvatarFallback>
                                </Avatar>
                                <div>
                                  <h3 className="font-medium">
                                    {post.author?.fullName || "Anonymous"}
                                  </h3>
                                  <p className="text-xs text-muted-foreground">
                                    {timeAgo(post.createdAt)}
                                  </p>
                                </div>
                              </div>
                              <Badge
                                variant="outline"
                                className="bg-primary/10 text-primary"
                              >
                                Attendants Only
                              </Badge>
                            </div>

                            <h3 className="text-lg font-bold mb-2">
                              {post.title}
                            </h3>
                            <p className="text-gray-600 line-clamp-3">
                              {post.content}
                            </p>

                            <div className="mt-4 flex justify-between items-center">
                              <div className="flex items-center text-sm text-muted-foreground">
                                <MessageSquare className="h-4 w-4 mr-1" />
                                <span>
                                  {post.comments?.length || 0} comments
                                </span>
                              </div>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="text-primary hover:text-primary-dark"
                                onClick={() => setSelectedPost(post)}
                              >
                                <Eye className="h-4 w-4 mr-2" /> View Details
                              </Button>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>
        </div>
      </section>

      {/* Create Post Dialog */}
      <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
        <DialogContent className="sm:max-w-xl">
          <DialogHeader>
            <DialogTitle>Create New Post</DialogTitle>
            <DialogDescription>
              Share educational content, announcements, or start a discussion
              with{" "}
              {forumType === USER_TYPE.ATTENDANT
                ? "other attendants"
                : "visitors"}
              .
            </DialogDescription>
          </DialogHeader>

          <CloudinaryUpload />
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Title</FormLabel>
                    <FormControl>
                      <Input placeholder="Enter post title" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="content"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Content</FormLabel>
                    <FormControl>
                      <Textarea
                        placeholder="Write your post content here..."
                        className="min-h-[200px]"
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="isAttendantOnly"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                    <FormControl>
                      <input
                        type="checkbox"
                        checked={field.value}
                        onChange={field.onChange}
                        className="hidden"
                      />
                    </FormControl>
                    <div className="space-y-1 leading-none">
                      <FormLabel>
                        {forumType === USER_TYPE.ATTENDANT ? (
                          <Badge
                            variant="outline"
                            className="bg-primary/10 text-primary pointer-events-none"
                          >
                            Attendants Only
                          </Badge>
                        ) : (
                          <Badge
                            variant="outline"
                            className="bg-gray-100 text-gray-500 pointer-events-none"
                          >
                            Public Forum
                          </Badge>
                        )}
                      </FormLabel>
                    </div>
                  </FormItem>
                )}
              />

              <div className="flex justify-end space-x-2 pt-4">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsCreateDialogOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  className="bg-primary hover:bg-primary-dark"
                  disabled={createPostMutation.isPending}
                >
                  {createPostMutation.isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Creating...
                    </>
                  ) : (
                    "Create Post"
                  )}
                </Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>

      {/* Post Details Dialog */}
      <Dialog
        open={!!selectedPost}
        onOpenChange={(open) => !open && setSelectedPost(null)}
      >
        <DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
          {selectedPost && (
            <>
              <DialogHeader>
                <DialogTitle>{selectedPost.title}</DialogTitle>
                <div className="flex justify-between items-center">
                  <div className="flex items-center mt-2">
                    <Avatar className="h-8 w-8 mr-2">
                      <AvatarImage
                        src={`${selectedPost.author?.profileImage}`}
                        alt={selectedPost.author?.fullName || "User"}
                      />
                      <AvatarFallback className="bg-primary text-white text-xs">
                        {selectedPost.author?.fullName
                          ?.charAt(0)
                          .toUpperCase() || "U"}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <p className="text-sm font-medium">
                        {selectedPost.author?.fullName}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {formatDate(selectedPost.createdAt)}
                      </p>
                    </div>
                  </div>
                  {selectedPost.isAttendantOnly && (
                    <Badge
                      variant="outline"
                      className="bg-primary/10 text-primary"
                    >
                      Attendants Only
                    </Badge>
                  )}
                </div>
              </DialogHeader>

              <div className="my-4 whitespace-pre-line">
                {selectedPost.content}
              </div>

              <div className="border-t pt-4 mt-4">
                <h4 className="font-medium mb-4">
                  Comments ({selectedPost.comments?.length || 0})
                </h4>
                {selectedPost.comments && selectedPost.comments.length > 0 ? (
                  <div className="space-y-4">
                    {selectedPost.comments.map((comment: Comment) => (
                      <div
                        key={comment.id}
                        className="bg-muted/30 p-3 rounded-md"
                      >
                        <div className="flex items-center mb-2">
                          <Avatar className="h-6 w-6 mr-2">
                            <AvatarImage
                              src={`${comment.author?.profileImage}`}
                              alt={comment.author?.fullName || "User"}
                            />
                            <AvatarFallback className="bg-primary-light text-white text-xs">
                              {comment.author?.fullName
                                ?.charAt(0)
                                .toUpperCase() || "U"}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <p className="text-sm font-medium">
                              {comment.author?.fullName}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {timeAgo(comment.createdAt)}
                            </p>
                          </div>
                        </div>
                        <p className="text-sm">{comment.content}</p>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-muted-foreground text-center py-2">
                    No comments yet
                  </p>
                )}
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
};

export default PostsDashboard;
