"use client";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import postData from "@/api/post-data";
import { Button } from "@/components/ui/button";
import { useCurrency } from "@/stores/currency-state";
import { getToken } from "@/actions/cookies";
import SubmitButton from "../../shared/SubmitButton";

// Form validation schema using Zod

export default function CreateWithdrawing({ token, limit }) {
  const { rate, currencyShortname } = useCurrency();
  const t = useTranslations("withdrawForm");

  // Updated form validation schema using Zod
  const formSchema = z.object({
    amount: z.preprocess(
      (val) => (val ? parseFloat(val) : undefined),
      z
        .number({ required_error: t("required") })
        .min(
          parseInt(limit),
          t("limit") +
            " " +
            (Number(limit) * rate).toFixed(2) +
            " " +
            currencyShortname
        )
    ),
    // currency: z
    //   .string({ required_error: "العملة مطلوبة" })
    //   .min(1, "يجب إدخال العملة"),
    details: z
      .string({ required_error: t("required") })
      .min(5, t("detailsMin")),
  });
  // Initialize the form with React Hook Form and Zod resolver
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      amount: "",
      currency: "",
      details: "",
    },
  });
  const {
    formState: { isSubmitting },
  } = form;
  // Form submission handler
  const onSubmit = async (values) => {
    const formData = new FormData();
    formData.append("amount", values.amount);
    formData.append("currency", currencyShortname);
    formData.append("details", values.details);

    if (token) {
      try {
        const response = await postData({
          endPoint: "/user/withdraw/requests",
          body: formData,
          token,
        }); // Replace with your API endpoint
        if (!response.error && response.status == "success") {
          toastSuccess(t("success"));
          form.reset();
        } else {
          throw new Error(response?.data[0] || "حدث خطأ في الارسال");
        }
      } catch (error) {
        toastError(error.message || t("failed"));
      }
    }
  };

  return (
    <div className=" w-full">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          {/* Amount Field */}
          <FormField
            control={form.control}
            name="amount"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Input
                    type="number"
                    placeholder={t("amountPlaceholder")}
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {/* Details Field */}
          <FormField
            control={form.control}
            name="details"
            render={({ field }) => (
              <FormItem>
                <FormControl>
                  <Textarea
                    type="text"
                    placeholder={t("detailsPlaceholder")}
                    {...field}
                    className="focus-visible:ring-main"
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* Submit Button */}
          <SubmitButton text={t("btn")} loading={isSubmitting} isIcon={false} />
        </form>
      </Form>
    </div>
  );
}
