"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 { formatPrice } from "@repo/utils"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table"
import { Badge } from "../ui/badge"
import { Button } from "../ui/button"
import { Skeleton } from "../ui/skeleton"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "../ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "../ui/alert-dialog"
import { HugeiconsIcon } from "@hugeicons/react"
import {
  MoreVerticalIcon,
  PencilEdit01Icon,
  Delete01Icon,
  CheckmarkCircle01Icon,
  Cancel01Icon,
} from "@hugeicons/core-free-icons"

export interface Variant {
  _id: Id<"productVariants">
  name: string
  sku: string
  price: number
  compareAtPrice?: number
  stockQuantity: number
  isActive: boolean
  weight: number
  weightUnit: "g" | "kg" | "lb" | "oz"
  attributes?: { size?: string; flavor?: string; color?: string }
  length?: number
  width?: number
  height?: number
  dimensionUnit?: "cm" | "in"
}

interface VariantsTableProps {
  variants: Variant[]
  onPreview: (variant: Variant) => void
  onEdit: (variant: Variant) => void
}

function TableSkeleton() {
  return (
    <>
      {Array.from({ length: 6 }).map((_, i) => (
        <TableRow key={i}>
          <TableCell><Skeleton className="h-4 w-32" /></TableCell>
          <TableCell><Skeleton className="h-4 w-24" /></TableCell>
          <TableCell><Skeleton className="h-4 w-16" /></TableCell>
          <TableCell><Skeleton className="h-4 w-16" /></TableCell>
          <TableCell><Skeleton className="h-4 w-10" /></TableCell>
          <TableCell><Skeleton className="h-5 w-16 rounded-full" /></TableCell>
          <TableCell><Skeleton className="h-4 w-16" /></TableCell>
          <TableCell><Skeleton className="size-7 rounded-lg" /></TableCell>
        </TableRow>
      ))}
    </>
  )
}

function VariantActionsMenu({
  variant,
  onEdit,
}: {
  variant: Variant
  onEdit: (variant: Variant) => void
}) {
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [isToggling, setIsToggling] = useState(false)
  const deleteVariant = useMutation(api.products.deleteVariant)
  const updateVariant = useMutation(api.products.updateVariant)

  async function handleToggleActive() {
    setIsToggling(true)
    try {
      await updateVariant({ id: variant._id, isActive: !variant.isActive })
      toast.success(`"${variant.name}" ${variant.isActive ? "deactivated" : "activated"}`)
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to update variant")
    } finally {
      setIsToggling(false)
    }
  }

  async function handleDelete() {
    setIsDeleting(true)
    try {
      await deleteVariant({ id: variant._id })
      toast.success(`"${variant.name}" deleted`)
      setDeleteOpen(false)
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to delete variant")
    } finally {
      setIsDeleting(false)
    }
  }

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger
          render={
            <Button
              variant="ghost"
              size="icon"
              aria-label={`Actions for ${variant.name}`}
            />
          }
        >
          <HugeiconsIcon icon={MoreVerticalIcon} strokeWidth={2} />
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem onClick={() => onEdit(variant)}>
            <HugeiconsIcon icon={PencilEdit01Icon} strokeWidth={2} />
            Edit
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            onClick={handleToggleActive}
            disabled={isToggling}
          >
            <HugeiconsIcon
              icon={variant.isActive ? Cancel01Icon : CheckmarkCircle01Icon}
              strokeWidth={2}
            />
            {variant.isActive ? "Deactivate" : "Activate"}
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            variant="destructive"
            onClick={() => setDeleteOpen(true)}
          >
            <HugeiconsIcon icon={Delete01Icon} strokeWidth={2} />
            Delete
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete &ldquo;{variant.name}&rdquo;?</AlertDialogTitle>
            <AlertDialogDescription>
              {variant.isActive
                ? "This variant will be permanently deleted. If it appears in existing orders, it will be deactivated instead."
                : "This variant will be permanently deleted."}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              variant="destructive"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting ? "Deleting…" : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

export function VariantsTable({ variants, onPreview, onEdit }: VariantsTableProps) {
  return (
    <div className="rounded-lg border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead scope="col">Name</TableHead>
            <TableHead scope="col">SKU</TableHead>
            <TableHead scope="col">Price</TableHead>
            <TableHead scope="col">Compare at</TableHead>
            <TableHead scope="col">Stock</TableHead>
            <TableHead scope="col">Status</TableHead>
            <TableHead scope="col">Weight</TableHead>
            <TableHead scope="col" className="w-10" />
          </TableRow>
        </TableHeader>
        <TableBody>
          {variants.length === 0 ? (
            <TableRow>
              <TableCell
                colSpan={8}
                className="py-16 text-center text-sm text-muted-foreground"
              >
                No variants yet. Create the first variant for this product.
              </TableCell>
            </TableRow>
          ) : (
            variants.map((variant) => (
              <TableRow key={variant._id}>
                <TableCell>
                  <button
                    type="button"
                    className="font-medium hover:underline text-left"
                    onClick={() => onPreview(variant)}
                  >
                    {variant.name}
                  </button>
                </TableCell>
                <TableCell className="font-mono text-xs text-muted-foreground">
                  {variant.sku}
                </TableCell>
                <TableCell>{formatPrice(variant.price)}</TableCell>
                <TableCell className="text-muted-foreground">
                  {variant.compareAtPrice ? formatPrice(variant.compareAtPrice) : "—"}
                </TableCell>
                <TableCell>{variant.stockQuantity}</TableCell>
                <TableCell>
                  <Badge variant={variant.isActive ? "default" : "secondary"}>
                    {variant.isActive ? "Active" : "Inactive"}
                  </Badge>
                </TableCell>
                <TableCell className="text-muted-foreground">
                  {variant.weight} {variant.weightUnit}
                </TableCell>
                <TableCell>
                  <VariantActionsMenu variant={variant} onEdit={onEdit} />
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  )
}

export { TableSkeleton as VariantsTableSkeleton }
