"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 {
  ProductImageCarousel,
  type ProductImage,
} from "../../../components/images/ProductImageCarousel"
import { ImageUploadSection } from "../../../components/images/ImageUploadSection"
import { Skeleton } from "@/components/ui/skeleton"
import { Separator } from "@/components/ui/separator"

interface SelectedProduct {
  _id: string
  name: string
}

export default function ImagesPage() {
  const [selectedProduct, setSelectedProduct] = useState<SelectedProduct | null>(null)
  const [showUpload, setShowUpload] = useState(false)

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

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

  function handleSearchClear() {
    setSelectedProduct(null)
    setShowUpload(false)
  }

  function handleUploadSuccess() {
    setShowUpload(false)
  }

  const images = productData?.images ?? []
  const nextPosition =
    images.length > 0 ? Math.max(...images.map((img) => img.position)) + 1 : 0

  return (
    <main className="flex flex-1 flex-col gap-6 p-4 pt-0">
      <h1 className="text-xl font-semibold">Product images</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>

      {/* Gallery */}
      {selectedProduct && (
        <>
          <Separator />

          <section className="space-y-4">
            <div>
              <h2 className="text-base font-semibold">{selectedProduct.name}</h2>
              <p className="text-sm text-muted-foreground">
                {productData === undefined
                  ? "Loading images…"
                  : `${images.length} image${images.length !== 1 ? "s" : ""}`}
              </p>
            </div>

            {productData === undefined ? (
              <div className="flex gap-4">
                {[0, 1, 2].map((i) => (
                  <Skeleton key={i} className="aspect-square w-32 rounded-md" />
                ))}
              </div>
            ) : (
              <ProductImageCarousel
                images={images as ProductImage[]}
                onAddMore={() => setShowUpload(true)}
              />
            )}
          </section>

          {/* Upload section */}
          {showUpload && productData && (
            <>
              <Separator />
              <section className="max-w-lg space-y-2">
                <h3 className="text-sm font-semibold">Add image</h3>
                <p className="text-xs text-muted-foreground">
                  Select an image. The background will be removed automatically before upload.
                </p>
                <ImageUploadSection
                  productId={selectedProduct._id as Id<"products">}
                  nextPosition={nextPosition}
                  onSuccess={handleUploadSuccess}
                />
              </section>
            </>
          )}
        </>
      )}

      {/* Empty state */}
      {!selectedProduct && (
        <p className="text-sm text-muted-foreground">
          Search for a product above to manage its images.
        </p>
      )}
    </main>
  )
}
