"use client"

import type React from "react"

import { useState, useRef } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Layers, Loader2 } from "lucide-react"
import type { Post } from "@/types/post"
import { cn } from "@/lib/utils"
import { createPost } from "@/actions/post-actions"
import { toast } from "sonner"

// Popular general hashtags for everyday use
const POPULAR_HASHTAGS = [
  "Love",
  "Happy",
  "Fun",
  "Friends",
  "Family",
  "Life",
  "Memories",
  "Blessed",
  "Grateful",
  "Smile",
  "Selfie",
  "Weekend",
  "Motivation",
  "Inspiration",
  "Success",
  "Goals",
  "Dreams",
  "Believe",
  "Positive",
  "Vibes",
  "Food",
  "Foodie",
  "Yummy",
  "Delicious",
  "Travel",
  "Adventure",
  "Explore",
  "Vacation",
  "Beach",
  "Nature",
  "Fitness",
  "Workout",
  "Health",
  "Wellness",
  "Fashion",
  "Style",
  "Beauty",
  "Photography",
  "Photo",
  "Art",
  "Music",
  "Dance",
  "Party",
  "Celebrate",
  "Birthday",
  "Anniversary",
  "Shopping",
  "Sale",
  "NewPost",
  "Follow",
  "Like",
  "Share",
  "Comment",
  "Viral",
  "Trending",
  "Daily",
  "InstaGood",
  "PicOfTheDay",
  "ThrowBack",
  "MemoryLane",
  "GoodTimes",
]

interface InlineCreatePostProps {
  onPost: (post: Post) => void
}

