"use client";

import { sendpayout } from "@/pages/payout-request/lib/api";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { Input } from "@/shared/ui/input";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";

export default function WithdrawRequestForm() {
  const [amount, setAmount] = useState("");

  const mutation = useMutation({
    mutationFn: async ({ body }: { body: { amount: number } }) => {
      return sendpayout({ body });
    },
    onSuccess: () => {
      toast.success("So‘rov muvaffaqiyatli yuborildi!");
      setAmount("");
    },
    onError: () => {
      toast.error("So‘rov yuborishda xatolik yuz berdi!");
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    // Amount bo'sh bo'lmasligi va raqam ekanligini tekshirish
    const numericAmount = Number(amount);
    if (!numericAmount || numericAmount <= 0) {
      toast.error("Iltimos, miqdorni to‘g‘ri kiriting!");
      return;
    }

    mutation.mutate({ body: { amount: numericAmount } });
  };

  return (
    <Card className="max-w-md mx-auto mt-10 bg-gray-900 border-gray-800 text-white">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">
          Pul olish so‘rovi
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-2">
              Miqdorni kiriting (so‘m)
            </label>
            <Input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              placeholder="Masalan: 100000"
              className="bg-gray-800 border-gray-700 text-white"
            />
          </div>

          <Button
            type="submit"
            className="w-full bg-blue-600 hover:bg-blue-700"
            disabled={!amount || mutation.isPending}
          >
            {mutation.isPending ? "Yuborilmoqda..." : "So‘rov yuborish"}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
