"use client"

import { useState } from "react"
import { useMutation } from "convex/react"
import { toast } from "sonner"
import { api } from "../../../../../convex/_generated/api"
import type { Id } from "../../../../../convex/_generated/dataModel"
import { dollarsToCents } from "@repo/utils"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog"
import { Button } from "../ui/button"
import { ScrollArea } from "../ui/scroll-area"
import { VariantForm, CREATE_DEFAULTS, type VariantFormValues } from "./VariantForm"

const FORM_ID = "create-variant-form"

interface CreateVariantDialogProps {
  productId: Id<"products">
  productName: string
  brand?: string
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function CreateVariantDialog({
  productId,
  productName,
  brand,
  open,
  onOpenChange,
}: CreateVariantDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const addVariant = useMutation(api.products.addVariant)

  async function handleSubmit(values: VariantFormValues) {
    setIsSubmitting(true)
    try {
      const attrSize = values.attrSize?.trim() || undefined
      const attrFlavor = values.attrFlavor?.trim() || undefined
      const attrColor = values.attrColor?.trim() || undefined
      const hasAttrs = attrSize || attrFlavor || attrColor

      await addVariant({
        productId,
        name: values.name,
        sku: values.sku,
        price: dollarsToCents(values.price),
        compareAtPrice: values.onSale && values.compareAtPrice != null
          ? dollarsToCents(values.compareAtPrice)
          : undefined,
        stockQuantity: values.stockQuantity,
        isActive: values.isActive,
        weight: values.weight,
        weightUnit: values.weightUnit,
        attributes: hasAttrs
          ? { size: attrSize, flavor: attrFlavor, color: attrColor }
          : undefined,
        length: values.length,
        width: values.width,
        height: values.height,
        dimensionUnit: values.dimensionUnit,
      })

      toast.success(`Variant "${values.name}" created`)
      onOpenChange(false)
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to create variant")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg" showCloseButton={false}>
        <DialogHeader>
          <DialogTitle>Create variant</DialogTitle>
        </DialogHeader>

        <ScrollArea className="max-h-[65vh] pr-1">
          <div className="pb-2">
            <VariantForm
              formId={FORM_ID}
              defaultValues={CREATE_DEFAULTS}
              onSubmit={handleSubmit}
              productName={productName}
              brand={brand}
              mode="create"
            />
          </div>
        </ScrollArea>

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isSubmitting}
          >
            Cancel
          </Button>
          <Button type="submit" form={FORM_ID} disabled={isSubmitting}>
            {isSubmitting && (
              <svg
                data-icon="inline-start"
                className="animate-spin"
                viewBox="0 0 24 24"
                fill="none"
                aria-hidden="true"
              >
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
            )}
            {isSubmitting ? "Creating…" : "Create variant"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
