import { useForm } from '@tanstack/react-form'
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/demo/form/sv')({
  component: RouteComponent,
})

const formFields = [
  {
    fieldName: 'transfer.fee',
    description: 'Transfer Fee',
    currentValue: '0.01',
  },
  {
    fieldName: 'threshold',
    description: 'Threshold',
    currentValue: '20',
  },
]

function RouteComponent() {
  const form = useForm({
    defaultValues: {
      summary: '', // field that always exists
      ...formFields.reduce(
        (acc, field) => {
          acc[field.fieldName] = field.currentValue
          return acc
        },
        {} as Record<string, string>,
      ),
    },
    onSubmit: async ({ value }) => {
      console.log('Form submitted:', value)
      console.log('fee', value['transfer.fee'] as string)
      //  Element implicitly has an 'any' type because expression of type '"transfer.fee"' can't be used to index type '{ summary: string; }'.
      // Property 'transfer.fee' does not exist on type '{ summary: string; }'.
    },
  })

  return (
    <div>
      <form
        onSubmit={(e) => {
          e.preventDefault()
          e.stopPropagation()
          form.handleSubmit()
        }}
      >
        <form.Field
          name="summary"
          children={(field) => (
            <div className="flex flex-row mb-4 space-x-4">
              <label htmlFor={field.name}>Summary</label>
              <input
                id={field.name}
                name={field.name}
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
              />
            </div>
          )}
        />

        {formFields.map((fieldConfig) => (
          <form.Field
            key={fieldConfig.fieldName}
            // Type 'string' is not assignable to type '"summary"'.
            name={fieldConfig.fieldName}
            children={(field) => (
              <div className="flex flex-row mb-4 space-x-4">
                <label htmlFor={field.name}>{fieldConfig.description}</label>
                <input
                  id={field.name}
                  name={field.name}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={(e) => field.handleChange(e.target.value)}
                />
              </div>
            )}
          />
        ))}

        <form.Subscribe
          selector={(state) => [state.canSubmit, state.isSubmitting]}
          children={([canSubmit, isSubmitting]) => (
            <button type="submit" disabled={!canSubmit}>
              {isSubmitting ? '...' : 'Submit'}
            </button>
          )}
        />
      </form>
    </div>
  )
}
