"use client"

import { useEffect, useMemo, useState } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { slugify } from "@repo/utils"
import Link from "next/link"
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Button, buttonVariants } from "@/components/ui/button"
import { Separator } from "@/components/ui/separator"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { HugeiconsIcon } from "@hugeicons/react"
import { ArrowDown01Icon } from "@hugeicons/core-free-icons"

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

const formSchema = z.object({
  name: z.string().min(1, "Name is required"),
  slug: z
    .string()
    .min(1, "Slug is required")
    .regex(/^[a-z0-9-]+$/, "Lowercase letters, numbers, and hyphens only"),
  status: z.enum(["active", "draft", "archived"]),
  categoryId: z.string().min(1, "Category is required"),
  tags: z.string().default(""),
  shortDescription: z.string().optional(),
  description: z.string().optional(),
  brand: z.string().optional(),
  // Attributes — comma-separated for array fields
  petSize: z.string().optional(),
  ageRange: z.string().optional(),
  specialDiet: z.string().optional(),
  material: z.string().optional(),
  flavor: z.string().optional(),
  // SEO
  seoTitle: z.string().optional(),
  seoDescription: z.string().optional(),
  canonicalSlug: z.string().optional(),
})

export type ProductFormValues = z.infer<typeof formSchema>

// ─── Types ─────────────────────────────────────────────────────────────────────

export type CategoryOption = {
  _id: string
  name: string
  slug: string
  parentId?: string
}

interface ProductFormProps {
  mode: "create" | "edit"
  categories: CategoryOption[]
  defaultValues?: Partial<ProductFormValues>
  onSubmit: (values: ProductFormValues) => Promise<void>
  isSubmitting: boolean
}

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

function parseCommaList(str?: string): string[] {
  if (!str?.trim()) return []
  return str
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean)
}

export function buildProductPayload(values: ProductFormValues) {
  const tags = parseCommaList(values.tags)

  const petSize = parseCommaList(values.petSize)
  const ageRange = parseCommaList(values.ageRange)
  const specialDiet = parseCommaList(values.specialDiet)
  const material = values.material?.trim() || undefined
  const flavor = values.flavor?.trim() || undefined

  const hasAttrs =
    petSize.length > 0 ||
    ageRange.length > 0 ||
    specialDiet.length > 0 ||
    material ||
    flavor

  return {
    name: values.name,
    slug: values.slug,
    status: values.status,
    categoryId: values.categoryId,
    tags,
    description: values.description?.trim() || undefined,
    shortDescription: values.shortDescription?.trim() || undefined,
    brand: values.brand?.trim() || undefined,
    attributes: hasAttrs
      ? {
          ...(petSize.length > 0 && { petSize }),
          ...(ageRange.length > 0 && { ageRange }),
          ...(specialDiet.length > 0 && { specialDiet }),
          ...(material && { material }),
          ...(flavor && { flavor }),
        }
      : undefined,
    seoTitle: values.seoTitle?.trim() || undefined,
    seoDescription: values.seoDescription?.trim() || undefined,
    canonicalSlug: values.canonicalSlug?.trim() || undefined,
  }
}

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

