"use client"

import { useState } from "react"
import { useMutation } from "convex/react"
import { toast } from "sonner"
import { api } from "../../../../../convex/_generated/api"
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, variantToFormValues, type VariantFormValues } from "./VariantForm"
import type { Variant } from "./VariantsTable"

const FORM_ID = "edit-variant-form"

interface EditVariantDialogProps {
  variant: Variant | null
  productName: string
  brand?: string
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function EditVariantDialog({
  variant,
  productName,
  brand,
  open,
  onOpenChange,
}: EditVariantDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const updateVariant = useMutation(api.products.updateVariant)

  async function handleSubmit(values: VariantFormValues) {
    if (!variant) return
    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 updateVariant({
        id: variant._id,
        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(`"${values.name}" updated`)
      onOpenChange(false)
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to update variant")
    } finally {
      setIsSubmitting(false)
    }
  }

  if (!variant) return null

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

        <ScrollArea className="max-h-[65vh] pr-1">
          <div className="pb-2">
            <VariantForm
              formId={FORM_ID}
              defaultValues={variantToFormValues(variant)}
              onSubmit={handleSubmit}
              productName={productName}
              brand={brand}
              mode="edit"
            />
          </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 ? "Saving…" : "Save changes"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
