'use client';

import { ReactNode } from 'react';
import { useFormContext } from 'react-hook-form';
import { FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { KeyValueRepeater } from '../common/KeyValueRepeater';

interface FormKeyValueRepeaterProps {
  name: string;
  label?: string;
  description?: string;
  availableKeys?: { label: ReactNode; value: string }[];
  keyPlaceholder?: string;
  valuePlaceholder?: string;
  className?: string;
  isSecret?: boolean;
  defaultValue?: { key: string; value: string }[];
}

export function FormKeyValueRepeater({
  name,
  label,
  description,
  availableKeys,
  keyPlaceholder,
  valuePlaceholder,
  className,
  isSecret,
  defaultValue,
}: FormKeyValueRepeaterProps) {
  const form = useFormContext();

  return (
    <FormField
      control={form.control}
      name={name}
      render={({ field }) => (
        <FormItem className={className}>
          {label && <FormLabel>{label}</FormLabel>}
          <FormControl>
            <KeyValueRepeater
              availableKeys={availableKeys}
              initialPairs={field.value || defaultValue}
              onChange={field.onChange}
              keyPlaceholder={keyPlaceholder}
              valuePlaceholder={valuePlaceholder}
              isSecret={isSecret}
            />
          </FormControl>
          {description && <FormDescription>{description}</FormDescription>}
          <FormMessage />
        </FormItem>
      )}
    />
  );
}
