"use client"

import { useState, useRef } from "react"
import { Send, Smile, ImageIcon, Wand2, Reply, ChevronRight } from "lucide-react"
import { Button } from "@/Components/UI/Button"
import { Input } from "@/Components/UI/Input"
import EmojiPicker from "emoji-picker-react"
import { usePage } from "@inertiajs/react"
import { route } from "ziggy-js"
import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"

const CommentBox = ({ comments = [], onAddComment , account}) => {
  const [newComment, setNewComment] = useState("")
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [showMagicWand, setShowMagicWand] = useState(false)
  const [showToneSubmenu, setShowToneSubmenu] = useState(false)
  const [showTranslateSubmenu, setShowTranslateSubmenu] = useState(false)
  const [selectedImages, setSelectedImages] = useState([])
  const [isProcessing, setIsProcessing] = useState(false)
  const [replyingTo, setReplyingTo] = useState(null)
  const [replyText, setReplyText] = useState("")
  const fileInputRef = useRef(null)

  const handleEmojiSelect = (emojiData) => {
    setNewComment((prev) => prev + emojiData.emoji)
    setShowEmojiPicker(false)
  }

  const handleImageSelect = (e) => {
    const files = Array.from(e.target.files)
    setSelectedImages((prev) => [...prev, ...files])
  }

  const handleImproveWriting = async () => {
    if (!newComment.trim()) return

    setIsProcessing(true)
    try {
      const response = await fetch(route("user.ai.improve-text"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
        },
        body: JSON.stringify({ text: newComment }),
      })
      const data = await response.json()
      if (data.improved_text) {
        setNewComment(data.improved_text)
      }
    } catch (error) {
      console.error("Error improving text:", error)
    } finally {
      setIsProcessing(false)
      setShowMagicWand(false)
    }
  }

  const handleChangeTone = async (tone) => {
    if (!newComment.trim()) return

    setIsProcessing(true)
    try {
      const response = await fetch(route("user.ai.change-tone"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
        },
        body: JSON.stringify({ text: newComment, tone }),
      })
      const data = await response.json()
      if (data.modified_text) {
        setNewComment(data.modified_text)
      }
    } catch (error) {
      console.error("Error changing tone:", error)
    } finally {
      setIsProcessing(false)
      setShowMagicWand(false)
      setShowToneSubmenu(false)
    }
  }

  const handleTranslate = async (language) => {
    if (!newComment.trim()) return

    setIsProcessing(true)
    try {
      const response = await fetch(route("user.ai.translate"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
        },
        body: JSON.stringify({ text: newComment, target_language: language }),
      })
      const data = await response.json()
      if (data.translated_text) {
        setNewComment(data.translated_text)
      }
    } catch (error) {
      console.error("Error translating text:", error)
    } finally {
      setIsProcessing(false)
      setShowMagicWand(false)
      setShowTranslateSubmenu(false)
    }
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    if (newComment.trim()) {
      onAddComment?.(newComment, selectedImages)
      setNewComment("")
      setSelectedImages([])
    }
  }

  const handleReplySubmit = (commentId) => {
    if (replyText.trim()) {
      // Handle reply submission logic here
      setReplyingTo(null)
      setReplyText("")
    }
  }

  const hasComments = comments && comments.length > 0

  return (
    <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800">
      {/* Comments Header */}
      <div className="p-4 border-b border-gray-200 dark:border-zinc-800">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Comments</h3>
      </div>

      {/* Add Comment Form */}
      <div className="p-4 border-b border-gray-200 dark:border-zinc-800 relative">
        <form onSubmit={handleSubmit}>
          <div className="flex items-center space-x-3 mb-4">
            <Avatar className="h-10 w-10">
              <AvatarImage src={account?.avatar} alt="User Avatar" />
              <AvatarFallback>AV</AvatarFallback>
            </Avatar>
            <Input
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              placeholder="Write a comment..."
              className="flex-1 border-none bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 text-gray-500 placeholder:text-gray-400"
              disabled={isProcessing}
            />
          </div>

          {selectedImages.length > 0 && (
            <div className="flex flex-wrap gap-2 mb-4">
              {selectedImages.map((file, index) => (
                <div key={index} className="relative">
                  <img
                    src={URL.createObjectURL(file) || "/placeholder.svg"}
                    alt={`Selected ${index + 1}`}
                    className="w-16 h-16 object-cover rounded-lg"
                  />
                  <button
                    type="button"
                    onClick={() => setSelectedImages((prev) => prev.filter((_, i) => i !== index))}
                    className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs"
                  >
                    ×
                  </button>
                </div>
              ))}
            </div>
          )}

          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2 relative">
              <div className="relative">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="text-gray-400 hover:text-gray-600 p-1"
                  onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                >
                  <Smile className="h-4 w-4" />
                </Button>
                {showEmojiPicker && (
                  <div className="absolute bottom-full left-0 mb-2 z-50">
                    <EmojiPicker onEmojiClick={handleEmojiSelect} />
                  </div>
                )}
              </div>

              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="text-gray-400 hover:text-gray-600 p-1"
                onClick={() => fileInputRef.current?.click()}
              >
                <ImageIcon className="h-4 w-4" />
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                multiple
                accept="image/*"
                onChange={handleImageSelect}
                className="hidden"
              />

              <div className="relative">
                <Button
                  type="button"
                  variant="ghost"
                  size="sm"
                  className="text-gray-400 hover:text-gray-600 p-1"
                  onClick={() => setShowMagicWand(!showMagicWand)}
                  disabled={isProcessing}
                >
                  <Wand2 className="h-4 w-4" />
                </Button>

                {showMagicWand && (
                  <div className="absolute bottom-full left-0 mb-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg py-2 min-w-48 z-50">
                    <button
                      type="button"
                      onClick={handleImproveWriting}
                      disabled={!newComment.trim() || isProcessing}
                      className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center space-x-2 disabled:opacity-50"
                    >
                      <span>✨</span>
                      <span>Improve writing</span>
                    </button>

                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setShowToneSubmenu(!showToneSubmenu)}
                        className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center justify-between"
                      >
                        <div className="flex items-center space-x-2">
                          <span>🎭</span>
                          <span>Change tone</span>
                        </div>
                        <ChevronRight className="h-4 w-4" />
                      </button>

                      {showToneSubmenu && (
                        <div className="absolute left-full top-0 ml-1 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg py-2 min-w-32">
                          {["Formal", "Casual", "Friendly"].map((tone) => (
                            <button
                              key={tone}
                              type="button"
                              onClick={() => handleChangeTone(tone.toLowerCase())}
                              disabled={!newComment.trim() || isProcessing}
                              className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
                            >
                              {tone}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>

                    <div className="relative">
                      <button
                        type="button"
                        onClick={() => setShowTranslateSubmenu(!showTranslateSubmenu)}
                        className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center justify-between"
                      >
                        <div className="flex items-center space-x-2">
                          <span>🌐</span>
                          <span>Translate</span>
                        </div>
                        <ChevronRight className="h-4 w-4" />
                      </button>

                      {showTranslateSubmenu && (
                        <div className="absolute left-full top-0 ml-1 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-lg shadow-lg py-2 min-w-48 max-h-64 overflow-y-auto">
                          {[
                            "Arabic",
                            "Chinese (Simplified)",
                            "Chinese (Traditional)",
                            "Dutch",
                            "English (United Kingdom)",
                            "French",
                            "German",
                            "Spanish",
                            "Italian",
                            "Japanese",
                            "Korean",
                            "Portuguese",
                          ].map((language) => (
                            <button
                              key={language}
                              type="button"
                              onClick={() => handleTranslate(language)}
                              disabled={!newComment.trim() || isProcessing}
                              className="w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50"
                            >
                              {language}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>

            <Button
              type="submit"
              size="sm"
              className="bg-blue-500 hover:bg-blue-600 text-white p-2"
              disabled={!newComment.trim() || isProcessing}
            >
              <Send className="h-4 w-4" />
            </Button>
          </div>
        </form>
      </div>

      {/* Comments Content */}
      <div className="p-4">
        {!hasComments ? (
          <div className="text-center py-12">
            <div className="w-16 h-16 bg-gray-300 dark:bg-gray-600 rounded-full mx-auto mb-4"></div>
            <h4 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No Comments Found!</h4>
            <p className="text-gray-500 dark:text-gray-400 text-sm">
              Don't forget to share your social media accounts to connect
              <br />
              with others online!
            </p>
          </div>
        ) : (
          <div className="space-y-4">
            {comments.map((comment) => (
              <div
                key={comment.id}
                className="border-b border-gray-100 dark:border-gray-700 last:border-b-0 pb-4 last:pb-0"
              >
                <div className="flex items-start space-x-3">
                  <img
                    src={comment.user?.avatar || "/placeholder.svg?height=32&width=32"}
                    alt={comment.user?.name}
                    className="w-8 h-8 rounded-full object-cover flex-shrink-0"
                  />
                  <div className="flex-1">
                    <div className="flex items-center space-x-2 mb-2">
                      <span className="font-medium text-sm text-gray-900 dark:text-white">{comment.user?.name}</span>
                      <span className="text-xs text-gray-500 dark:text-gray-400">{comment.created_at}</span>
                    </div>
                    <p className="text-sm text-gray-700 dark:text-gray-300 mb-3">{comment.content}</p>

                    <div className="flex items-center space-x-4">
                      <Button variant="ghost" size="sm" className="text-gray-400 hover:text-gray-600 h-6 px-0">
                        <Smile className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-gray-400 hover:text-gray-600 h-6 px-0"
                        onClick={() => setReplyingTo(replyingTo === comment.id ? null : comment.id)}
                      >
                        <Reply className="h-4 w-4" />
                      </Button>
                    </div>

                    {replyingTo === comment.id && (
                      <div className="mt-3 ml-4 border-l-2 border-gray-200 dark:border-gray-600 pl-4">
                        <div className="flex items-center space-x-2">
                          <img
                            src="/placeholder.svg?height=24&width=24"
                            alt="Your avatar"
                            className="w-6 h-6 rounded-full object-cover flex-shrink-0"
                          />
                          <Input
                            value={replyText}
                            onChange={(e) => setReplyText(e.target.value)}
                            placeholder="Write a reply..."
                            className="flex-1 text-sm"
                            onKeyPress={(e) => {
                              if (e.key === "Enter") {
                                handleReplySubmit(comment.id)
                              }
                            }}
                          />
                          <Button
                            size="sm"
                            onClick={() => handleReplySubmit(comment.id)}
                            disabled={!replyText.trim()}
                            className="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 text-xs"
                          >
                            Reply
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default CommentBox
