import * as React from 'react'
import { SettingsForm } from '../components/SettingsForm'
import {Config, defaultConfig, NATURAL_KEY_WIDTHS, RANGES, SCALE_FACTORS} from '../../../common/config'
import { useMidi } from '../hooks/midi'
import { useForm } from '../hooks/form'

interface SettingsPageProps {
  params: URLSearchParams
}

const SettingsPage: React.FC<SettingsPageProps> = ({ params }) => {
  const { handleAction } = useForm()
  const { midiAccess, lastStateChangeTimestamp } = useMidi()

  const defaultValues = Object.entries(defaultConfig).reduce(
    (theConfig, [key, value]) => ({
      ...theConfig,
      [key]: params.get(key) || value
    }),
    {} as Config
  )

  return (
    <main className="py-16 select-none">
      <div className="px-4 mx-auto max-w-screen-sm">
        <h1 className="text-5xl mb-8">
          Settings
        </h1>
        <SettingsForm
          lastStateChangeTimestamp={lastStateChangeTimestamp}
          midiAccess={midiAccess}
          defaultValues={defaultValues}
          ranges={RANGES}
          scaleFactors={SCALE_FACTORS}
          naturalKeyWidths={NATURAL_KEY_WIDTHS}
          onSubmit={handleAction}
        />
      </div>
    </main>
  )
}

export default SettingsPage
