'use client'

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import type { PriceRow } from '@/lib/admin-prices'

function Row({ row }: { row: PriceRow }) {
  const t = useTranslations('Admin')
  const [value, setValue] = useState(String(row.price))
  const [busy, setBusy] = useState(false)
  const [saved, setSaved] = useState(false)

  async function save() {
    setBusy(true)
    setSaved(false)
    try {
      const res = await fetch('/api/admin/prices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ service: row.service, value: Number(value) }),
      })
      const data: { success?: boolean } = await res.json()
      if (data.success) {
        setSaved(true)
        setTimeout(() => setSaved(false), 2000)
      }
    } finally {
      setBusy(false)
    }
  }

  return (
    <li className="flex items-center justify-between gap-4 py-3">
      <span className="text-amber-300">{t(`svc_${row.service}`)}</span>
      <div className="flex items-center gap-2">
        <input
          type="number"
          step="0.01"
          min="0"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          className="w-24 rounded border border-amber-900/60 bg-[#2c1e14] px-2 py-1 text-right"
        />
        <button onClick={save} disabled={busy} className="rounded bg-amber-600 px-3 py-1 text-sm font-semibold text-[#1b120b] disabled:opacity-60">
          {t('save')}
        </button>
        {saved && <span className="text-sm text-green-400">{t('saved')}</span>}
      </div>
    </li>
  )
}

export function AdminPricesManager({ prices }: { prices: PriceRow[] }) {
  return (
    <ul className="divide-y divide-amber-900/40">
      {prices.map((row) => (
        <Row key={row.service} row={row} />
      ))}
    </ul>
  )
}
