"use client"

import { useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import Link from "next/link"

const formSchema = z.object({
  content: z.string().min(10, {
    message: "Reply must be at least 10 characters.",
  }),
})

type ReplyFormValues = z.infer<typeof formSchema>

export function ReplyForm({ questionId }: { questionId: number }) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const { user } = useAuth()
  const router = useRouter()

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<ReplyFormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      content: "",
    },
  })

  async function onSubmit(values: ReplyFormValues) {
    if (!user) {
      toast.error("Please log in to reply")
      router.push("/login")
      return
    }

    setIsSubmitting(true)
    try {
      await fetchApi('replies.php', {
        method: 'POST',
        body: JSON.stringify({
          question_id: questionId,
          content: values.content
        })
      })
      
      toast.success("Reply posted successfully!")
      reset()
      router.refresh()
    } catch (error: any) {
      toast.error(error.message || "Failed to post reply")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="pt-4">
      <h3 className="text-lg font-bold mb-4">Leave a Reply</h3>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="space-y-2">
          <Textarea 
            placeholder={user ? "Share your experience or offer support..." : "Please log in to share your experience."}
            className="min-h-[150px] bg-background border-none shadow-sm resize-none focus-visible:ring-primary/20"
            disabled={!user || isSubmitting}
            {...register("content")}
          />
          {errors.content && (
            <p className="text-xs font-medium text-destructive">{errors.content.message}</p>
          )}
        </div>
        <Button 
          type="submit" 
          className="w-full sm:w-auto px-8 font-bold" 
          disabled={!user || isSubmitting}
        >
          {isSubmitting ? "Posting..." : "Post Reply"}
        </Button>
        {!user && (
          <div className="flex flex-col items-center gap-3 mt-4 p-6 bg-muted/50 rounded-xl border border-dashed">
            <p className="text-sm font-medium text-muted-foreground">
              You must be logged in to participate in the discussion.
            </p>
            <div className="flex gap-3">
              <Button variant="outline" asChild size="sm">
                <Link href="/login">Log In</Link>
              </Button>
              <Button asChild size="sm">
                <Link href="/register">Sign Up</Link>
              </Button>
            </div>
          </div>
        )}
      </form>
    </div>
  )
}
