"use client"

import type React from "react"

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 { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { ImageIcon, Video, Globe, Lock, ArrowLeft, Loader2, X } from "lucide-react"
import type { Post, Privacy } from "@/types/post"
import { cn } from "@/lib/utils"

interface CreatePostModalProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onPost: (post: Post) => void
}

export function CreatePostModal({ open, onOpenChange, onPost }: CreatePostModalProps) {
  const [step, setStep] = useState<1 | 2>(1)
  const [content, setContent] = useState("")
  const [mediaFile, setMediaFile] = useState<File | null>(null)
  const [mediaPreview, setMediaPreview] = useState<string | null>(null)
  const [mediaType, setMediaType] = useState<"image" | "video" | null>(null)
  const [privacy, setPrivacy] = useState<Privacy>("public")
  const [isSubmitting, setIsSubmitting] = useState(false)

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

  const handleMediaUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // Max 1 file validation
    const isImage = file.type.startsWith("image/")
    const isVideo = file.type.startsWith("video/")

    if (!isImage && !isVideo) {
      alert("Please upload an image or video file")
      return
    }

    setMediaFile(file)
    setMediaType(isImage ? "image" : "video")

    const reader = new FileReader()
    reader.onloadend = () => {
      setMediaPreview(reader.result as string)
    }
    reader.readAsDataURL(file)
  }

  const handleRemoveMedia = () => {
    setMediaFile(null)
    setMediaPreview(null)
    setMediaType(null)
  }

  const handleNext = () => {
    if (content.trim().length === 0) return
    setStep(2)
  }

  const handleBack = () => {
    setStep(1)
  }

  const handleSubmit = async () => {
    if (!content.trim()) return

    setIsSubmitting(true)

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

    const newPost: Post = {
      id: Date.now().toString(),
      author: {
        id: "current-user",
        username: "you",
        displayName: "You",
        avatar: "/diverse-user-avatars.png",
      },
      content,
      type: mediaType === "image" ? "photo" : "thought",
      timestamp: "Just now",
      likes: 0,
      comments: 0,
      isLiked: false,
      imageUrl: mediaPreview || undefined,
      privacy,
      replies: [],
    }

    onPost(newPost)

    // Reset form
    setContent("")
    setMediaFile(null)
    setMediaPreview(null)
    setMediaType(null)
    setPrivacy("public")
    setStep(1)
    setIsSubmitting(false)
    onOpenChange(false)
  }

  const handleClose = () => {
    setContent("")
    setMediaFile(null)
    setMediaPreview(null)
    setMediaType(null)
    setPrivacy("public")
    setStep(1)
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[540px] p-0 gap-0">
        <DialogHeader className="px-6 py-4 border-b">
          <div className="flex items-center gap-3">
            {step === 2 && (
              <Button variant="ghost" size="icon" onClick={handleBack} className="h-8 w-8 -ml-2">
                <ArrowLeft className="h-5 w-5" />
              </Button>
            )}
            <DialogTitle className="text-lg font-semibold">{step === 1 ? "Create Post" : "Post Settings"}</DialogTitle>
          </div>
        </DialogHeader>

        <div className="px-6 py-4 max-h-[70vh] overflow-y-auto">
          {step === 1 ? (
            <div className="space-y-4">
              <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 on your mind?"
                    value={content}
                    onChange={(e) => {
                      if (e.target.value.length <= characterLimit) {
                        setContent(e.target.value)
                      }
                    }}
                    className="min-h-[120px] text-base resize-none border-0 focus-visible:ring-0 p-0"
                    autoFocus
                  />

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

                  {mediaPreview && (
                    <div className="relative rounded-lg overflow-hidden border">
                      {mediaType === "image" ? (
                        <img
                          src={mediaPreview || "/placeholder.svg"}
                          alt="Upload preview"
                          className="w-full h-auto max-h-[300px] object-cover"
                        />
                      ) : (
                        <video src={mediaPreview} controls className="w-full h-auto max-h-[300px]" />
                      )}
                      <Button
                        variant="destructive"
                        size="icon"
                        className="absolute top-2 right-2 h-8 w-8 rounded-full"
                        onClick={handleRemoveMedia}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  )}

                  {!mediaFile && (
                    <div className="flex gap-2">
                      <Label
                        htmlFor="image-upload"
                        className="flex-1 flex items-center justify-center gap-2 border-2 border-dashed rounded-lg p-4 cursor-pointer hover:bg-accent transition-colors"
                      >
                        <ImageIcon className="w-5 h-5 text-muted-foreground" />
                        <span className="text-sm font-medium">Add Image</span>
                        <input
                          id="image-upload"
                          type="file"
                          accept="image/*"
                          onChange={handleMediaUpload}
                          className="sr-only"
                        />
                      </Label>

                      <Label
                        htmlFor="video-upload"
                        className="flex-1 flex items-center justify-center gap-2 border-2 border-dashed rounded-lg p-4 cursor-pointer hover:bg-accent transition-colors"
                      >
                        <Video className="w-5 h-5 text-muted-foreground" />
                        <span className="text-sm font-medium">Add Video</span>
                        <input
                          id="video-upload"
                          type="file"
                          accept="video/*"
                          onChange={handleMediaUpload}
                          className="sr-only"
                        />
                      </Label>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              <div className="space-y-3">
                <Label className="text-base font-semibold">Who can see this post?</Label>
                <RadioGroup value={privacy} onValueChange={(value) => setPrivacy(value as Privacy)}>
                  <div className="flex items-start space-x-3 p-4 rounded-lg border hover:bg-accent transition-colors cursor-pointer">
                    <RadioGroupItem value="public" id="public" className="mt-1" />
                    <Label htmlFor="public" className="flex-1 cursor-pointer">
                      <div className="flex items-center gap-2 mb-1">
                        <Globe className="w-5 h-5" />
                        <span className="font-semibold">Public</span>
                      </div>
                      <p className="text-sm text-muted-foreground">Anyone can see this post</p>
                    </Label>
                  </div>

                  <div className="flex items-start space-x-3 p-4 rounded-lg border hover:bg-accent transition-colors cursor-pointer">
                    <RadioGroupItem value="private" id="private" className="mt-1" />
                    <Label htmlFor="private" className="flex-1 cursor-pointer">
                      <div className="flex items-center gap-2 mb-1">
                        <Lock className="w-5 h-5" />
                        <span className="font-semibold">Private</span>
                      </div>
                      <p className="text-sm text-muted-foreground">Only you can see this post</p>
                    </Label>
                  </div>
                </RadioGroup>
              </div>

              <div className="p-4 bg-accent/50 rounded-lg">
                <p className="text-sm text-muted-foreground">
                  <strong>Preview:</strong> Your post will be visible to{" "}
                  {privacy === "public" ? "everyone on MyPowerPost" : "only you"}
                </p>
              </div>
            </div>
          )}
        </div>

        <div className="px-6 py-4 border-t flex justify-end gap-2">
          {step === 1 ? (
            <>
              <Button variant="outline" onClick={handleClose}>
                Cancel
              </Button>
              <Button
                onClick={handleNext}
                disabled={!content.trim() || content.length > characterLimit}
                className="bg-primary text-primary-foreground hover:bg-primary/90"
              >
                Next
              </Button>
            </>
          ) : (
            <>
              <Button variant="outline" onClick={handleBack}>
                Back
              </Button>
              <Button
                onClick={handleSubmit}
                disabled={isSubmitting}
                className="bg-primary text-primary-foreground hover:bg-primary/90"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    Posting...
                  </>
                ) : (
                  "Post"
                )}
              </Button>
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
