'use client';

import get from 'lodash-es/get';
import { ModelTypes } from '@/zeus/index.js';
import { TailwindPlayCommonParams } from '@/TailwindPlay/Fields/types.js';
import { useState } from 'react';

export const FieldButton: React.FC<
  Omit<TailwindPlayCommonParams, 'setState'> & {
    value?: string;
    onChange?: (key: string, value: string) => void;
  }
> = ({ f, prefix = '', index, ...commonParams }) => {
  const { modelData, state, attributes, onSubmit } = commonParams;
  const [isSubmitting, setIsSubmitting] = useState(false);
  const key = `${prefix}${f.name}${typeof index === 'number' ? `[${index}]` : ''}`;
  const v = get(modelData, key) as ModelTypes['ButtonField'] | undefined;
  const dataFieldName = key.replace(/\[\d+\]/g, '').replace(/^\./, '');
  const renderAttrs = (get(attributes, key) as { className?: string; component?: string } | undefined) || f.visual;
  const type = (v?.type as 'submit' | 'button') || 'button';
  const isSubmitButton = type === 'submit';
  const handleClick = async () => {
    // Emit __clicked__ for all button types to enable state changes via rules
    if (commonParams.onChange) {
      commonParams.onChange(key, '__clicked__');
    }

    // Handle submit action if this is a submit button
    if (isSubmitButton && onSubmit) {
      try {
        setIsSubmitting(true);
        await onSubmit(state, prefix);
      } catch (error) {
        console.error('Submission failed:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  return (
    <button
      type={type}
      className={renderAttrs?.className || ''}
      disabled={isSubmitting}
      onClick={handleClick}
      data-field-name={dataFieldName}
    >
      {isSubmitting ? v?.loadingLabel : v?.label}
    </button>
  );
};
