import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { usePage } from '@inertiajs/react';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription } from "@/Components/ui/sheet";
import { ScrollArea } from "@/Components/ui/scroll-area";
import { Skeleton } from "@/Components/ui/skeleton";
import { Button } from "@/Components/ui/button";
import { 
    AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, 
    AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle 
} from "@/Components/ui/alert-dialog";
import { Loader2, MessageSquare } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import useTranslation from '@/hooks/useTranslation'; 

// Sub-components
import CommentItem from './Comments/CommentItem';
import CommentInput from './Comments/CommentInput';

function useMediaQuery(query) {
    const [matches, setMatches] = useState(false);
    useEffect(() => {
        const media = window.matchMedia(query);
        if (media.matches !== matches) setMatches(media.matches);
        const listener = () => setMatches(media.matches);
        window.addEventListener("resize", listener);
        return () => window.removeEventListener("resize", listener);
    }, [matches, query]);
    return matches;
}

export default function CommentsSheet({ postId, open, onOpenChange, initialCount = 0, onCountUpdate }) {
    const { t } = useTranslation();
    const { auth, post_settings, dir } = usePage().props; 
    
    const isDesktop = useMediaQuery("(min-width: 768px)");
    const activeSide = isDesktop ? (dir === 'rtl' ? 'left' : 'right') : 'bottom';
    
    const areCommentsOpen = post_settings?.comments_enabled !== 'false';

    const [comments, setComments] = useState([]); 
    const [page, setPage] = useState(1);
    const [lastPage, setLastPage] = useState(1);
    const [loading, setLoading] = useState(false);
    
    const [totalCount, setTotalCount] = useState(Number(initialCount) || 0);
    const [replyingToId, setReplyingToId] = useState(null); 
    const [deleteId, setDeleteId] = useState(null);

    useEffect(() => {
        setTotalCount(Number(initialCount) || 0);
    }, [initialCount]);

    const fetchComments = async (reset = false) => {
        if (loading) return;
        setLoading(true);
        const targetPage = reset ? 1 : page;

        try {
            const res = await axios.get(`/api/posts/${postId}/comments?page=${targetPage}`);
            if (reset) {
                setComments(res.data.data);
            } else {
                setComments(prev => [...prev, ...res.data.data]);
            }
            setLastPage(res.data.last_page);
            setPage(targetPage + 1);
        } catch (error) {
            console.error("Failed to load comments", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (open) {
            setPage(1);
            fetchComments(true);
        }
    }, [open, postId]);

    // Handle Main Comment
    const handlePostRoot = async (content) => {
        try {
            const res = await axios.post(`/api/posts/${postId}/comments`, { content });
            setComments([res.data, ...comments]); 
            
            setTotalCount(prev => {
                const nextVal = Number(prev) + 1;
                if (onCountUpdate) onCountUpdate(nextVal);
                return nextVal;
            });
            toast.success(t('_comment_posted', 'Comment posted!'));
        } catch (error) {
            toast.error(error.response?.data?.message || t('_failed_post', 'Failed to post.'));
            throw error;
        }
    };

    // Handle Replies
    const handleReply = async (parentId, content) => {
        try {
            const res = await axios.post(`/api/posts/${postId}/comments`, { 
                content: content,
                parent_id: parentId 
            });
            const addChildToParent = (list) => {
                return list.map(c => {
                    if (c.id === parentId) {
                        return { ...c, children: [...(c.children || []), res.data] };
                    } else if (c.children && c.children.length > 0) {
                        return { ...c, children: addChildToParent(c.children) };
                    }
                    return c;
                });
            };
            setComments(prev => addChildToParent(prev));
            
            setTotalCount(prev => {
                const nextVal = Number(prev) + 1;
                if (onCountUpdate) onCountUpdate(nextVal);
                return nextVal;
            });
            toast.success(t('_reply_posted', 'Reply posted!'));
        } catch (error) {
            toast.error(error.response?.data?.message || t('_failed_reply', 'Failed to post reply.'));
            throw error;
        }
    };

    // Handled Edits (FIXED STATE OVERWRITE BUG)
    const handleUpdate = async (id, content) => {
        try {
            const res = await axios.put(`/api/comments/${id}`, { content });
            const updateInList = (list) => {
                return list.map(c => {
                    // We only update the content properties, preserving 'user' and 'children' relations
                    if (c.id === id) {
                        return { ...c, content: res.data.content, updated_at: res.data.updated_at };
                    }
                    if (c.children) return { ...c, children: updateInList(c.children) };
                    return c;
                });
            };
            setComments(prev => updateInList(prev));
            toast.success(t('_updated', 'Updated!'));
        } catch (error) {
            toast.error(t('_update_failed', 'Update failed.'));
            throw error;
        }
    };

    // Handle Delete
    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/api/comments/${deleteId}`);
            const deleteInList = (list) => {
                return list.filter(c => c.id !== deleteId).map(c => {
                    if (c.children) return { ...c, children: deleteInList(c.children) };
                    return c;
                });
            };
            setComments(prev => deleteInList(prev));
            
            setTotalCount(prev => {
                const nextVal = Math.max(0, Number(prev) - 1);
                if (onCountUpdate) onCountUpdate(nextVal);
                return nextVal;
            });

            toast.success(t('_deleted', 'Deleted.'));
        } catch (error) {
            toast.error(t('_delete_failed', 'Unauthorized or failed.'));
        } finally {
            setDeleteId(null);
        }
    };

    return (
        <Sheet open={open} onOpenChange={onOpenChange}>
            <SheetContent 
                side={activeSide} 
                className={cn(
                    "w-full flex flex-col p-0 z-[150] border-border",
                    isDesktop ? "sm:max-w-2xl" : "h-[90dvh] rounded-t-3xl"
                )}
            >
                <SheetHeader className="p-6 border-b">
                    <SheetTitle className="flex items-center gap-2 text-start">
                        <MessageSquare className="w-5 h-5 rtl:flip" />
                        {t('_discussion', 'Discussion')} ({totalCount})
                    </SheetTitle>
                    <SheetDescription className="text-start">
                        {t('_share_thoughts', 'Share your thoughts on this story.')}
                    </SheetDescription>
                </SheetHeader>

                <ScrollArea className="flex-1 p-6">
                    {loading && comments.length === 0 ? (
                        <div className="space-y-6">
                            {[1, 2, 3].map((i) => (
                                <div key={i} className="flex gap-3">
                                    <Skeleton className="h-8 w-8 rounded-full" />
                                    <div className="flex-1 space-y-2">
                                        <Skeleton className="h-4 w-24" />
                                        <Skeleton className="h-4 w-full" />
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : comments.length === 0 ? (
                        <div className="text-center text-muted-foreground py-10 flex flex-col items-center gap-2">
                            <MessageSquare className="w-10 h-10 opacity-20" />
                            <p>{t('_no_comments_yet', 'No comments yet. Start the conversation!')}</p>
                        </div>
                    ) : (
                        <div className="space-y-6">
                            {comments.map((comment) => (
                                <CommentItem 
                                    key={comment.id} 
                                    comment={comment} 
                                    auth={auth}
                                    onDelete={setDeleteId}
                                    onUpdate={handleUpdate}
                                    onReply={handleReply}
                                    replyingToId={replyingToId}
                                    setReplyingToId={setReplyingToId}
                                    areCommentsOpen={areCommentsOpen}
                                />
                            ))}
                            
                            {page <= lastPage && (
                                <Button 
                                    variant="ghost" 
                                    className="w-full text-xs text-muted-foreground" 
                                    onClick={() => fetchComments(false)}
                                    disabled={loading}
                                >
                                    {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('_load_older_comments', 'Load older comments')}
                                </Button>
                            )}
                        </div>
                    )}
                </ScrollArea>

                <div className="p-4 border-t bg-background">
                    <CommentInput 
                        auth={auth} 
                        areCommentsOpen={areCommentsOpen} 
                        onPost={handlePostRoot} 
                    />
                </div>

                {/* Delete Confirmation Modal */}
                <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
                    <AlertDialogContent>
                        <AlertDialogHeader>
                            <AlertDialogTitle>{t('_delete_comment_confirm', 'Delete this comment?')}</AlertDialogTitle>
                            <AlertDialogDescription>{t('_action_cannot_undone', 'This action cannot be undone.')}</AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                            <AlertDialogCancel>{t('_cancel', 'Cancel')}</AlertDialogCancel>
                            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700 text-white">{t('_delete', 'Delete')}</AlertDialogAction>
                        </AlertDialogFooter>
                    </AlertDialogContent>
                </AlertDialog>

            </SheetContent>
        </Sheet>
    );
}