'use client';

import { useState, useEffect } from 'react';
import { useT, useLocale } from '@/lib/i18n/react';
import { captureCaught } from '@/lib/observability';
import { FormField } from '@/components/ui/primitives/FormField';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { BasicRowConfigEditor } from '../_shared/BasicRowConfigEditor';
import type { Config } from './config';

interface CategoryOption {
  id: string;
  slug: string;
  nameHe: string;
  nameEn: string;
}

export function ConfigEditor({
  config,
  onChange,
}: {
  config: Config;
  onChange: (c: Config) => void;
}) {
  const t = useT('page_organizer');
  const { locale } = useLocale();
  const [categories, setCategories] = useState<CategoryOption[]>([]);

  useEffect(() => {
    fetch('/api/admin/categories')
      .then((r) => r.json() as Promise<{ ok: boolean; categories: CategoryOption[] }>)
      .then((data) => {
        if (data.ok) setCategories(data.categories);
      })
      .catch((err) => {
        captureCaught(err, {
          scope: 'page-layout.deal-row-category.ConfigEditor',
          severity: 'warning',
        });
      });
  }, []);

  return (
    <BasicRowConfigEditor
      config={config}
      onChange={onChange}
      extra={
        <FormField label={t('category')} tooltip={t('help_category')}>
          <Select
            value={config.categoryId}
            onValueChange={(id) => {
              const cat = categories.find((c) => c.id === id);
              if (!cat) return;
              onChange({
                ...config,
                categoryId: id,
                categorySlug: cat.slug,
                categoryName: { he: cat.nameHe, en: cat.nameEn },
              });
            }}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {categories.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {locale === 'en' ? c.nameEn : c.nameHe}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </FormField>
      }
    />
  );
}
