"use client";
import { useEffect, useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { useToast } from "@/hooks/use-toast";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent } from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import ForumPost from "./ForumPost";
import { Skeleton } from "@/components/ui/skeleton";
import { Loader2 } from "lucide-react";
import { Post } from "@/models/Post";
import { API_URL } from "@/lib/constants";

// Form validation schema
const forumPostSchema = z.object({
  title: z.string().min(3, "Title must be at least 3 characters"),
  content: z.string().min(10, "Message must be at least 10 characters"),
  isAttendantOnly: z.boolean(),
  authorId: z.string().optional(),
});

type ForumPostFormValues = z.infer<typeof forumPostSchema>;

const CommunityForum = () => {
  const { user } = useAuth();
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState("public");

  // WebSocket setup for real-time updates
  const [socket, setSocket] = useState<WebSocket | null>(null);

  useEffect(() => {
    // Connect to WebSocket server
    const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
    const wsUrl = `${protocol}//${window.location.host}/ws`;
    const newSocket = new WebSocket(wsUrl);

    newSocket.onopen = () => {
      console.log("Connected to WebSocket server");
    };

    newSocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === "new_post" || data.type === "new_comment") {
        queryClient.invalidateQueries({ queryKey: ["/posts"] });
      }
    };

    newSocket.onclose = () => {
      console.log("Disconnected from WebSocket server");
    };

    setSocket(newSocket);

    return () => {
      newSocket.close();
    };
  }, []);

  // Form setup
  const form = useForm<ForumPostFormValues>({
    resolver: zodResolver(forumPostSchema),
    defaultValues: {
      title: "",
      content: "",
      isAttendantOnly: activeTab === "attendant",
    },
  });

  // Update when tab changes
  useEffect(() => {
    form.setValue("isAttendantOnly", activeTab === "attendant");
  }, [activeTab, form]);

  // Fetch posts based on the active tab
  const { data: posts = { data: [], hasMore: false, total: 0 }, isLoading } =
    useQuery<{
      data: Post[];
      hasMore: boolean;
      total: number;
    }>({
      queryKey: ["/posts", activeTab === "public" ? "false" : "true"],
      queryFn: async ({ queryKey }) => {
        const attendantOnly = queryKey[1];
        const response = await fetch(
          API_URL + `/posts?attendantOnly=${attendantOnly}`
        );
        if (!response.ok) {
          throw new Error("Failed to fetch posts");
        }

        const posts = await response.json();
        console.log({ posts });
        return posts;
      },
      enabled:
        activeTab === "public" ||
        user?.userType === "attendant" ||
        user?.userType === "admin",
    });

  // Mutation for creating a new post
  const createPostMutation = useMutation({
    mutationFn: async (data: ForumPostFormValues) => {
      const res = await apiRequest("POST", "/posts", data);
      return res;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/posts"] });
      toast({
        title: "Post created successfully!",
        description: "Your message has been posted to the forum.",
      });
      form.reset();
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to create post",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const onSubmit = (data: ForumPostFormValues) => {
    if (!user) {
      toast({
        title: "Authentication required",
        description: "You must be logged in to post to the forum.",
        variant: "destructive",
      });
      return;
    }

    console.log("\n\n forum post data: ", data, "\n\n");
    createPostMutation.mutate({ ...data, authorId: String(user?.id) });
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <Tabs
        defaultValue="public"
        value={activeTab}
        onValueChange={setActiveTab}
        className="w-full"
      >
        <TabsList className="grid w-full grid-cols-2 mb-8">
          <TabsTrigger value="public">Public Forum</TabsTrigger>
          {(user?.userType === "attendant" || user?.userType === "admin") && (
            <TabsTrigger value="attendant">Attendants' Forum</TabsTrigger>
          )}
        </TabsList>

        <TabsContent value="public" className="space-y-8">
          <Card>
            <CardContent className="p-6">
              <h3 className="text-2xl font-bold text-neutral-dark mb-6 font-heading">
                Join the Conversation
              </h3>

              {user ? (
                <Form {...form}>
                  <form
                    onSubmit={form.handleSubmit(onSubmit)}
                    className="space-y-6"
                  >
                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Topic</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="What would you like to discuss?"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="content"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Message</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="Share your thoughts, questions, or experiences..."
                              className="h-32"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {(user?.userType === "attendant" ||
                      user?.userType === "admin") && (
                      <FormField
                        control={form.control}
                        name="isAttendantOnly"
                        render={({ field }) => (
                          <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                            <FormControl>
                              <Checkbox
                                checked={field.value}
                                onCheckedChange={field.onChange}
                                disabled={activeTab === "attendant"}
                              />
                            </FormControl>
                            <div className="space-y-1 leading-none">
                              <FormLabel>
                                Post to attendants' forum only
                              </FormLabel>
                            </div>
                          </FormItem>
                        )}
                      />
                    )}

                    <Button
                      type="submit"
                      className="w-full bg-primary hover:bg-primary-dark"
                      disabled={createPostMutation.isPending}
                    >
                      {createPostMutation.isPending ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Posting...
                        </>
                      ) : (
                        "Post to Forum"
                      )}
                    </Button>
                  </form>
                </Form>
              ) : (
                <div className="text-center py-6 bg-neutral-light rounded-md">
                  <p className="text-gray-600 mb-4">
                    You need to be logged in to join the conversation.
                  </p>
                  <Button asChild className="bg-primary hover:bg-primary-dark">
                    <a href="/auth">Sign In or Register</a>
                  </Button>
                </div>
              )}
            </CardContent>
          </Card>

          <div className="space-y-6">
            <h3 className="text-2xl font-bold text-neutral-dark font-heading">
              Community Forum
            </h3>

            {isLoading ? (
              Array(3)
                .fill(0)
                .map((_, index) => (
                  <Card key={index} className="mb-4">
                    <CardContent className="p-6">
                      <div className="flex items-start">
                        <div className="flex-shrink-0 mr-4">
                          <Skeleton className="h-10 w-10 rounded-full" />
                        </div>
                        <div className="w-full">
                          <Skeleton className="h-5 w-1/4 mb-1" />
                          <Skeleton className="h-4 w-1/6 mb-2" />
                          <Skeleton className="h-4 w-full mb-1" />
                          <Skeleton className="h-4 w-full mb-1" />
                          <Skeleton className="h-4 w-3/4 mb-3" />
                          <div className="flex space-x-4">
                            <Skeleton className="h-8 w-16" />
                            <Skeleton className="h-8 w-16" />
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))
            ) : posts.data?.length === 0 ? (
              <div className="bg-white p-8 rounded-lg shadow-sm text-center">
                <p className="text-gray-600">
                  No posts yet. Be the first to start a discussion!
                </p>
              </div>
            ) : (
              posts.data?.map((post) => <ForumPost key={post.id} post={post} />)
            )}
          </div>
        </TabsContent>

        {(user?.userType === "attendant" || user?.userType === "admin") && (
          <TabsContent value="attendant" className="space-y-8">
            <Card>
              <CardContent className="p-6">
                <h3 className="text-2xl font-bold text-neutral-dark mb-6 font-heading">
                  Attendants' Discussion
                </h3>

                <Form {...form}>
                  <form
                    onSubmit={form.handleSubmit(onSubmit)}
                    className="space-y-6"
                  >
                    <FormField
                      control={form.control}
                      name="title"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Topic</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="What would you like to discuss with other attendants?"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="content"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>Message</FormLabel>
                          <FormControl>
                            <Textarea
                              placeholder="Share professional insights, questions, or experiences..."
                              className="h-32"
                              {...field}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <input type="hidden" name="isAttendantOnly" value="true" />

                    <Button
                      type="submit"
                      className="w-full bg-primary hover:bg-primary-dark"
                      disabled={createPostMutation.isPending}
                      onClick={() => form.setValue("isAttendantOnly", true)}
                    >
                      {createPostMutation.isPending ? (
                        <>
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          Posting...
                        </>
                      ) : (
                        "Post to Attendants' Forum"
                      )}
                    </Button>
                  </form>
                </Form>
              </CardContent>
            </Card>

            <div className="space-y-6">
              <h3 className="text-2xl font-bold text-neutral-dark font-heading">
                Attendants' Forum
              </h3>

              {isLoading ? (
                Array(3)
                  .fill(0)
                  .map((_, index) => (
                    <Card key={index} className="mb-4">
                      <CardContent className="p-6">
                        <div className="flex items-start">
                          <div className="flex-shrink-0 mr-4">
                            <Skeleton className="h-10 w-10 rounded-full" />
                          </div>
                          <div className="w-full">
                            <Skeleton className="h-5 w-1/4 mb-1" />
                            <Skeleton className="h-4 w-1/6 mb-2" />
                            <Skeleton className="h-4 w-full mb-1" />
                            <Skeleton className="h-4 w-full mb-1" />
                            <Skeleton className="h-4 w-3/4 mb-3" />
                            <div className="flex space-x-4">
                              <Skeleton className="h-8 w-16" />
                              <Skeleton className="h-8 w-16" />
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))
              ) : posts.data?.length === 0 ? (
                <div className="bg-white p-8 rounded-lg shadow-sm text-center">
                  <p className="text-gray-600">
                    No attendant-only posts yet. Start a professional
                    discussion!
                  </p>
                </div>
              ) : (
                posts.data?.map((post) => (
                  <ForumPost key={post.id} post={post} />
                ))
              )}
            </div>
          </TabsContent>
        )}
      </Tabs>
    </div>
  );
};

export default CommunityForum;
