"use client"

import React from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"

export type PreviewProduct = {
  _id: string
  name: string
  slug: string
  status: "active" | "draft" | "archived"
  description?: string
  shortDescription?: string
  brand?: string
  tags: string[]
  parentCategorySlug?: string
  childCategorySlug?: string
  topCategorySlug?: string
  attributes?: {
    petSize?: string[]
    ageRange?: string[]
    specialDiet?: string[]
    material?: string
    flavor?: string
  }
  seoTitle?: string
  seoDescription?: string
  canonicalSlug?: string
  createdAt?: number
  updatedAt?: number
  averageRating?: number
  reviewCount?: number
}

const STATUS_CONFIG = {
  active: { label: "Active", variant: "default" as const },
  draft: { label: "Draft", variant: "secondary" as const },
  archived: { label: "Archived", variant: "outline" as const },
}

function formatDate(ms?: number) {
  if (!ms) return "—"
  return new Date(ms).toLocaleString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  })
}

function InfoRow({
  label,
  children,
}: {
  label: string
  children?: React.ReactNode
}) {
  if (children == null || children === "") return null
  return (
    <div className="grid grid-cols-[128px_1fr] gap-2 py-0.5">
      <span className="pt-0.5 text-xs text-muted-foreground">{label}</span>
      <span className="break-words text-sm">{children}</span>
    </div>
  )
}

interface ProductPreviewDialogProps {
  product: PreviewProduct | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function ProductPreviewDialog({
  product,
  open,
  onOpenChange,
}: ProductPreviewDialogProps) {
  if (!product) return null

  const statusCfg = STATUS_CONFIG[product.status]
  const attrs = product.attributes
  const hasAttrs =
    attrs &&
    ((attrs.petSize?.length ?? 0) > 0 ||
      (attrs.ageRange?.length ?? 0) > 0 ||
      (attrs.specialDiet?.length ?? 0) > 0 ||
      attrs.material ||
      attrs.flavor)
  const hasSeo =
    product.seoTitle || product.seoDescription || product.canonicalSlug

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle>{product.name}</DialogTitle>
        </DialogHeader>

        <ScrollArea className="max-h-[60vh]">
          <div className="space-y-3 py-1">
            {/* Core fields */}
            <div className="space-y-0.5">
              <InfoRow label="Status">
                <Badge variant={statusCfg.variant}>{statusCfg.label}</Badge>
              </InfoRow>
              <InfoRow label="Slug">{product.slug}</InfoRow>
              <InfoRow label="Brand">{product.brand}</InfoRow>
            </div>

            <Separator />

            {/* Category */}
            <div className="space-y-0.5">
              <p className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                Category
              </p>
              <InfoRow label="Parent">{product.parentCategorySlug}</InfoRow>
              <InfoRow label="Child">{product.childCategorySlug}</InfoRow>
              <InfoRow label="Top">{product.topCategorySlug}</InfoRow>
            </div>

            {(product.shortDescription || product.description) && (
              <>
                <Separator />
                <div>
                  <p className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Description
                  </p>
                  <InfoRow label="Short">{product.shortDescription}</InfoRow>
                  {product.description && (
                    <div className="py-0.5">
                      <p className="mb-1 text-xs text-muted-foreground">Full</p>
                      <p className="whitespace-pre-wrap text-sm leading-relaxed">
                        {product.description}
                      </p>
                    </div>
                  )}
                </div>
              </>
            )}

            {product.tags.length > 0 && (
              <>
                <Separator />
                <InfoRow label="Tags">
                  <div className="flex flex-wrap gap-1">
                    {product.tags.map((t) => (
                      <Badge key={t} variant="secondary">
                        {t}
                      </Badge>
                    ))}
                  </div>
                </InfoRow>
              </>
            )}

            {hasAttrs && (
              <>
                <Separator />
                <div className="space-y-0.5">
                  <p className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    Attributes
                  </p>
                  {(attrs?.petSize?.length ?? 0) > 0 && (
                    <InfoRow label="Pet size">{attrs!.petSize!.join(", ")}</InfoRow>
                  )}
                  {(attrs?.ageRange?.length ?? 0) > 0 && (
                    <InfoRow label="Age range">{attrs!.ageRange!.join(", ")}</InfoRow>
                  )}
                  {(attrs?.specialDiet?.length ?? 0) > 0 && (
                    <InfoRow label="Special diet">
                      {attrs!.specialDiet!.join(", ")}
                    </InfoRow>
                  )}
                  {attrs?.material && (
                    <InfoRow label="Material">{attrs.material}</InfoRow>
                  )}
                  {attrs?.flavor && (
                    <InfoRow label="Flavor">{attrs.flavor}</InfoRow>
                  )}
                </div>
              </>
            )}

            {hasSeo && (
              <>
                <Separator />
                <div className="space-y-0.5">
                  <p className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                    SEO
                  </p>
                  <InfoRow label="SEO title">{product.seoTitle}</InfoRow>
                  <InfoRow label="SEO description">{product.seoDescription}</InfoRow>
                  <InfoRow label="Canonical slug">{product.canonicalSlug}</InfoRow>
                </div>
              </>
            )}

            <Separator />

            {/* Meta */}
            <div className="space-y-0.5">
              <p className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
                Meta
              </p>
              <InfoRow label="Created">{formatDate(product.createdAt)}</InfoRow>
              <InfoRow label="Updated">{formatDate(product.updatedAt)}</InfoRow>
              {product.averageRating != null && (
                <InfoRow label="Rating">
                  {product.averageRating.toFixed(1)} ({product.reviewCount ?? 0}{" "}
                  reviews)
                </InfoRow>
              )}
            </div>
          </div>
        </ScrollArea>

        <DialogFooter showCloseButton />
      </DialogContent>
    </Dialog>
  )
}
