"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { BsArrowRight } from "react-icons/bs";
import { FaSpinner } from "react-icons/fa6";
import { z } from "zod";

export default function CreditCharge({ setShowModal }) {
  const locale = useLocale(); // Retrieve the current locale
  const t = useTranslations();
  const user = useTranslations("user");
  const e = useTranslations("form-errors");
  const [bankTransfer, setBankTransfer] = useState(false); // State to handle bank transfer option display
  const [isPostLoading, setIsPostLoading] = useState(false); // State to handle bank transfer option display

  // Initialize react-hook-form with Zod validation schema
  const {
    register,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(
      z.object({
        amount: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1), // amount field is required
        method: z
          .string({ errorMap: () => ({ message: e("required") }) })
          .min(1), // method field is required
        bank_sender_name: z.string().min(3, e("at-least3")).optional(), // Optional field for sender's name
        bank_transactions_num: z.string().min(3, e("at-least3")).optional(), // Optional field for bank transfer number
      })
    ), // Apply Zod schema for validation
  });

  // Fetch available payment methods using react-query
  const { data, isLoading, error } = useQuery({
    queryKey: ["paymentmethods", locale], // Unique key for caching
    queryFn: async () => {
      return fetchData({
        endPoint: "/user/balance/payment-methods",
        locale,
      }); // API call to fetch payment methods
    },
  });

  const handleSelectChange = (value) => {
    setBankTransfer(value === "17"); // Show additional fields if payment method is '17'
    setValue("method", value); // Update form value for payment method
  };

  const onSubmit = async (values) => {
    setIsPostLoading(true);
    // Create a FormData object with the form values
    const formData = new FormData();
    formData.append("amount", values.amount);
    formData.append("method", values.method);
    if (values.method == "17") {
      formData.append("bank_sender_name", values.bank_sender_name || ""); // optional field
      formData.append(
        "bank_transactions_num",
        values.bank_transactions_num || ""
      ); // optional field
    }
    // Post form data to API endpoint
    const res = await postData({
      endPoint: "/user/balance/recharge",
      locale,
      body: formData,
    });
    // Check if the response is successful
    if (res.error) {
      setIsPostLoading(false);
      toastError(res?.message);
    }

    // Parse and log the JSON response
    if (res.status == "success") {
      setIsPostLoading(false);
      toastSuccess(res.message);
      setShowModal(false);
      if (res?.data?.payment_url) {
        window.location.href = `${res?.data?.payment_url}`;
      }
    } else {
      setIsPostLoading(false);
      toastError(res.message);
      toastError(res.data);
    }
    setIsPostLoading(false);
  };

  // Render error message if query fails
  if (error) return <p>{error.message || t("error-message")}</p>;
  if (data?.error) toastError(data?.message);
  if (isLoading) {
    return <div className="flex items-center justify-center w-full h-[40vh]">
      <div className="loader"></div>
    </div>
  }

  return (
    // Render form with inputs
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 p-6">
      {/* Input field for amount */}
      <div className="mb-4">
        <input
          type="text"
          className="btn-outline-black"
          placeholder={user("amount")}
          {...register("amount")} // Register input with react-hook-form
        />
        {errors.amount && (
          <p className="text-red-500">{errors.amount.message}</p>
        )}{" "}
        {/* Display error if amount is invalid */}
      </div>

      <div className="">
        {/* Select dropdown for payment methods */}
        <Select
          className="btn-outline-black border-black"
          dir={locale == "en" ? "ltr" : "rtl"}
          onValueChange={handleSelectChange}
        >
          <SelectTrigger className="h-8 md:h-10 lg:h-12 btn-outline-black border-black focus:ring-main">
            <SelectValue
              className="placeholder:text-secondary btn-outline-black"
              placeholder={user("visa")}
            />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              {data?.data ? (
                Object.entries(data?.data).map(([key, value], index) => (
                  <SelectItem key={index} value={key}>
                    {value}
                  </SelectItem> // Map through payment methods and render them as SelectItems
                ))
              ) : (
                <FaSpinner className="animate-spin m-2" />
              )}
            </SelectGroup>
          </SelectContent>
        </Select>
        {errors.method && (
          <p className="text-red-500">{errors.method.message}</p>
        )}{" "}
      </div>

      {/* Conditional rendering for additional fields based on bankTransfeer state */}
      {bankTransfer && (
        <div>
          {/* Input for sender name, shown only if bank transfer method is selected */}
          <input
            type="text"
            className="btn-outline-black "
            placeholder={user("sendername")}
            {...register("bank_sender_name")}
          />
          {errors.bank_sender_name && (
            <p className="text-red-500 mb-2">
              {errors.bank_sender_name.message}
            </p>
          )}{" "}
          {/* Display error if payment method is invalid */}
          {/* Input for bank transfer number, shown only if bank transfer method is selected */}
          <input
            type="text"
            className="btn-outline-black "
            placeholder={user("banktransfernum")}
            {...register("bank_transactions_num")}
          />
          {errors.bank_transactions_num && (
            <p className="text-red-500 mb-2">
              {errors.bank_transactions_num.message}
            </p>
          )}{" "}
          {/* Display error if payment method is invalid */}
        </div>
      )}

      {/* Submit button */}
      <div className="flex justify-start">
        {isPostLoading ? (
          <button
            disabled
            className="bg-main opacity-75 w-32 h-10 gap-x-1 flex m-auto items-center justify-center text-white rounded-sm text-sm p-2"
          >
            <FaSpinner className="animate-spin" />
          </button>
        ) : (
          <button
            type="submit"
            className="btn-main w-32 h-10 gap-x-1 flex m-auto justify-center items-center text-white rounded-sm text-sm p-2"
          >
            <BsArrowRight />
            {user("sendreq")}
          </button>
        )}
      </div>
    </form>
  );
}
