"use client"

import { useEffect, useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { centsToDollars, generateSku } from "@repo/utils"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "../ui/form"
import { Input } from "../ui/input"
import { Switch } from "../ui/switch"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select"
import { Separator } from "../ui/separator"
import type { Variant } from "./VariantsTable"

// ─── Schema ───────────────────────────────────────────────────────────────────

const optionalPositiveNum = z.preprocess(
  (v) => (v === "" || v == null ? undefined : Number(v)),
  z.number().positive().optional(),
) as z.ZodType<number | undefined>

export const variantFormSchema = z
  .object({
    name: z.string().min(1, "Name is required"),
    sku: z.string().min(1, "SKU is required"),
    price: z.coerce.number({ invalid_type_error: "Enter a valid price" }).positive("Price must be greater than 0"),
    stockQuantity: z.coerce.number({ invalid_type_error: "Enter a valid number" }).int().min(0, "Stock must be 0 or more"),
    isActive: z.boolean(),
    weight: z.coerce.number({ invalid_type_error: "Enter a valid weight" }).positive("Weight must be greater than 0"),
    weightUnit: z.enum(["g", "kg", "lb", "oz"]),
    onSale: z.boolean(),
    compareAtPrice: optionalPositiveNum,
    attrSize: z.string().optional(),
    attrFlavor: z.string().optional(),
    attrColor: z.string().optional(),
    length: optionalPositiveNum,
    width: optionalPositiveNum,
    height: optionalPositiveNum,
    dimensionUnit: z.enum(["cm", "in"]).optional(),
  })
  .superRefine((data, ctx) => {
    if (data.onSale && !data.compareAtPrice) {
      ctx.addIssue({
        code: "custom",
        path: ["compareAtPrice"],
        message: "Compare at price is required when on sale",
      })
    }
    const hasDim = data.length != null || data.width != null || data.height != null
    if (hasDim) {
      if (data.length == null)
        ctx.addIssue({ code: "custom", path: ["length"], message: "Required when any dimension is set" })
      if (data.width == null)
        ctx.addIssue({ code: "custom", path: ["width"], message: "Required when any dimension is set" })
      if (data.height == null)
        ctx.addIssue({ code: "custom", path: ["height"], message: "Required when any dimension is set" })
      if (!data.dimensionUnit)
        ctx.addIssue({ code: "custom", path: ["dimensionUnit"], message: "Required when dimensions are set" })
    }
  })

export type VariantFormValues = z.infer<typeof variantFormSchema>

// ─── Helpers ──────────────────────────────────────────────────────────────────

export function variantToFormValues(variant: Variant): VariantFormValues {
  return {
    name: variant.name,
    sku: variant.sku,
    price: centsToDollars(variant.price),
    stockQuantity: variant.stockQuantity,
    isActive: variant.isActive,
    weight: variant.weight,
    weightUnit: variant.weightUnit,
    onSale: variant.compareAtPrice != null,
    compareAtPrice: variant.compareAtPrice != null ? centsToDollars(variant.compareAtPrice) : undefined,
    attrSize: variant.attributes?.size ?? "",
    attrFlavor: variant.attributes?.flavor ?? "",
    attrColor: variant.attributes?.color ?? "",
    length: variant.length,
    width: variant.width,
    height: variant.height,
    dimensionUnit: variant.dimensionUnit ?? "cm",
  }
}

export const CREATE_DEFAULTS: VariantFormValues = {
  name: "",
  sku: "",
  price: 0,
  stockQuantity: 0,
  isActive: true,
  weight: 0,
  weightUnit: "kg",
  onSale: false,
  compareAtPrice: undefined,
  attrSize: "",
  attrFlavor: "",
  attrColor: "",
  length: undefined,
  width: undefined,
  height: undefined,
  dimensionUnit: "cm",
}

// ─── Component ────────────────────────────────────────────────────────────────

interface VariantFormProps {
  formId: string
  defaultValues: VariantFormValues
  onSubmit: (values: VariantFormValues) => Promise<void>
  productName?: string
  brand?: string
  /** In edit mode the SKU starts as manually set — auto-gen is off by default */
  mode?: "create" | "edit"
}

export function VariantForm({
  formId,
  defaultValues,
  onSubmit,
  productName = "",
  brand = "",
  mode = "create",
}: VariantFormProps) {
  const [skuManuallyEdited, setSkuManuallyEdited] = useState(mode === "edit")

  const form = useForm<VariantFormValues>({
    resolver: zodResolver(variantFormSchema),
    defaultValues,
  })

  // Reset when defaultValues change (e.g. switching from one variant to another)
  useEffect(() => {
    form.reset(defaultValues)
    setSkuManuallyEdited(mode === "edit")
  }, [defaultValues]) // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-generate SKU from variant-level details only
  const [attrFlavor, attrSize, attrColor, weight, weightUnit] = form.watch([
    "attrFlavor",
    "attrSize",
    "attrColor",
    "weight",
    "weightUnit",
  ])

  useEffect(() => {
    if (skuManuallyEdited) return
    const suggested = generateSku(
      brand,
      productName,
      { flavor: attrFlavor, size: attrSize, color: attrColor },
      weight || undefined,
      weightUnit,
    )
    if (suggested) form.setValue("sku", suggested)
  }, [brand, productName, attrFlavor, attrSize, attrColor, weight, weightUnit, skuManuallyEdited]) // eslint-disable-line react-hooks/exhaustive-deps

  const onSale = form.watch("onSale")
  const length = form.watch("length")
  const width = form.watch("width")
  const height = form.watch("height")
  const showDimensionUnit = length != null || width != null || height != null

  return (
    <Form {...form}>
      <form id={formId} onSubmit={form.handleSubmit(onSubmit)} className="space-y-5">

        {/* ── Identity ─────────────────────────────────────────────── */}
        <div className="grid grid-cols-2 items-start gap-4">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Name</FormLabel>
                <FormControl>
                  <Input placeholder="500g bag" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="sku"
            render={({ field }) => (
              <FormItem>
                <FormLabel>SKU</FormLabel>
                <FormControl>
                  <Input
                    placeholder="RC-ADG-5KG"
                    {...field}
                    onChange={(e) => {
                      setSkuManuallyEdited(true)
                      field.onChange(e.target.value.toUpperCase())
                    }}
                  />
                </FormControl>
                <FormDescription>
                  {skuManuallyEdited ? "Manually set." : "Auto-generated from details."}
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <Separator />

        {/* ── Pricing ──────────────────────────────────────────────── */}
        <div className="space-y-4">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Pricing</p>

          <div className="grid grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="price"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Price (£)</FormLabel>
                  <FormControl>
                    <Input type="number" step="0.01" min="0" placeholder="19.99" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="onSale"
              render={({ field }) => (
                <FormItem className="flex flex-col justify-end pb-1">
                  <FormLabel>On sale</FormLabel>
                  <div className="flex items-center gap-2">
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <span className="text-sm text-muted-foreground">
                      {field.value ? "Yes" : "No"}
                    </span>
                  </div>
                </FormItem>
              )}
            />
          </div>

          {onSale && (
            <FormField
              control={form.control}
              name="compareAtPrice"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Compare at price (£)</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      step="0.01"
                      min="0"
                      placeholder="24.99"
                      value={field.value ?? ""}
                      onChange={field.onChange}
                    />
                  </FormControl>
                  <FormDescription>Original price shown as strikethrough.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}
        </div>

        <Separator />

        {/* ── Inventory ────────────────────────────────────────────── */}
        <div className="space-y-4">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Inventory</p>

          <div className="grid grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="stockQuantity"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Stock quantity</FormLabel>
                  <FormControl>
                    <Input type="number" min="0" step="1" placeholder="0" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="isActive"
              render={({ field }) => (
                <FormItem className="flex flex-col justify-end pb-1">
                  <FormLabel>Active</FormLabel>
                  <div className="flex items-center gap-2">
                    <FormControl>
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <span className="text-sm text-muted-foreground">
                      {field.value ? "Visible" : "Hidden"}
                    </span>
                  </div>
                </FormItem>
              )}
            />
          </div>
        </div>

        <Separator />

        {/* ── Shipping ─────────────────────────────────────────────── */}
        <div className="space-y-4">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Shipping</p>

          <div className="grid grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="weight"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Weight</FormLabel>
                  <FormControl>
                    <Input type="number" step="0.001" min="0" placeholder="0.5" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="weightUnit"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Unit</FormLabel>
                  <Select value={field.value} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="kg">kg</SelectItem>
                      <SelectItem value="g">g</SelectItem>
                      <SelectItem value="lb">lb</SelectItem>
                      <SelectItem value="oz">oz</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          {/* Dimensions */}
          <div className="grid grid-cols-3 gap-3">
            {(["length", "width", "height"] as const).map((dim) => (
              <FormField
                key={dim}
                control={form.control}
                name={dim}
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="capitalize">{dim}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.1"
                        min="0"
                        placeholder="—"
                        value={field.value ?? ""}
                        onChange={field.onChange}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            ))}
          </div>

          {showDimensionUnit && (
            <FormField
              control={form.control}
              name="dimensionUnit"
              render={({ field }) => (
                <FormItem className="max-w-[120px]">
                  <FormLabel>Dimension unit</FormLabel>
                  <Select value={field.value ?? "cm"} onValueChange={field.onChange}>
                    <FormControl>
                      <SelectTrigger className="w-full">
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="cm">cm</SelectItem>
                      <SelectItem value="in">in</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
          )}
        </div>

        <Separator />

        {/* ── Attributes (optional) ────────────────────────────────── */}
        <div className="space-y-4">
          <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
            Attributes <span className="normal-case font-normal">(optional)</span>
          </p>
          <div className="grid grid-cols-3 gap-3">
            <FormField
              control={form.control}
              name="attrSize"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Size</FormLabel>
                  <FormControl>
                    <Input placeholder="500g" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="attrFlavor"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Flavor</FormLabel>
                  <FormControl>
                    <Input placeholder="Chicken" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="attrColor"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Color</FormLabel>
                  <FormControl>
                    <Input placeholder="Red" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

      </form>
    </Form>
  )
}
