"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { ImagePlus, Save, Send, Loader2 } 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, Controller } from "react-hook-form"
import * as z from "zod"
import { toast } from "sonner"

const insightSchema = z.object({
  title: z.string().min(10, "Title must be at least 10 characters"),
  category: z.string().min(1, "Please select a category"),
  read_time: z.string().min(1, "Please provide estimated read time"),
  excerpt: z.string().min(20, "Excerpt must be at least 20 characters"),
  content: z.string().min(100, "Content must be at least 100 characters"),
})

type InsightFormValues = z.infer<typeof insightSchema>

export default function CreateArticlePage() {
  const { user, loading } = useAuth()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [categories, setCategories] = useState<string[]>([])
  const router = useRouter()

  const { control, register, handleSubmit, formState: { errors } } = useForm<InsightFormValues>({
    resolver: zodResolver(insightSchema),
    defaultValues: {
      title: "",
      category: "",
      read_time: "5 min read",
      excerpt: "",
      content: "",
    },
  })

  useEffect(() => {
    if (!loading && (!user || user.role !== 'expert')) {
      router.push("/insights")
    }
  }, [user, loading, router])

  useEffect(() => {
    fetchApi('content.php?page=insights').then(data => {
      if (data.navigation?.categories) {
        setCategories(JSON.parse(data.navigation.categories))
      }
    }).catch(console.error)
  }, [])

  if (loading || (user && user.role !== 'expert')) {
    return <div className="container mx-auto px-4 py-12 text-center">Checking permissions...</div>
  }

  const onSubmit = async (values: InsightFormValues) => {
    setIsSubmitting(true)
    setError(null)

    try {
      await fetchApi('insights.php', {
        method: 'POST',
        body: JSON.stringify(values),
      })
      toast.success("Article published successfully!")
      router.push("/insights")
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An unknown error occurred')
      toast.error(err instanceof Error ? err.message : 'Failed to publish article')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <main className="flex-1 container mx-auto px-4 py-12 max-w-4xl">
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold">Create New Insight</h1>
            <p className="text-muted-foreground">Share peer-reviewed information with the community.</p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" type="button">
              <Save className="mr-2 h-4 w-4" />
              Save Draft
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Send className="mr-2 h-4 w-4" />}
              Publish
            </Button>
          </div>
        </div>

        <div className="grid gap-8">
          {error && (
            <div className="p-3 text-sm font-medium text-destructive bg-destructive/10 rounded-md text-center">
              {error}
            </div>
          )}
          <Card>
            <CardHeader>
              <CardTitle>Article Details</CardTitle>
              <CardDescription>Provide the core information for your article.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="title">Article Title</Label>
                <Input 
                  id="title" 
                  placeholder="Enter a descriptive title" 
                  className="text-lg font-semibold"
                  {...register("title")}
                />
                {errors.title && <p className="text-xs text-destructive">{errors.title.message}</p>}
              </div>

              <div className="grid sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="category">Category</Label>
                  <Controller
                    name="category"
                    control={control}
                    render={({ field }) => (
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <SelectTrigger>
                          <SelectValue placeholder="Select category" />
                        </SelectTrigger>
                        <SelectContent>
                          {categories.map((cat) => (
                            <SelectItem key={cat} value={cat} className="capitalize">
                              {cat.replace('-', ' ')}
                            </SelectItem>
                          ))}
                          {categories.length === 0 && (
                            <>
                              <SelectItem value="treatment">Treatment</SelectItem>
                              <SelectItem value="lifestyle">Lifestyle</SelectItem>
                              <SelectItem value="mental-health">Mental Health</SelectItem>
                              <SelectItem value="research">Research</SelectItem>
                            </>
                          )}
                        </SelectContent>
                      </Select>
                    )}
                  />
                  {errors.category && <p className="text-xs text-destructive">{errors.category.message}</p>}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="read-time">Estimated Read Time</Label>
                  <Input id="read-time" placeholder="e.g. 5 min read" {...register("read_time")} />
                  {errors.read_time && <p className="text-xs text-destructive">{errors.read_time.message}</p>}
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="excerpt">Short Excerpt</Label>
                <Textarea
                  id="excerpt"
                  placeholder="Brief summary to display in article lists..."
                  className="resize-none h-20"
                  {...register("excerpt")}
                />
                {errors.excerpt && <p className="text-xs text-destructive">{errors.excerpt.message}</p>}
              </div>

              <div className="space-y-2">
                <Label>Featured Image</Label>
                <div className="border-2 border-dashed rounded-lg p-12 text-center hover:bg-muted/50 transition-colors cursor-pointer">
                  <ImagePlus className="mx-auto h-12 w-12 text-muted-foreground mb-4" />
                  <p className="text-sm text-muted-foreground">Click to upload or drag and drop</p>
                  <p className="text-xs text-muted-foreground mt-1">Recommended size: 1200x630px</p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Content</CardTitle>
              <CardDescription>Write your article content using the editor below.</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <Textarea
                  id="content"
                  placeholder="Start writing your article here..."
                  className="min-h-[400px] font-serif text-lg leading-relaxed"
                  {...register("content")}
                />
                {errors.content && <p className="text-xs text-destructive">{errors.content.message}</p>}
              </div>
            </CardContent>
          </Card>
        </div>
      </form>
    </main>
  )
}
