import { InputHTMLAttributes, useEffect, useState } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { DynamicFieldConfig } from '@/types/dynamic-field-config';
import InputError from '@/components/ui/input-error';
import { FormField } from '@/components/ui/form';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
interface DynamicFieldProps {
value: string | number | boolean | string[] | undefined;
onChange: (value: string | number | boolean | string[]) => void;
config: DynamicFieldConfig;
error?: string;
}
export default function DynamicField({ value, onChange, config, error }: DynamicFieldProps) {
const defaultLabel = config.name.replaceAll('_', ' ');
const label = config?.label || defaultLabel;
const [initialValue, setInitialValue] = useState(false);
if (!value) {
value = config?.default || '';
}
useEffect(() => {
if (!initialValue) {
if (config.type === 'checkbox') {
onChange((value as boolean) || false);
} else {
onChange(value);
}
setInitialValue(true);
}
}, [initialValue, setInitialValue, onChange, value, config]);
// Handle alert
if (config?.type === 'alert') {
return (
{config.label}
{config.description}
);
}
// Handle checkbox
if (config?.type === 'checkbox') {
return (
{config.description &&
{config.description}
}
);
}
// Handle select
if (config?.type === 'select' && config.options) {
return (
{config.description && {config.description}
}
);
}
// Default to text input
const props: InputHTMLAttributes = {};
if (config?.placeholder) {
props.placeholder = config.placeholder;
}
return (
onChange(e.target.value)}
{...props}
/>
{config.description && {config.description}
}
);
}