import React from 'react';
import { Label } from '@/components/ui/label';
import { SearchableSelect } from '@/components/ui/searchable-select';
import { ProductsApi } from '@/lib/api/products';

export default function RepeaterProductField({
  label,
  value,
  onChange,
}: {
  label: string;
  value: string;
  onChange: (fieldName: string, nextValue: any) => void;
}) {
  const [search, setSearch] = React.useState('');
  const [options, setOptions] = React.useState<any[]>([]);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;

    async function run() {
      const q = search.trim();
      if (q.length < 2) {
        setOptions([]);
        return;
      }

      setLoading(true);
      try {
        const res = await ProductsApi.search(q, 10);
        const rows = (res as any)?.rows ?? (res as any)?.data ?? (res as any)?.items ?? [];
        const mapped = (Array.isArray(rows) ? rows : []).map((p: any) => {
          const productSlug =
            p.slug || p.product_slug || p.permalink_slug || p.slug?.toString?.() || '';

          const name = p.name || 'Product';
          const skuSuffix = p.sku ? ` (${p.sku})` : '';
          const labelStr = `${name}${skuSuffix}`;
          const triggerLabel = productSlug ? `${name} /${productSlug}` : name;

          return {
            value: String(productSlug || p.id),
            searchText: `${name} ${p.sku ?? ''} ${productSlug ?? ''}`.trim(),
            label: labelStr,
            triggerLabel,
            product: {
              ...p,
              product_slug: productSlug || p.product_slug || '',
              id: p.id,
              price: p.price ?? p.sale_price ?? p.regular_price ?? null,
              image_url: p.image_url ?? p.image ?? p.thumbnail_url ?? '',
            },
          };
        });

        if (!cancelled) setOptions(mapped);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    run();
    return () => {
      cancelled = true;
    };
  }, [search]);

  const selectedOption = options.find((o) => o.value === (value || ''));

  return (
    <div className="space-y-1.5">
      <Label className="text-xs text-gray-500">{label}</Label>
      <SearchableSelect
        value={selectedOption?.value || (value || '')}
        onChange={(v) => {
          const selected = options.find((o) => o.value === v)?.product;
          if (!selected) return;

          onChange('product_slug', selected.product_slug || '');
          onChange('product_name', selected.name || '');
          onChange('product_price', selected.sale_price ?? selected.price ?? '');
          onChange('product_image', selected.image_url ?? '');
          onChange('product_id', selected.id ? Number(selected.id) : 0);
        }}
        options={options.map((o) => ({
          value: String(o.value ?? ''),
          label: o.label,
          triggerLabel: o.triggerLabel,
          searchText: String(o.searchText ?? ''),
        }))}
        placeholder={loading ? 'Searching…' : 'Search product…'}
        emptyLabel={loading ? 'Searching…' : 'No products found'}
        search={search}
        onSearch={setSearch}
        showCheckIndicator={false}
      />
    </div>
  );
}
