import { useState } from 'react'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import TextField from '@mui/material/TextField'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { patchAdminOrderDeliveryFee } from '@/entities/order/api/admin-order-api'
import { invalidateQueryKeys } from '@/shared/lib/invalidate-query-keys'

export function DeliveryFeeAdjustmentForm({
  orderId,
  deliveryFeeCents,
}: {
  orderId: string
  deliveryFeeCents: number
}) {
  const qc = useQueryClient()
  const [rub, setRub] = useState(() => String(deliveryFeeCents / 100))
  const feeMut = useMutation({
    mutationFn: () => patchAdminOrderDeliveryFee(orderId, Math.round(Number.parseFloat(rub) * 100)),
    onSuccess: async () => {
      await invalidateQueryKeys(qc, [
        ['admin', 'orders'],
        ['admin', 'orders', 'detail'],
        ['admin', 'orders', 'summary'],
      ])
    },
  })

  return (
    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'flex-end' } }}>
      <TextField
        size="small"
        label="Доставка, ₽"
        type="number"
        value={rub}
        onChange={(e) => setRub(e.target.value)}
        slotProps={{ htmlInput: { min: 0, step: 1 } }}
        sx={{ width: { xs: '100%', sm: 200 } }}
      />
      <Button
        variant="contained"
        disabled={
          feeMut.isPending ||
          !rub.trim() ||
          !Number.isFinite(Number.parseFloat(rub)) ||
          Number.parseFloat(rub) < 0 ||
          !Number.isInteger(Number.parseFloat(rub))
        }
        onClick={() => feeMut.mutate()}
      >
        Утвердить доставку и открыть оплату
      </Button>
    </Stack>
  )
}
