"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent } from "@/components/ui/card"
import { formatDistanceToNow } from "date-fns"
import { getApiUrl } from "@/lib/api-config"
import { MessageCircle, CornerDownRight, Heart, Flag } from "lucide-react"
import { cn } from "@/lib/utils"
import { ReportDialog } from "@/components/moderation/report-dialog"

interface Comment {
    id: number
    user_id: number
    content: string
    created_at: string
    parent_id: number | null
}

interface CommentSectionProps {
    entityType: "show" | "venue" | "song" | "tour" | "performance" | "year"
    entityId: number
}

export function CommentSection({ entityType, entityId }: CommentSectionProps) {
    const [comments, setComments] = useState<Comment[]>([])
    const [newComment, setNewComment] = useState("")
    const [loading, setLoading] = useState(false)

    useEffect(() => {
        fetchComments()
    }, [entityType, entityId])

    const fetchComments = async () => {
        try {
            const res = await fetch(`${getApiUrl()}/social/comments?${entityType}_id=${entityId}&limit=100`)
            if (res.ok) {
                const data = await res.json()
                setComments(data)
            }
        } catch (err) {
            console.error("Failed to fetch comments", err)
        }
    }

    const handleSubmit = async (e: React.FormEvent, parentId: number | null = null, content: string = newComment) => {
        e.preventDefault()
        if (!content.trim()) return

        const token = localStorage.getItem("token")
        if (!token) {
            alert("Please log in to comment.")
            return
        }

        setLoading(true)
        try {
            const body: any = {
                content: content,
                parent_id: parentId
            }
            body[`${entityType}_id`] = entityId

            const res = await fetch(`${getApiUrl()}/social/comments`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify(body)
            })

            if (!res.ok) throw new Error("Failed to post comment")

            const savedComment = await res.json()
            setComments(prev => [savedComment, ...prev])
            setNewComment("")
        } catch (err) {
            console.error(err)
            alert("Error posting comment")
        } finally {
            setLoading(false)
        }
    }

    // Tree builder
    const rootComments = comments.filter(c => c.parent_id === null)
    const getReplies = (parentId: number) => comments.filter(c => c.parent_id === parentId).sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())

    return (
        <div className="space-y-8">
            <h3 className="text-xl font-semibold flex items-center gap-2">
                <MessageCircle className="h-5 w-5" />
                Discussion
            </h3>

            {/* Root Post Form */}
            <div className="flex gap-4">
                <div className="flex-1">
                    <form onSubmit={(e) => handleSubmit(e)} className="space-y-4">
                        <Textarea
                            placeholder="Share your thoughts..."
                            value={newComment}
                            onChange={(e) => setNewComment(e.target.value)}
                            required
                            className="min-h-[100px]"
                        />
                        <div className="flex justify-end">
                            <Button type="submit" disabled={loading || !newComment.trim()}>
                                {loading ? "Posting..." : "Post Comment"}
                            </Button>
                        </div>
                    </form>
                </div>
            </div>

            <div className="space-y-6">
                {rootComments.length === 0 ? (
                    <p className="text-muted-foreground text-center py-8">No comments yet. Be the first!</p>
                ) : (
                    rootComments.map(comment => (
                        <CommentItem
                            key={comment.id}
                            comment={comment}
                            getReplies={getReplies}
                            onReply={handleSubmit}
                        />
                    ))
                )}
            </div>
        </div>
    )
}

function CommentItem({ comment, getReplies, onReply }: {
    comment: Comment,
    getReplies: (id: number) => Comment[],
    onReply: (e: React.FormEvent, parentId: number, content: string) => Promise<void>
}) {
    const [isReplying, setIsReplying] = useState(false)
    const [replyContent, setReplyContent] = useState("")
    const [submitting, setSubmitting] = useState(false)
    const replies = getReplies(comment.id)

    const handleReplySubmit = async (e: React.FormEvent) => {
        setSubmitting(true)
        await onReply(e, comment.id, replyContent)
        setSubmitting(false)
        setIsReplying(false)
        setReplyContent("")
    }

    return (
        <div className="group">
            <div className="flex gap-3">
                <div className="flex flex-col items-center">
                    <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-xs font-bold text-primary">
                        {comment.user_id}
                    </div>
                    {(replies.length > 0) && <div className="w-px h-full bg-border my-2" />}
                </div>

                <div className="flex-1 space-y-2 pb-6">
                    <div className="flex items-center gap-2">
                        <span className="font-semibold text-sm">User #{comment.user_id}</span>
                        <span className="text-xs text-muted-foreground">
                            • {formatDistanceToNow(new Date(comment.created_at), { addSuffix: true })}
                        </span>
                    </div>

                    <div className="text-sm leading-relaxed whitespace-pre-wrap">
                        {comment.content}
                    </div>

                    <div className="flex items-center gap-4 pt-1">
                        <Button
                            variant="ghost"
                            size="sm"
                            className={cn("h-6 px-2 text-xs text-muted-foreground gap-1 hover:text-primary", isReplying && "text-primary bg-primary/5")}
                            onClick={() => setIsReplying(!isReplying)}
                        >
                            <MessageCircle className="h-3 w-3" />
                            Reply
                        </Button>
                        <Button variant="ghost" size="sm" className="h-6 px-2 text-xs text-muted-foreground gap-1 hover:text-red-500">
                            <Heart className="h-3 w-3" />
                            Like
                        </Button>
                        <ReportDialog
                            entityType="comment"
                            entityId={comment.id}
                            trigger={
                                <Button variant="ghost" size="sm" className="h-6 px-2 text-xs text-muted-foreground gap-1 hover:text-red-500">
                                    <Flag className="h-3 w-3" />
                                    Report
                                </Button>
                            }
                        />
                    </div>

                    {isReplying && (
                        <div className="mt-4 pl-4 border-l-2 border-primary/20">
                            <form onSubmit={handleReplySubmit} className="space-y-3">
                                <Textarea
                                    placeholder={`Reply to User #${comment.user_id}...`}
                                    value={replyContent}
                                    onChange={(e) => setReplyContent(e.target.value)}
                                    autoFocus
                                    className="min-h-[80px]"
                                />
                                <div className="flex justify-end gap-2">
                                    <Button type="button" variant="ghost" onClick={() => setIsReplying(false)}>Cancel</Button>
                                    <Button type="submit" size="sm" disabled={submitting || !replyContent.trim()}>
                                        Reply
                                    </Button>
                                </div>
                            </form>
                        </div>
                    )}

                    {/* Recursive Replies */}
                    {replies.length > 0 && (
                        <div className="mt-4 space-y-4">
                            {replies.map(reply => (
                                <CommentItem
                                    key={reply.id}
                                    comment={reply}
                                    getReplies={getReplies}
                                    onReply={onReply}
                                />
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}
