"use client"

import { useState } from "react"
import { useQuery, useMutation } from "convex/react"
import { useRouter, useParams } from "next/navigation"
import Link from "next/link"
import { api } from "../../../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../../../convex/_generated/dataModel"
import { Button, buttonVariants } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { Skeleton } from "@/components/ui/skeleton"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  ProductForm,
  buildProductPayload,
  type ProductFormValues,
} from "@/components/products/ProductForm"
import { HugeiconsIcon } from "@hugeicons/react"
import { ArrowLeft01Icon, Archive01Icon } from "@hugeicons/core-free-icons"

export default function EditProductPage() {
  const params = useParams()
  const productId = params.id as Id<"products">
  const router = useRouter()

  const product = useQuery(api.products.getByIdForAdmin, { id: productId })
  const categories = useQuery(api.categories.list, {}) ?? []
  const updateProduct = useMutation(api.products.update)
  const archiveProduct = useMutation(api.products.archive)

  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [archiveOpen, setArchiveOpen] = useState(false)
  const [isArchiving, setIsArchiving] = useState(false)

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

  async function handleArchive() {
    setIsArchiving(true)
    try {
      await archiveProduct({ id: productId })
      router.push("/products")
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to archive product.")
      setIsArchiving(false)
    }
  }

  // Loading state
  if (product === undefined) {
    return (
      <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
        <div className="flex flex-col gap-1">
          <Skeleton className="h-7 w-20" />
          <Skeleton className="h-7 w-48" />
        </div>
        <div className="max-w-2xl space-y-8">
          <div className="space-y-4">
            <Skeleton className="h-4 w-16" />
            <Skeleton className="h-9 w-full" />
            <Skeleton className="h-9 w-full" />
            <div className="grid grid-cols-2 gap-4">
              <Skeleton className="h-9 w-full" />
              <Skeleton className="h-9 w-full" />
            </div>
          </div>
        </div>
      </main>
    )
  }

  // Not found
  if (product === null) {
    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">Product not found</h1>
        </div>
        <p className="text-sm text-muted-foreground">
          This product does not exist or you do not have permission to view it.
        </p>
      </main>
    )
  }

  const defaultValues: Partial<ProductFormValues> = {
    name: product.name ?? "",
    slug: product.slug ?? "",
    status: product.status ?? "draft",
    categoryId: product.categoryId ?? "",
    tags: (product.tags ?? []).join(", "),
    shortDescription: product.shortDescription ?? "",
    description: product.description ?? "",
    brand: product.brand ?? "",
    petSize: (product.attributes?.petSize ?? []).join(", "),
    ageRange: (product.attributes?.ageRange ?? []).join(", "),
    specialDiet: (product.attributes?.specialDiet ?? []).join(", "),
    material: product.attributes?.material ?? "",
    flavor: product.attributes?.flavor ?? "",
    seoTitle: product.seoTitle ?? "",
    seoDescription: product.seoDescription ?? "",
    canonicalSlug: product.canonicalSlug ?? "",
  }

  return (
    <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
      <div className="flex items-start justify-between">
        <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">{product.name}</h1>
        </div>

        {product.status !== "archived" && (
          <Button
            variant="outline"
            size="sm"
            className="text-destructive hover:text-destructive"
            onClick={() => setArchiveOpen(true)}
          >
            <HugeiconsIcon icon={Archive01Icon} strokeWidth={2} />
            Archive
          </Button>
        )}
      </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="edit"
          categories={categories}
          defaultValues={defaultValues}
          onSubmit={handleSubmit}
          isSubmitting={isSubmitting}
        />
      </div>

      <AlertDialog open={archiveOpen} onOpenChange={setArchiveOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>
              Archive &ldquo;{product.name}&rdquo;?
            </AlertDialogTitle>
            <AlertDialogDescription>
              This product will no longer appear on the storefront. You can
              restore it by editing the product status later.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              onClick={handleArchive}
              disabled={isArchiving}
            >
              {isArchiving ? "Archiving…" : "Archive"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </main>
  )
}
