import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { HttpError } from '@/shared/api/client'
import type { PricingSettingsDto } from '@/shared/api/types'
import { updatePricingSettings } from './api'

export function PricingSettingsEditor({ settings }: { settings: PricingSettingsDto }) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [pricePerConfigPerQuarter, setPricePerConfigPerQuarter] = useState(
    settings.pricePerConfigPerQuarter != null ? String(settings.pricePerConfigPerQuarter) : '',
  )
  const [pricePerConfigPerYear, setPricePerConfigPerYear] = useState(
    settings.pricePerConfigPerYear != null ? String(settings.pricePerConfigPerYear) : '',
  )

  const mutation = useMutation({
    mutationFn: () =>
      updatePricingSettings(
        pricePerConfigPerQuarter === '' ? null : Number(pricePerConfigPerQuarter),
        pricePerConfigPerYear === '' ? null : Number(pricePerConfigPerYear),
      ),
    onSuccess: async () => {
      toast.success(t('admin.pricing.updated'))
      await queryClient.invalidateQueries({ queryKey: ['admin-pricing'] })
    },
    onError: (error) => toast.error(error instanceof HttpError ? error.detail : t('auth.genericError')),
  })

  return (
    <form
      className="flex flex-col gap-4"
      onSubmit={(e) => {
        e.preventDefault()
        mutation.mutate()
      }}
    >
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="pricePerConfigPerQuarter">{t('admin.pricing.pricePerConfigPerQuarter')}</Label>
        <Input
          id="pricePerConfigPerQuarter"
          type="number"
          min={0}
          value={pricePerConfigPerQuarter}
          onChange={(e) => setPricePerConfigPerQuarter(e.target.value)}
        />
        <p className="text-xs text-muted-foreground">{t('admin.pricing.pricePerConfigPerQuarterHint')}</p>
      </div>
      <div className="flex flex-col gap-1.5">
        <Label htmlFor="pricePerConfigPerYear">{t('admin.pricing.pricePerConfigPerYear')}</Label>
        <Input
          id="pricePerConfigPerYear"
          type="number"
          min={0}
          value={pricePerConfigPerYear}
          onChange={(e) => setPricePerConfigPerYear(e.target.value)}
        />
        <p className="text-xs text-muted-foreground">{t('admin.pricing.pricePerConfigPerYearHint')}</p>
      </div>
      <div>
        <Button type="submit" disabled={mutation.isPending}>
          {t('admin.roles.save')}
        </Button>
      </div>
    </form>
  )
}
