'use client'

import { useState, useTransition } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { DemoTooltip } from '@/components/shared/demo-tooltip'
import { updateMinQuotaPctAction } from '@/actions/settings'
import { debugProps } from '@/lib/debug'

interface MinQuotaEditorProps {
  currentValue: number
  isDemo: boolean
}

export function MinQuotaEditor({ currentValue, isDemo }: MinQuotaEditorProps) {
  const [value, setValue] = useState(currentValue)
  const [isPending, startTransition] = useTransition()

  function handleSave() {
    startTransition(async () => {
      const result = await updateMinQuotaPctAction(value)
      if ('error' in result) {
        toast.error(result.error as string)
      } else {
        toast.success('Instelling opgeslagen')
      }
    })
  }

  return (
    <div className="space-y-3" {...debugProps('min-quota-editor', 'MinQuotaEditor', 'components/settings/min-quota-editor.tsx')}>
      <div>
        <label htmlFor="min-quota-pct" className="text-sm font-medium text-foreground">
          Minimaal beschikbaar Claude-quota voordat de worker een job oppakt (%)
        </label>
        <p className="text-xs text-muted-foreground mt-0.5">
          Worker slaapt tot quota gereset is wanneer onder deze drempel.
        </p>
      </div>
      <div className="flex items-center gap-3">
        <input
          id="min-quota-pct"
          type="number"
          min={1}
          max={100}
          value={value}
          onChange={e => setValue(Number(e.target.value))}
          disabled={isDemo || isPending}
          className="w-24 rounded border border-border bg-surface-container px-3 py-1.5 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
          data-debug-id="min-quota-editor__input"
        />
        <span className="text-sm text-muted-foreground">%</span>
        <DemoTooltip show={isDemo}>
          <Button onClick={handleSave} disabled={isDemo || isPending} size="sm" data-debug-id="min-quota-editor__save">
            Opslaan
          </Button>
        </DemoTooltip>
      </div>
    </div>
  )
}
