"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 type { Post } from "@/types/post"
import { cn } from "@/lib/utils"

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 fileInputRef = useRef<HTMLInputElement>(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 handlePost = () => {
    if (!content.trim() && selectedFiles.length === 0) return

    const newPost: Post = {
      id: Date.now().toString(),
      author: {
        id: "current-user",
        username: "you",
        displayName: "You",
        avatar: "/diverse-user-avatars.png",
      },
      content,
      type: postType,
      timestamp: "Just now",
      likes: 0,
      comments: 0,
      isLiked: false,
      privacy: "public",
      replies: [],
      ...(selectedFiles.length > 0 && { media: previewUrls }),
    }

    onPost(newPost)
    handleRemoveMedia()
    setContent("")
    setIsExpanded(false)
    setPostType("thought")
  }

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

        <div className="flex-1 space-y-3">
          <Textarea
            placeholder="What's interesting..."
            value={content}
            onChange={(e) => {
              if (e.target.value.length <= characterLimit) {
                setContent(e.target.value)
              }
            }}
            onFocus={() => setIsExpanded(true)}
            className="min-h-[60px] 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>
          )}

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

              <Button
                variant="outline"
                size="sm"
                onClick={() => fileInputRef.current?.click()}
                className={cn("border-border hover:bg-accent", postType === "photo" && "bg-accent border-primary")}
              >
                <svg className="w-4 h-4 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>
                Photo
              </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}
              className="bg-primary hover:bg-primary/90 dark:bg-[#ff6b6b] dark:hover:bg-[#ff5252] text-primary-foreground font-semibold px-6"
            >
              Post
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