export function InlineCreatePost({ onPost }: InlineCreatePostProps) {
  const [content, setContent] = useState("")
  const [isExpanded, setIsExpanded] = useState(false)
  const [postType, setPostType] = useState<"thought" | "photo">("thought")
  const [selectedFiles, setSelectedFiles] = useState<File[]>([])
  const [previewUrls, setPreviewUrls] = useState<string[]>([])
  const [showClustersSection, setShowClustersSection] = useState(false)
  const [isPosting, setIsPosting] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const characterLimit = 500
  const remainingChars = characterLimit - content.length

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || [])
    if (files.length === 0) return

    setSelectedFiles(files)
    setPostType("photo")
    setIsExpanded(true)

    // Create preview URLs for images and videos
    const urls = files.map((file) => URL.createObjectURL(file))
    setPreviewUrls(urls)
  }

  const handleRemoveMedia = () => {
    // Clean up preview URLs
    previewUrls.forEach((url) => URL.revokeObjectURL(url))
    setSelectedFiles([])
    setPreviewUrls([])
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  const handleHashtagClick = (hashtag: string) => {
    // Check if hashtag already exists in content
    if (content.includes(hashtag)) {
      return
    }

    // Add hashtag to content with a space before it
    const newContent = content.trim() ? `${content} ${hashtag}` : hashtag
    
    if (newContent.length <= characterLimit) {
      setContent(newContent)
      // Focus back on textarea
      textareaRef.current?.focus()
    }
  }

  const toggleClustersSection = () => {
    setShowClustersSection(!showClustersSection)
  }

  const handlePost = async () => {
    if (!content.trim() && selectedFiles.length === 0) return

    setIsPosting(true)

    try {
      // Prepare form data for backend
      const formData = new FormData()
      formData.append("content", content)
      formData.append("privacy", "PUBLIC")
      
      // Add media file if selected (only first file for now)
      if (selectedFiles.length > 0) {
        formData.append("media", selectedFiles[0])
      }

      // Use API route instead of Server Action for file uploads
      const hasMedia = selectedFiles.length > 0
      
      let result
      if (hasMedia) {
        // Use API route for file uploads (no size limit)
        const response = await fetch('/api/posts/create', {
          method: 'POST',
          body: formData,
        })
        result = await response.json()
      } else {
        // Use Server Action for text-only posts (faster)
        result = await createPost(formData)
      }

      if (result.success && result.post) {
        // Add new post to feed
        onPost(result.post)
        
        // Reset form
        handleRemoveMedia()
        setContent("")
        setIsExpanded(false)
        setPostType("thought")
        setShowClustersSection(false)
        
        toast.success("Post created successfully!")
      } else {
        toast.error(result.error || "Failed to create post")
      }
    } catch (error) {
      toast.error("An unexpected error occurred")
    } finally {
      setIsPosting(false)
    }
  }

  return (
    <div className="bg-card border border-border rounded-xl p-3 sm:p-4 shadow-sm">
      <div className="flex gap-2 sm:gap-3">
        <Avatar className="w-8 h-8 sm:w-10 sm:h-10 shrink-0">
          <AvatarImage src="/diverse-user-avatars.png" />
          <AvatarFallback>You</AvatarFallback>
        </Avatar>

        <div className="flex-1 space-y-2 sm:space-y-3">
          <Textarea
            ref={textareaRef}
            placeholder="What's interesting..."
            value={content}
            onChange={(e) => {
              if (e.target.value.length <= characterLimit) {
                setContent(e.target.value)
              }
            }}
            onFocus={() => setIsExpanded(true)}
            className="min-h-[50px] sm:min-h-[60px] text-sm sm:text-base resize-none bg-muted/50 border-border focus-visible:ring-1 focus-visible:ring-primary"
          />

          {previewUrls.length > 0 && (
            <div className="relative">
              <div className="grid grid-cols-2 gap-2">
                {previewUrls.map((url, index) => {
                  const file = selectedFiles[index]
                  const isVideo = file?.type.startsWith("video/")

                  return (
                    <div key={index} className="relative rounded-lg overflow-hidden border border-border">
                      {isVideo ? (
                        <video src={url} controls className="w-full h-48 object-cover bg-muted">
                          Your browser does not support the video tag.
                        </video>
                      ) : (
                        <img
                          src={url || "/placeholder.svg"}
                          alt={`Upload ${index + 1}`}
                          className="w-full h-48 object-cover"
                        />
                      )}
                    </div>
                  )
                })}
              </div>
              <Button
                variant="destructive"
                size="sm"
                onClick={handleRemoveMedia}
                className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0"
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </Button>
            </div>
          )}

          {isExpanded && (
            <div className="text-sm text-muted-foreground">
              <span className={cn(remainingChars < 50 && "text-orange-500", remainingChars < 20 && "text-red-500")}>
                {remainingChars} characters remaining
              </span>
            </div>
          )}

          {/* Popular Hashtags Section - Only shown when button is clicked */}
          {showClustersSection && (
            <div className="border border-border rounded-lg bg-muted/30 p-3 animate-in slide-in-from-top-2">
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-semibold text-foreground">Popular Clusters</span>
                  <span className="text-xs text-muted-foreground">Click to add</span>
                </div>
                <div className="flex flex-wrap gap-2 max-h-[300px] overflow-y-auto pr-2">
                  {POPULAR_HASHTAGS.map((hashtag) => {
                    const isAdded = content.includes(hashtag)
                    return (
                      <button
                        key={hashtag}
                        onClick={() => handleHashtagClick(hashtag)}
                        disabled={isAdded}
                        className={cn(
                          "px-3 py-1.5 rounded-full text-sm font-medium transition-all",
                          isAdded
                            ? "bg-primary text-primary-foreground cursor-not-allowed opacity-60"
                            : "bg-background hover:bg-primary hover:text-primary-foreground border border-border hover:border-primary"
                        )}
                      >
                        {hashtag}
                        {isAdded && (
                          <span className="ml-1 text-xs">✓</span>
                        )}
                      </button>
                    )
                  })}
                </div>
              </div>
            </div>
          )}

          <div className="flex items-center justify-between flex-wrap gap-2">
            <div className="flex gap-1.5 sm:gap-2 flex-wrap">
              {/* <Button
                variant="outline"
                size="sm"
                onClick={() => setPostType("thought")}
                className={cn("border-border hover:bg-accent text-xs sm:text-sm px-2 sm:px-3", postType === "thought" && "bg-accent border-primary")}
              >
                <svg className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                <span className="hidden sm:inline">Thought</span>
              </Button> */}

              <Button
                variant="outline"
                size="sm"
                onClick={() => fileInputRef.current?.click()}
                className={cn("border-border hover:bg-accent text-xs sm:text-sm px-2 sm:px-3", postType === "photo" && "bg-accent border-primary")}
              >
                <svg className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                  />
                </svg>
                <span className="hidden sm:inline">Photo/Video</span>
              </Button>

              <Button
                variant="outline"
                size="sm"
                onClick={toggleClustersSection}
                className={cn("border-border hover:bg-accent text-xs sm:text-sm px-2 sm:px-3", showClustersSection && "bg-accent border-primary")}
              >
                <Layers className="w-3 h-3 sm:w-4 sm:h-4 sm:mr-1" />
                <span className="hidden sm:inline">Clusters</span>
              </Button>

              <input
                ref={fileInputRef}
                type="file"
                accept="image/*,video/*"
                multiple
                onChange={handleFileSelect}
                className="hidden"
              />
            </div>

            <Button
              onClick={handlePost}
              disabled={(!content.trim() && selectedFiles.length === 0) || content.length > characterLimit || isPosting}
              className="bg-primary hover:bg-primary/90 dark:bg-[#ff6b6b] dark:hover:bg-[#ff5252] text-primary-foreground font-semibold px-4 sm:px-6 text-sm sm:text-base"
            >
              {isPosting ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  Posting...
                </>
              ) : (
                "Post"
              )}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