export function ProductForm({
  mode,
  categories,
  defaultValues,
  onSubmit,
  isSubmitting,
}: ProductFormProps) {
  const [slugManuallySet, setSlugManuallySet] = useState(mode === "edit")

  const form = useForm<ProductFormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      slug: "",
      status: "draft",
      categoryId: "",
      tags: "",
      shortDescription: "",
      description: "",
      brand: "",
      petSize: "",
      ageRange: "",
      specialDiet: "",
      material: "",
      flavor: "",
      seoTitle: "",
      seoDescription: "",
      canonicalSlug: "",
      ...defaultValues,
    },
  })

  // Auto-derive slug from name in create mode
  const nameValue = form.watch("name")
  useEffect(() => {
    if (!slugManuallySet && nameValue) {
      form.setValue("slug", slugify(nameValue), { shouldValidate: false })
    }
  }, [nameValue, slugManuallySet, form])

  // Build category options with "Parent / Child" display labels
  const categoryOptions = useMemo(() => {
    const idToName: Record<string, string> = {}
    for (const cat of categories) idToName[cat._id] = cat.name
    return categories
      .filter((cat) => cat.parentId)
      .map((cat) => ({
        value: cat._id,
        label: `${idToName[cat.parentId!] ?? "?"} / ${cat.name}`,
      }))
      .sort((a, b) => a.label.localeCompare(b.label))
  }, [categories])

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        {/* ── Core ───────────────────────────────────────────────────── */}
        <section className="space-y-4">
          <h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
            Core
          </h2>

          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Name</FormLabel>
                <FormControl>
                  <Input placeholder="Royal Canin Adult Cat" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="slug"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Slug</FormLabel>
                <FormControl>
                  <Input
                    placeholder="royal-canin-adult-cat"
                    {...field}
                    onChange={(e) => {
                      setSlugManuallySet(true)
                      field.onChange(e)
                    }}
                  />
                </FormControl>
                <FormDescription>
                  URL-safe identifier. Auto-generated from name; edit to
                  override.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="grid grid-cols-2 gap-4">
            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Status</FormLabel>
                  <Select
                    value={field.value}
                    onValueChange={(v) => field.onChange(v)}
                  >
                    <FormControl>
                      <SelectTrigger className="w-full">
                        <SelectValue placeholder="Select status" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="archived">Archived</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="categoryId"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Category</FormLabel>
                  <Select
                    value={field.value}
                    onValueChange={(v) => field.onChange(v)}
                  >
                    <FormControl>
                      <SelectTrigger className="w-full">
                        <SelectValue placeholder="Select category" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {categories.length === 0 ? (
                        <SelectItem value="_loading" disabled>
                          Loading…
                        </SelectItem>
                      ) : (
                        categoryOptions.map((opt) => (
                          <SelectItem key={opt.value} value={opt.value}>
                            {opt.label}
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>

          <FormField
            control={form.control}
            name="tags"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Tags</FormLabel>
                <FormControl>
                  <Input placeholder="cat-food, dry, indoor" {...field} />
                </FormControl>
                <FormDescription>Comma-separated list of tags.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </section>

        <Separator />

        {/* ── Details ────────────────────────────────────────────────── */}
        <section className="space-y-4">
          <h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
            Details
          </h2>

          <FormField
            control={form.control}
            name="brand"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Brand</FormLabel>
                <FormControl>
                  <Input placeholder="Royal Canin" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="shortDescription"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Short description</FormLabel>
                <FormControl>
                  <Textarea
                    placeholder="One or two sentences shown in listings…"
                    className="resize-none"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Full description</FormLabel>
                <FormControl>
                  <Textarea
                    placeholder="Detailed product description…"
                    className="min-h-32 resize-y"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </section>

        <Separator />

        {/* ── Attributes (collapsible) ────────────────────────────────── */}
        <Collapsible className="group/collapsible">
          <CollapsibleTrigger className="flex w-full items-center justify-between py-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors">
            <span className="uppercase tracking-wide">Attributes</span>
            <HugeiconsIcon
              icon={ArrowDown01Icon}
              strokeWidth={2}
              className="size-4 transition-transform group-data-[open]/collapsible:rotate-180"
            />
          </CollapsibleTrigger>
          <CollapsibleContent className="space-y-4 pt-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="petSize"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Pet size</FormLabel>
                    <FormControl>
                      <Input placeholder="small, medium, large" {...field} />
                    </FormControl>
                    <FormDescription>Comma-separated.</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="ageRange"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Age range</FormLabel>
                    <FormControl>
                      <Input placeholder="puppy, adult, senior" {...field} />
                    </FormControl>
                    <FormDescription>Comma-separated.</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="specialDiet"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Special diet</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="grain-free, hypoallergenic"
                      {...field}
                    />
                  </FormControl>
                  <FormDescription>Comma-separated.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="material"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Material</FormLabel>
                    <FormControl>
                      <Input placeholder="Nylon" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="flavor"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Flavor</FormLabel>
                    <FormControl>
                      <Input placeholder="Chicken" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </CollapsibleContent>
        </Collapsible>

        <Separator />

        {/* ── SEO / Advanced (collapsible) ───────────────────────────── */}
        <Collapsible className="group/collapsible">
          <CollapsibleTrigger className="flex w-full items-center justify-between py-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors">
            <span className="uppercase tracking-wide">Advanced / SEO</span>
            <HugeiconsIcon
              icon={ArrowDown01Icon}
              strokeWidth={2}
              className="size-4 transition-transform group-data-[open]/collapsible:rotate-180"
            />
          </CollapsibleTrigger>
          <CollapsibleContent className="space-y-4 pt-4">
            <FormField
              control={form.control}
              name="seoTitle"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>SEO title</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Overrides product name in search results"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="seoDescription"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>SEO description</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Meta description for search engines…"
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="canonicalSlug"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Canonical slug</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Overrides slug for canonical URL"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </CollapsibleContent>
        </Collapsible>

        {/* ── Actions ────────────────────────────────────────────────── */}
        <div className="flex items-center gap-3 pt-2">
          <Button type="submit" 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
              ? mode === "create"
                ? "Creating…"
                : "Saving…"
              : mode === "create"
                ? "Create product"
                : "Save changes"}
          </Button>
          <Link
            href="/products"
            className={buttonVariants({ variant: "outline" })}
          >
            Cancel
          </Link>
        </div>
      </form>
    </Form>
  )
}
