"use client"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ShieldAlert, Info } from "lucide-react"
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { fetchApi } from "@/lib/api-client"
import { useAuth } from "@/components/auth-provider"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"

const askSchema = z.object({
  title: z.string().min(10, "Title must be at least 10 characters"),
  content: z.string().min(20, "Please provide more details (at least 20 characters)"),
  tags: z.string().optional(),
})

type AskFormValues = z.infer<typeof askSchema>

export default function AskQuestionPage() {
  const { user, loading } = useAuth()
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [content, setContent] = useState<any>({})
  const router = useRouter()

  useEffect(() => {
    if (!loading && !user) {
      router.push("/login?callbackUrl=/forum/ask")
    }
  }, [user, loading, router])

  useEffect(() => {
    fetchApi('content.php?page=forum').then(setContent).catch(console.error)
  }, [])

  const form = useForm<AskFormValues>({
    resolver: zodResolver(askSchema),
    defaultValues: {
      title: "",
      content: "",
      tags: "",
    },
  })

  if (loading) {
    return <div className="container mx-auto px-4 py-12 text-center">Loading...</div>
  }

  if (!user) {
    return null
  }

  const onSubmit = async (values: AskFormValues) => {
    setIsLoading(true)
    setError(null)

    try {
      const tagsArray = values.tags ? values.tags.split(',').map(t => t.trim().replace(/^#/, '')) : []
      await fetchApi('forum.php', {
        method: 'POST',
        body: JSON.stringify({
          ...values,
          tags: tagsArray
        }),
      })
      router.push("/forum")
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred')
      setIsLoading(false)
    }
  }

  return (
    <main className="flex-1 container mx-auto px-4 py-12 max-w-3xl">
      <div className="mb-8 space-y-2">
        <h1 className="text-3xl font-bold">Ask the Community</h1>
        <p className="text-muted-foreground">Share your concerns or questions with patients and experts.</p>
      </div>

      <div className="grid gap-8">
        <div className="p-4 rounded-xl bg-secondary/10 border border-secondary/20 flex gap-4 items-start">
          <Info className="h-5 w-5 text-secondary shrink-0 mt-0.5" />
          <div className="text-sm">
            <p className="font-bold mb-1">{content.ask?.info_title || "Before you post:"}</p>
            <p className="text-muted-foreground">
              {content.ask?.info_text || "Have you tried searching for your question? Similar topics might already have expert answers."}
            </p>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Your Question</CardTitle>
            <CardDescription>Be as specific as possible to get the best help.</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              {error && (
                <div className="p-3 text-sm font-medium text-destructive bg-destructive/10 rounded-md text-center">
                  {error}
                </div>
              )}
              <div className="space-y-2">
                <Label htmlFor="title">Title</Label>
                <Input 
                  id="title" 
                  placeholder="e.g. Tips for managing fatigue during immunotherapy?" 
                  {...form.register("title")}
                />
                {form.formState.errors.title && (
                  <p className="text-xs text-destructive">{form.formState.errors.title.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="content">Details</Label>
                <Textarea
                  id="content"
                  placeholder="Explain your situation, what you've tried, or what specifically you're looking to learn..."
                  className="min-h-[200px]"
                  {...form.register("content")}
                />
                {form.formState.errors.content && (
                  <p className="text-xs text-destructive">{form.formState.errors.content.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="tags">Tags (comma separated)</Label>
                <Input 
                  id="tags" 
                  placeholder="e.g. #Immunotherapy, #Fatigue, #Stage3" 
                  {...form.register("tags")}
                />
              </div>

              <div className="p-4 rounded-lg bg-destructive/5 border border-destructive/10 flex gap-3">
                <ShieldAlert className="h-5 w-5 text-destructive shrink-0" />
                <p className="text-xs text-destructive/80">
                  {content.ask?.reminder_text || "Reminder: Please do not ask for specific medical prescriptions or dosages. Share experiences and general questions only."}
                </p>
              </div>

              <div className="flex justify-end gap-3 pt-4">
                <Button type="button" variant="ghost" onClick={() => router.back()}>Cancel</Button>
                <Button type="submit" className="px-8 shadow-lg font-bold" disabled={isLoading}>
                  {isLoading ? "Posting..." : "Post Question"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>
    </main>
  )
}
