'use client'

import { useState, useRef, useEffect } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { ImagePlus, Link2, Smile, Sparkles, Send, Loader2 } from "lucide-react"
import { useDispatch, useSelector } from "react-redux"
import { RootState } from "@/lib/store/store"
import { createPost } from "@/lib/api/client"
import { toast } from "sonner"
import { triggerPostsRefresh } from "@/lib/store/slices/userSlice"
import EmojiPicker from "emoji-picker-react"
import { RiDeleteBinLine } from "react-icons/ri"
import { FaPlay } from "react-icons/fa"

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL

export function IdeaComposer() {
  const dispatch = useDispatch()
  const { accessToken, currentCustomer, dynamicImages, selectedCategory } = useSelector((state: RootState) => state.user)
  const securityKey = dynamicImages?.securityKey
  
  const [content, setContent] = useState("")
  const [isFocused, setIsFocused] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [postStatus, setPostStatus] = useState<"Active" | "InActive">("Active") // Public = Active, Private = InActive
  const [mediaData, setMediaData] = useState<any[]>([])
  const [showMediaPreview, setShowMediaPreview] = useState(false)
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [descriptionError, setDescriptionError] = useState(false)
  const [descriptionErrorMessage, setDescriptionMessage] = useState("")
  
  const fileInputRef = useRef<HTMLInputElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const emojiPickerRef = useRef<HTMLDivElement>(null)

  // Click outside for emoji picker
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (emojiPickerRef.current && !emojiPickerRef.current.contains(event.target as Node)) {
        setShowEmojiPicker(false)
      }
    }
    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  const handleEmojiSelect = (emojiData: any) => {
    setContent(prev => prev + emojiData.emoji)
    setShowEmojiPicker(false)
  }

  const openFilePicker = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click()
    }
  }

