"use client"

import { useState } from "react"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Heart, MessageCircle, Send, Loader2 } from 'lucide-react'
import type { Post, Reply } from "@/types/post"
import { getDisplayName } from "@/types/post"
import { cn } from "@/lib/utils"

interface ThreadViewProps {
  post: Post | null
  open: boolean
  onOpenChange: (open: boolean) => void
  onLike: (postId: string) => void
  onReply: (postId: string, reply: Reply) => void
}

export function ThreadView({ post, open, onOpenChange, onLike, onReply }: ThreadViewProps) {
  const [replyContent, setReplyContent] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  const characterLimit = 250
  const remainingChars = characterLimit - replyContent.length

  if (!post) return null

  const handleSubmitReply = async () => {
    if (!replyContent.trim() || replyContent.length > characterLimit) return

    setIsSubmitting(true)

    // Simulate API call
    await new Promise((resolve) => setTimeout(resolve, 500))

    const newReply: Reply = {
      id: Date.now().toString(),
      authorId: "current-user",
      author: {
        id: "current-user",
        username: "you",
        displayName: "You",
        avatar: "/diverse-user-avatars.png",
      },
      content: replyContent,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      postId: post.id,
    }

    onReply(post.id, newReply)
    setReplyContent("")
    setIsSubmitting(false)
  }

  const replies = post.replies || []

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] p-0 gap-0 max-h-[90vh] flex flex-col">
        <DialogHeader className="px-6 py-4 border-b shrink-0">
          <DialogTitle className="text-lg font-semibold">Thread</DialogTitle>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto px-6 py-4">
          <div className="space-y-6">
            {/* Original Post */}
            <div className="pb-6 border-b">
              <div className="flex gap-3 mb-4">
                <Avatar className="w-10 h-10">
                  <AvatarImage src={post.author.avatar || "/placeholder.svg"} />
                  <AvatarFallback>{getDisplayName(post.author)[0]}</AvatarFallback>
                </Avatar>

                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-sm text-foreground">{getDisplayName(post.author)}</span>
                    <span className="text-xs text-muted-foreground">{post.timestamp}</span>
                  </div>
                  <p className="text-sm text-muted-foreground">{post.author.username}</p>
                </div>
              </div>

              <p className="text-base text-foreground leading-relaxed mb-4">{post.content}</p>

              {post.imageUrl && (
                <div className="rounded-lg overflow-hidden mb-4">
                  <img src={post.imageUrl || "/placeholder.svg"} alt="Post image" className="w-full h-auto object-cover" />
                </div>
              )}

              <div className="flex items-center gap-6">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => onLike(post.id)}
                  className={cn("gap-2 px-2", post.isLiked && "text-destructive hover:text-destructive")}
                >
                  <Heart className={cn("w-5 h-5", post.isLiked && "fill-current")} />
                  <span className="text-sm font-medium">{post.likes}</span>
                </Button>

                <div className="flex items-center gap-2 text-muted-foreground">
                  <MessageCircle className="w-5 h-5" />
                  <span className="text-sm font-medium">{replies.length} {replies.length === 1 ? "reply" : "replies"}</span>
                </div>
              </div>
            </div>

            {/* Replies */}
            {replies.length > 0 && (
              <div className="space-y-4">
                <h3 className="text-sm font-semibold text-muted-foreground">
                  {replies.length} {replies.length === 1 ? "Reply" : "Replies"}
                </h3>

                {replies.map((reply) => (
                  <div key={reply.id} className="flex gap-3 pl-4 border-l-2 border-border">
                    <Avatar className="w-8 h-8">
                      <AvatarImage src={reply.author.avatar || "/placeholder.svg"} />
                      <AvatarFallback>{getDisplayName(reply.author)[0]}</AvatarFallback>
                    </Avatar>

                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-semibold text-sm text-foreground">{getDisplayName(reply.author)}</span>
                        <span className="text-xs text-muted-foreground">{typeof reply.createdAt === 'string' ? new Date(reply.createdAt).toLocaleString() : reply.createdAt.toLocaleString()}</span>
                      </div>
                      <p className="text-sm text-foreground leading-relaxed">{reply.content}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Reply Input */}
        <div className="px-6 py-4 border-t shrink-0">
          <div className="flex gap-3">
            <Avatar className="w-8 h-8 shrink-0">
              <AvatarImage src="/diverse-user-avatars.png" />
              <AvatarFallback>You</AvatarFallback>
            </Avatar>

            <div className="flex-1 space-y-2">
              <Textarea
                placeholder="Write a reply..."
                value={replyContent}
                onChange={(e) => {
                  if (e.target.value.length <= characterLimit) {
                    setReplyContent(e.target.value)
                  }
                }}
                className="min-h-[60px] resize-none text-sm"
              />

              <div className="flex items-center justify-between">
                <span
                  className={cn(
                    "text-xs text-muted-foreground",
                    remainingChars < 50 && "text-orange-500",
                    remainingChars < 20 && "text-red-500"
                  )}
                >
                  {remainingChars} / {characterLimit}
                </span>

                <Button
                  size="sm"
                  onClick={handleSubmitReply}
                  disabled={!replyContent.trim() || replyContent.length > characterLimit || isSubmitting}
                  className="bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Sending...
                    </>
                  ) : (
                    <>
                      <Send className="w-4 h-4 mr-2" />
                      Reply
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
