'use client'

import { useEffect, useState } from 'react'
import type { VariantAttribute, ProductVariation } from '@/lib/db/queries/getProductDetail'

interface ProductVariantSelectorProps {
  variantAttributes: VariantAttribute[]
  variations: ProductVariation[]
  onChange: (variation: ProductVariation | null, selected: Record<string, string>) => void
}

export default function ProductVariantSelector({ variantAttributes, variations, onChange }: ProductVariantSelectorProps) {
  const [selected, setSelected] = useState<Record<string, string>>(() => variations[0]?.options ?? {})

  useEffect(() => {
    const match =
      variations.find((v) => variantAttributes.every((attr) => v.options[attr.attributeId] === selected[attr.attributeId])) ??
      null
    onChange(match, selected)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected])

  const isOptionAvailable = (attributeId: string, optionId: string) => {
    const trial = { ...selected, [attributeId]: optionId }
    return variations.some(
      (v) => Object.entries(trial).every(([attrId, optId]) => v.options[attrId] === optId) && v.stockQuantity > 0,
    )
  }

  return (
    <div className="space-y-4">
      {variantAttributes.map((attr) => (
        <div key={attr.attributeId}>
          <span className="text-sm font-medium text-dark block mb-2">{attr.name}</span>
          <div className="flex flex-wrap gap-2">
            {attr.options.map((opt) => {
              const isSelected = selected[attr.attributeId] === opt.id
              const available = isOptionAvailable(attr.attributeId, opt.id)
              return (
                <button
                  key={opt.id}
                  type="button"
                  disabled={!available}
                  onClick={() => setSelected((prev) => ({ ...prev, [attr.attributeId]: opt.id }))}
                  className={`px-4 py-2 rounded-lg border text-sm font-medium transition-all ${
                    isSelected
                      ? 'border-primary bg-primary/10 text-primary'
                      : available
                      ? 'border-gray-200 text-dark hover:border-primary'
                      : 'border-gray-100 text-gray-300 cursor-not-allowed line-through'
                  }`}
                >
                  {opt.value}
                </button>
              )
            })}
          </div>
        </div>
      ))}
    </div>
  )
}