const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const files = Array.from(event.target.files || [])
  if (files.length === 0) return
  
  // ✅ Check each file size first
  const oversizedFiles = files.filter(file => file.size > 1 * 1024 * 1024);
  if (oversizedFiles.length > 0) {
    toast.error(`File "${oversizedFiles[0].name}" exceeds 1 MB limit`);
    event.target.value = "";
    return;
  }
  
  const validFiles = files.filter(
    (file) =>
      ["image/png", "image/jpeg", "image/jpg"].includes(file.type) ||
      file.type === "video/mp4"
  )
  
  if (validFiles.length === 0) {
    toast.error("Only PNG, JPG, JPEG images or MP4 videos are allowed.")
    event.target.value = ""
    return
  }
  
  if (mediaData.length + validFiles.length > 5) {
    toast.error("Maximum 5 media files allowed")
    event.target.value = ""
    return
  }
  
  const newMediaData = validFiles.map((file) => ({
    file,
    preview: URL.createObjectURL(file),
  }))
  
  setMediaData((prev) => [...prev, ...newMediaData])
  setShowMediaPreview(true)
  event.target.value = ""
}

  // const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   const files = Array.from(event.target.files || [])
  //   if (files.length === 0) return
    
  //   const validFiles = files.filter(
  //     (file) =>
  //       ["image/png", "image/jpeg", "image/jpg"].includes(file.type) ||
  //       file.type === "video/mp4"
  //   )
    
  //   if (validFiles.length === 0) {
  //     toast.error("Only PNG, JPG, JPEG images or MP4 videos are allowed.")
  //     event.target.value = ""
  //     return
  //   }
    
  //   if (mediaData.length + validFiles.length > 5) {
  //     toast.error("Maximum 5 media files allowed")
  //     event.target.value = ""
  //     return
  //   }
    
  //   const newMediaData = validFiles.map((file) => ({
  //     file,
  //     preview: URL.createObjectURL(file),
  //   }))
    
  //   setMediaData((prev) => [...prev, ...newMediaData])
  //   setShowMediaPreview(true)
  //   event.target.value = ""
  // }

  const removeMedia = (index: number) => {
    setMediaData((prev) => prev.filter((_, i) => i !== index))
    if (mediaData.length === 1) {
      setShowMediaPreview(false)
    }
  }

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const value = e.target.value
    const charCount = value.replace(/\s/g, "").length
    
    if (charCount > 150) {
      setDescriptionError(true)
      setDescriptionMessage("Description should be less than 150 characters")
    } else {
      setDescriptionError(false)
    }
    
    setContent(value)
  }

  const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    // Public = Active, Private = InActive
    setPostStatus(e.target.value === "Public" ? "Active" : "InActive")
  }

  const renderMediaPreview = () => {
    if (mediaData.length === 0) return null
    
    const getGridClass = (count: number) => {
      if (count === 1) return "grid-cols-1"
      if (count === 2) return "grid-cols-2"
      if (count === 3) return "grid-cols-2 md:grid-cols-3"
      if (count === 4) return "grid-cols-2 md:grid-cols-4"
      return "grid-cols-2 md:grid-cols-4"
    }
    
    return (
      <div className={`grid ${getGridClass(mediaData.length)} gap-2 mt-3`}>
        {mediaData.map((media, index) => (
          <div
            key={index}
            className="relative rounded-md overflow-hidden h-24 bg-secondary"
          >
            {media.file.type.startsWith("image/") ? (
              <img
                src={media.preview}
                alt="Media preview"
                className="w-full h-full object-contain"
              />
            ) : (
              <div className="relative w-full h-full">
                <video
                  src={media.preview}
                  className="w-full h-full object-contain"
                  controls
                />
                <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
                  <div className="w-8 h-8 rounded-full bg-black/50 flex items-center justify-center">
                    <FaPlay className="text-white text-xs ml-0.5" />
                  </div>
                </div>
              </div>
            )}
            <button
              onClick={() => removeMedia(index)}
              className="absolute top-1 right-1 w-6 h-6 rounded-full bg-black/50 flex items-center justify-center hover:bg-black/70 transition-colors"
            >
              <RiDeleteBinLine size={12} className="text-white" />
            </button>
          </div>
        ))}
      </div>
    )
  }

  const handleSubmit = async () => {
    if (!accessToken) {
      toast.error("Please login to post ideas")
      return
    }
    
    if (!content.trim() && mediaData.length === 0) {
      toast.error("Please add a description or at least one media file")
      return
    }
    
    if (mediaData.length > 5) {
      toast.error("Maximum 5 media files allowed")
      return
    }
    
    setIsSubmitting(true)
    
    const formData = new FormData()
    
    if (content.trim()) {
      formData.append("description", content)
    }
    
    formData.append("status", postStatus)
    
    // ✅ Automatically use selected category from Redux if available
    if (selectedCategory?._id) {
      formData.append("postCategory", selectedCategory._id)
    }
    
    mediaData.forEach((media) => {
      formData.append("media", media.file)
    })
    
    try {
      const result = await createPost(formData, accessToken, securityKey)
      
      if (result.success) {
        toast.success(result.message || "Post created successfully!")
        dispatch(triggerPostsRefresh())
        
        // Reset form
        setContent("")
        setMediaData([])
        setShowMediaPreview(false)
        setPostStatus("Active")
        setDescriptionError(false)
        setDescriptionMessage("")
      } else {
        toast.error(result.message || "Failed to create post")
      }
    } catch (error: any) {
      console.error("Error creating post:", error)
      toast.error(error?.message || "Something went wrong")
    } finally {
      setIsSubmitting(false)
    }
  }

  // Get user data
  const customer = currentCustomer?.customer || currentCustomer
  const userAvatar = customer?.imageURL ? `${BASE_URL}/uploads/${customer.imageURL}` : undefined
  const userInitials = customer?.fullName?.split(" ").map((n: string) => n[0]).join("").toUpperCase().slice(0, 2) || "U"

  return (
    <div
      className={`rounded-2xl transition-all duration-300 ${
        isFocused ? "gradient-border glow-primary" : "glass glass-border"
      } p-5`}
    >
      <div className="flex gap-4">
        <div className="relative">
          <div className="absolute inset-0 rounded-full bg-primary/30 blur-md animate-pulse-glow" />
          <Avatar className="relative h-12 w-12 ring-2 ring-primary/30">
            <AvatarImage src={userAvatar} alt={customer?.fullName || "User"} />
            <AvatarFallback className="bg-primary text-primary-foreground font-bold">
              {userInitials}
            </AvatarFallback>
          </Avatar>
        </div>

        <div className="flex-1">
          <div className="relative">
            <textarea
              ref={textareaRef}
              placeholder="Share your next big idea..."
              value={content}
              onChange={handleContentChange}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
  className="min-h-[80px] w-full resize-none bg-transparent text-foreground dark:text-white placeholder-black dark:placeholder-white focus:outline-none text-base leading-relaxed"
    />
            {!content && (
              <div className="pointer-events-none absolute bottom-2 right-0 flex items-center gap-1.5 text-muted-foreground/50">
                <Sparkles className="h-4 w-4" />
                <span className="text-xs">AI-powered suggestions available</span>
              </div>
            )}
          </div>
          
          {descriptionError && (
            <p className="text-red-500 dark:text-red-400 text-xs mt-1">
              {descriptionErrorMessage}
            </p>
          )}

          {/* Media Preview */}
          {renderMediaPreview()}

          <div className="mt-4 flex items-center justify-between border-t border-border/30 pt-4">
            <div className="flex items-center gap-1">
              <button 
                type="button"
                onClick={openFilePicker}
                className="flex h-9 cursor-pointer  w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-primary transition-all"
              >
                <ImagePlus className="h-5 dark:text-white w-5" />
              </button>
             
              <div className="relative" ref={emojiPickerRef}>
                <button 
                  type="button"
                  onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                  className="flex cursor-pointer h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary hover:text-primary transition-all"
                >
                  <Smile className="h-5 w-5 dark:text-white" />
                </button>
                {showEmojiPicker && (
                  <div className="absolute z-50 bottom-full mb-2 left-0">
                    <EmojiPicker
                      onEmojiClick={handleEmojiSelect}
                      width={300}
                      height={300}
                      previewConfig={{ showPreview: false }}
                      skinTonesDisabled
                      searchDisabled={false}
                      theme={document.documentElement.classList.contains("dark") ? "dark" : "light"}
                    />
                  </div>
                )}
              </div>

              <div className="mx-3 h-6 w-px bg-border/50" />

              <select 
                value={postStatus === "Active" ? "Public" : "Private"}
                onChange={handleStatusChange}
                className="rounded-lg dark:text-white cursor-pointer bg-secondary/50 px-3 py-1.5 text-sm text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/30"
              >
                <option className="cursor-pointer">Public</option>
                <option className="cursor-pointer">Private</option>
              </select>
            </div>

            <button
              onClick={handleSubmit}
              disabled={isSubmitting || (!content.trim() && mediaData.length === 0)}
              className="flex items-center cursor-pointer gap-2 rounded-xl bg-primary px-5 py-2.5 text-sm font-semibold text-primary-foreground transition-all hover:glow-primary disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span>Posting...</span>
                </>
              ) : (
                <>
                  <Send className="h-4 w-4" />
                  <span>Post Idea</span>
                </>
              )}
            </button>
          </div>
        </div>
      </div>
      
      <input
        type="file"
        ref={fileInputRef}
        multiple
        hidden
        accept="image/png, image/jpeg, image/jpg, video/mp4"
        onChange={handleFileChange}
      />
    </div>
  )
}