'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 (
    <tr className="team-center-table-tr">
      <td className="lefted separate">
        <span className="yellow-info">{t(`svc_${row.service}`)}</span>
      </td>
      <td className="real-info-box no-wrap-td">
        <input
          type="number"
          step="0.01"
          min="0"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          style={{ width: 90, textAlign: 'right' }}
        />{' '}
        <button onClick={save} disabled={busy} className="ns-tool-btn">
          {t('save')}
        </button>{' '}
        {saved && <span className="green-info small-font">{t('saved')}</span>}
      </td>
    </tr>
  )
}

export function AdminPricesManager({ prices }: { prices: PriceRow[] }) {
  return (
    <table className="max-center-table">
      <tbody>
        {prices.map((row) => (
          <Row key={row.service} row={row} />
        ))}
      </tbody>
    </table>
  )
}
