"use client"

import { useState } from "react"
import { useQuery, useMutation } from "convex/react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { api } from "../../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../../convex/_generated/dataModel"
import { buttonVariants } from "@/components/ui/button"
import {
  ProductForm,
  buildProductPayload,
  type ProductFormValues,
} from "@/components/products/ProductForm"
import { HugeiconsIcon } from "@hugeicons/react"
import { ArrowLeft01Icon } from "@hugeicons/core-free-icons"
import { cn } from "@/lib/utils"

export default function NewProductPage() {
  const router = useRouter()
  const categories = useQuery(api.categories.list, {}) ?? []
  const createProduct = useMutation(api.products.create)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(values: ProductFormValues) {
    setIsSubmitting(true)
    setError(null)
    try {
      const payload = buildProductPayload(values)
      await createProduct({
        ...payload,
        categoryId: payload.categoryId as Id<"categories">,
      })
      router.push("/products")
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to create product. Please try again.")
      setIsSubmitting(false)
    }
  }

  return (
    <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
      <div className="flex flex-col gap-1">
        <Link
          href="/products"
          className={cn(buttonVariants({ variant: "ghost", size: "sm" }), "w-fit -ml-2")}
        >
          <HugeiconsIcon icon={ArrowLeft01Icon} strokeWidth={2} />
          Products
        </Link>
        <h1 className="text-xl font-semibold">New product</h1>
      </div>

      {error && (
        <p className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
          {error}
        </p>
      )}

      <div className="max-w-2xl">
        <ProductForm
          mode="create"
          categories={categories}
          onSubmit={handleSubmit}
          isSubmitting={isSubmitting}
        />
      </div>
    </main>
  )
}
