"use client"

import { useState } from "react"
import { useQuery } from "convex/react"
import { api } from "../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../convex/_generated/dataModel"
import { ProductSearchSection } from "../../../components/shared/ProductSearchSection"
import { VariantsTable, VariantsTableSkeleton, type Variant } from "../../../components/variants/VariantsTable"
import { VariantPreviewDialog } from "../../../components/variants/VariantPreviewDialog"
import { CreateVariantDialog } from "../../../components/variants/CreateVariantDialog"
import { EditVariantDialog } from "../../../components/variants/EditVariantDialog"
import { Separator } from "../../../components/ui/separator"
import { Button } from "../../../components/ui/button"
import {
  Table,
  TableBody,
} from "../../../components/ui/table"
import { HugeiconsIcon } from "@hugeicons/react"
import { AddCircleIcon } from "@hugeicons/core-free-icons"

interface SelectedProduct {
  _id: string
  name: string
}

export default function VariantsPage() {
  const [selectedProduct, setSelectedProduct] = useState<SelectedProduct | null>(null)
  const [createOpen, setCreateOpen] = useState(false)
  const [editVariant, setEditVariant] = useState<Variant | null>(null)
  const [previewVariant, setPreviewVariant] = useState<Variant | null>(null)

  const productData = useQuery(
    api.products.getByIdForAdmin,
    selectedProduct ? { id: selectedProduct._id as Id<"products"> } : "skip",
  )

  function handleProductSelect(product: SelectedProduct) {
    setSelectedProduct(product)
  }

  function handleSearchClear() {
    setSelectedProduct(null)
  }

  const variants = (productData?.variants ?? []) as Variant[]
  const isLoading = selectedProduct !== null && productData === undefined

  return (
    <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
      <h1 className="text-xl font-semibold">Variants</h1>

      {/* Product search */}
      <section className="space-y-2">
        <p className="text-sm font-medium text-muted-foreground">Select a product</p>
        <ProductSearchSection
          onSelect={handleProductSelect}
          onClear={handleSearchClear}
          selectedId={selectedProduct?._id}
        />
      </section>

      {/* No product selected */}
      {!selectedProduct && (
        <p className="text-sm text-muted-foreground">
          Search and select a product to manage its variants.
        </p>
      )}

      {/* Product selected */}
      {selectedProduct && (
        <>
          <Separator />

          <section className="space-y-4">
            {/* Toolbar */}
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-base font-semibold">{selectedProduct.name}</h2>
                <p className="text-sm text-muted-foreground">
                  {isLoading
                    ? "Loading variants…"
                    : `${variants.length} variant${variants.length !== 1 ? "s" : ""}`}
                </p>
              </div>
              {!isLoading && (
                <Button onClick={() => setCreateOpen(true)}>
                  <HugeiconsIcon icon={AddCircleIcon} strokeWidth={2} />
                  Create variant
                </Button>
              )}
            </div>

            {/* Loading skeleton */}
            {isLoading && (
              <div className="rounded-lg border">
                <Table>
                  <TableBody>
                    <VariantsTableSkeleton />
                  </TableBody>
                </Table>
              </div>
            )}

            {/* Variants table */}
            {!isLoading && productData && (
              <VariantsTable
                variants={variants}
                onPreview={(v) => setPreviewVariant(v)}
                onEdit={(v) => setEditVariant(v)}
              />
            )}
          </section>
        </>
      )}

      {/* Preview dialog */}
      <VariantPreviewDialog
        variant={previewVariant}
        open={previewVariant !== null}
        onOpenChange={(open) => { if (!open) setPreviewVariant(null) }}
      />

      {/* Create dialog */}
      {selectedProduct && (
        <CreateVariantDialog
          productId={selectedProduct._id as Id<"products">}
          productName={selectedProduct.name}
          brand={productData?.brand}
          open={createOpen}
          onOpenChange={setCreateOpen}
        />
      )}

      {/* Edit dialog */}
      <EditVariantDialog
        variant={editVariant}
        productName={selectedProduct?.name ?? ""}
        brand={productData?.brand}
        open={editVariant !== null}
        onOpenChange={(open) => { if (!open) setEditVariant(null) }}
      />
    </main>
  )
}
