// app/dashboard/users/[userId]/hooks/useUserDetails.ts

import { useState, useEffect } from "react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

export function useUserDetails(userId: string) {
    const router = useRouter();
    const [user, setUser] = useState<TelegramUser | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [conversations, setConversations] = useState<Conversation[]>([]);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);

    const fetchConversationDetails = async (conversationId: string) => {
        try {
            const res = await fetch(`/api/users/${userId}/conversations/${conversationId}`);

            if (!res.ok) {
                throw new Error("Failed to fetch conversation details");
            }

            const data = await res.json();
            return data;
        } catch (error) {
            console.error(`Error loading conversation ${conversationId}:`, error);
            return null;
        }
    };

    // Add a new function to refresh only the conversations
    const refreshConversations = async () => {
        try {
            // Get updated conversations from the API
            if (!user) return;

            const res = await fetch(`/api/users/${userId}/conversations`);
            if (!res.ok) {
                throw new Error("Failed to fetch conversations");
            }

            const data = await res.json();
            if (data.conversations && data.conversations.length > 0) {
                const conversationsWithMessages = await Promise.all(
                    data.conversations.map(async (conv: Conversation) => {
                        const convDetail = await fetchConversationDetails(conv.id);
                        return convDetail;
                    })
                );

                const sortedConversations = conversationsWithMessages
                    .filter(Boolean)
                    .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());

                setConversations(sortedConversations);
            }
        } catch (error) {
            console.error("Error refreshing conversations:", error);
            // Don't show toast here to avoid spamming the user every 3 seconds if there's an error
        }
    };

    const fetchUser = async () => {
        setIsLoading(true);
        try {
            const res = await fetch(`/api/users/${userId}`);

            if (!res.ok) {
                if (res.status === 404) {
                    toast.error("کاربر پیدا نشد");
                    router.push("/dashboard/users");
                    return;
                }
                throw new Error("Failed to fetch user");
            }

            const data = await res.json();
            setUser(data);

            if (data.conversations && data.conversations.length > 0) {
                const conversationsWithMessages = await Promise.all(
                    data.conversations.map(async (conv: Conversation) => {
                        const convDetail = await fetchConversationDetails(conv.id);
                        return convDetail;
                    })
                );
                const sortedConversations = conversationsWithMessages
                    .filter(Boolean)
                    .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());

                setConversations(sortedConversations);
            }
        } catch (error) {
            console.error("Error loading user:", error);
            toast.error("بارگیری جزئیات کاربر با مشکل مواجه شد");
        } finally {
            setIsLoading(false);
        }
    };

    const handleRespondentChange = async (isAi: boolean) => {
        try {
            const res = await fetch(`/api/users/${userId}`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    respondent: isAi ? "admin" : "ai"
                }),
            });
            if (!res.ok) {
                throw new Error("Failed to update respondent");
            }
            setUser(prev => prev ? { ...prev, respondent: isAi ? "admin" : "ai" } : null);
            toast.success(`پاسخ‌دهنده با موفقیت به ${isAi ? "ادمین" : "هوش مصنوعی"} تغییر یافت`);

        } catch (error) {
            console.error("Error updating respondent:", error);
            toast.error("تغییر پاسخ‌دهنده با مشکل مواجه شد");
        }
    };

    const handleDeleteUser = async () => {
        setIsDeleting(true);
        try {
            const res = await fetch(`/api/users/${userId}`, {
                method: "DELETE",
            });

            if (!res.ok) {
                throw new Error("Failed to delete user");
            }

            toast.success("کاربر با موفقیت حذف شد");
            router.push("/dashboard/users");
        } catch (error) {
            console.error("Error deleting user:", error);
            toast.error("حذف کاربر با مشکل مواجه شد");
            setIsDeleting(false);
            setDeleteDialogOpen(false);
        }
    };

    useEffect(() => {
        fetchUser();
    }, [userId]);

    return {
        user,
        isLoading,
        conversations,
        deleteDialogOpen,
        isDeleting,
        setDeleteDialogOpen,
        handleDeleteUser,
        handleRespondentChange,
        fetchUser,
        refreshConversations, 
        setConversations,
    };
}