import { useScriptGeneratorStore } from '@/store/scriptGeneratorStore'
import { ScriptParameterField } from './ScriptParameterField'
import type { ScriptParametersSchema, ScriptParameter } from '@/types'

interface Props {
  canGenerate: boolean
}

export function ScriptParameterForm({ canGenerate }: Props) {
  const selectedTemplate = useScriptGeneratorStore(s => s.selectedTemplate)
  const paramValues = useScriptGeneratorStore(s => s.paramValues)
  const formErrors = useScriptGeneratorStore(s => s.formErrors)

  if (!selectedTemplate) return null

  const schema = selectedTemplate.parameters_schema as ScriptParametersSchema
  const parameters = (schema?.parameters ?? []).slice().sort((a, b) => a.order - b.order)

  // Group parameters: null-group first, then named groups in order of first appearance
  const ungrouped = parameters.filter(p => p.group === null)
  const groupOrder: string[] = []
  const grouped: Record<string, ScriptParameter[]> = {}
  for (const p of parameters) {
    if (p.group !== null) {
      if (!grouped[p.group]) {
        grouped[p.group] = []
        groupOrder.push(p.group)
      }
      grouped[p.group].push(p)
    }
  }

  const renderParam = (param: ScriptParameter) => (
    <ScriptParameterField
      key={param.key}
      param={param}
      value={paramValues[param.key] ?? ''}
      error={formErrors[param.key] || undefined}
      disabled={!canGenerate}
    />
  )

  return (
    <div className="flex flex-col gap-4">
      {ungrouped.map(renderParam)}
      {groupOrder.map(group => (
        <div key={group}>
          <p className="font-label text-[0.625rem] uppercase tracking-[0.1em] text-muted-foreground mb-3">
            {group}
          </p>
          <div className="flex flex-col gap-4">
            {grouped[group].map(renderParam)}
          </div>
        </div>
      ))}
    </div>
  )
}
