import { useFieldArray, type Control, type UseFormRegister } from 'react-hook-form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';

interface AttributeSchemaBuilderProps {
  control: Control<any>;
  register: UseFormRegister<any>;
}

export function AttributeSchemaBuilder({ control, register }: AttributeSchemaBuilderProps) {
  const { fields, append, remove } = useFieldArray({
    control,
    name: 'attributes',
  });

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium"></h3>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={() => append({ key: '', type: 'STRING', required: false })}
        >
          <Plus className="w-4 h-4 mr-2" /> Add Attribute
        </Button>
      </div>

      {fields.length === 0 && (
        <p className="text-sm text-gray-500">No attributes defined. Payload will be empty.</p>
      )}

      <div className="space-y-3">
        {fields.map((field, index) => (
          <div key={field.id} className="flex items-center gap-3 bg-gray-50 p-3 rounded-md border">
            <div className="flex-1">
              <Input
                placeholder="Attribute Key (e.g. userId)"
                {...register(`attributes.${index}.key` as const, { required: true })}
              />
            </div>
            <div className="w-40">
              <select
                className="w-full h-10 px-3 py-2 border rounded-md bg-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                {...register(`attributes.${index}.type` as const)}
              >
                <option value="STRING">String</option>
                <option value="NUMBER">Number</option>
                <option value="BOOLEAN">Boolean</option>
                <option value="DATETIME">DateTime</option>
              </select>
            </div>
            <div className="flex items-center gap-2 w-24">
              <input
                type="checkbox"
                id={`req-${field.id}`}
                className="w-4 h-4"
                {...register(`attributes.${index}.required` as const)}
              />
              <label htmlFor={`req-${field.id}`} className="text-sm">Required</label>
            </div>
            <Button
              type="button"
              variant="destructive"
              size="icon"
              onClick={() => remove(index)}
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
}
