import InputGroup from "@/components/auth/InputGroup";
import AppText from "@/components/ui/app-text";
import Button from "@/components/ui/Button";
import DynamicFormFields from "@/components/ui/DynamicFormFields";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { useCurrency } from "@/hooks/useCurrency";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { WithdrawMethodTypes } from "@/types/withdraw";
import { showToast } from "@/utils/toast";
import { useQueryClient } from "@tanstack/react-query";
import { router } from "expo-router";
import { CheckCircleIcon, InfoIcon, ReceiptIcon, WalletIcon } from "phosphor-react-native";
import { useMemo, useState } from "react";
import { Controller, useForm, useWatch } from "react-hook-form";
import { Pressable, Text, View } from "react-native";

type FormTypes = {
  withdraw_method_id: number | null;
  amount: string;
  user_data: Record<string, any>;
};

export default function WithdrawForm() {
  const queryClient = useQueryClient();
  const { tran, translateNumber } = useTranslations();
  const { primary } = useColor();

  const [selectedMethod, setSelectedMethod] = useState<WithdrawMethodTypes | any>(null);

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<FormTypes>({
    defaultValues: {
      withdraw_method_id: null,
      amount: "",
      user_data: {},
    },
  });

  const amountValue = useWatch({
    control,
    name: "amount",
    defaultValue: "",
  });

  const { data: methodsData } = useGetQuery({
    url: "/client/withdraw-methods",
  });
  const methods = Array.isArray(methodsData) ? methodsData : [];

  const {
    mutate,
    isLoading: isSubmitting,
    backendErrors,
  } = useQueryMutation({
    url: "/client/withdraws",
  });

  const user = useAuthStore((s) => s.user);
  const { currency: siteCurrency } = useCurrency();

  // Sort fields once for rendering
  const sortedFields = useMemo(() => {
    if (!selectedMethod?.fields) return [];
    return [...selectedMethod.fields].sort((a: any, b: any) => a.position - b.position);
  }, [selectedMethod]);

  const withdrawalSummary = useMemo(() => {
    const amt = Number(amountValue) || 0;
    const pCharge = Number(selectedMethod?.percent_charge) || 0;
    const fCharge = Number(selectedMethod?.fixed_charge) || 0;
    const percentageAmt = (amt * pCharge) / 100;
    const totalCharge = percentageAmt + fCharge;
    const receive = Math.max(0, amt - totalCharge);

    return {
      charge: totalCharge,
      receive,
      fixed: fCharge,
      percent: percentageAmt,
    };
  }, [amountValue, selectedMethod]);

  const onSubmit = handleSubmit((data) => {
    console.log("📝 Raw form data:", JSON.stringify(data));

    const num = Number(data.amount);

    if (num > (user?.balance || 0)) {
      showToast({
        type: "error",
        text: tran("Insufficient balance"),
      });
      return;
    }

    // Build fields array exactly like the web frontend does
    const fields = (selectedMethod?.fields || []).map((field: any) => ({
      name: field.name,
      type: field.type,
      value: data.user_data?.[field.name] || "",
    }));

    const formattedData = {
      method: selectedMethod?.slug,
      amount: num,
      currency: selectedMethod?.currency || siteCurrency.code,
      fields,
    };

    console.log("📤 Final payload:", JSON.stringify(formattedData));

    mutate(formattedData, {
      onSuccess: () => {
        setSelectedMethod(null);
        queryClient.invalidateQueries({
          predicate: (query) => query.queryKey.some((key) => typeof key === "string" && key.includes("/client/withdraws")),
        });
        showToast({
          type: "success",
          text: tran("Withdrawal request submitted successfully"),
        });
        router.push("/(screens)/wallet/withdraw");
      },
      onError: (error: any) => {
        console.log(error);
        showToast({
          type: "error",
          text: tran(error?.response?.data?.message || "Something went wrong"),
        });
      },
    });
  });

  return (
    <View>
      <View className="flex-col gap-y-4">
        <Controller
          control={control}
          name="withdraw_method_id"
          rules={{ required: tran("Please select a withdrawal method") }}
          render={({ field: { onChange, value } }) => (
            <View>
              <AppText size="lg" className="font-manrope-bold pb-4">
                {tran("Select Method")}
              </AppText>

              <View className="flex-row flex-wrap gap-4">
                {methods?.map((method: WithdrawMethodTypes) => {
                  const isSelected = value === method.id;

                  return (
                    <Pressable
                      key={method.slug}
                      onPress={() => {
                        setSelectedMethod(method);
                        onChange(method.id);
                      }}
                      className="w-[47%] p-5 rounded-[28px] border-2 items-center justify-center transition-all bg-white"
                      style={{
                        borderColor: isSelected ? primary.base : "#f1f5f9",
                        elevation: isSelected ? 4 : 0,
                        shadowColor: primary.base,
                        shadowOffset: { width: 0, height: 4 },
                        shadowOpacity: isSelected ? 0.1 : 0,
                        shadowRadius: 12,
                      }}
                    >
                      <View className="size-14 rounded-2xl items-center justify-center mb-3 bg-slate-50 border border-slate-100/50">
                        {<WalletIcon size={32} color={primary.base} weight="duotone" />}
                      </View>
                      <Text className={`font-manrope-bold text-center text-[15px] ${isSelected ? "text-slate-900" : "text-slate-600"}`} numberOfLines={1}>
                        {method.name}
                      </Text>
                      {isSelected && (
                        <View className="absolute top-3 right-3">
                          <CheckCircleIcon size={24} color={primary.base} weight="fill" />
                        </View>
                      )}
                    </Pressable>
                  );
                })}
              </View>

              {errors.withdraw_method_id && <Text className="text-red-500 mt-1">{errors.withdraw_method_id.message}</Text>}
            </View>
          )}
        />
      </View>

      {selectedMethod && (
        <View className="pt-12 gap-y-6">
          <View className="flex-row justify-between items-center">
            <AppText size="lg" className="font-manrope-bold">
              {tran("Withdraw Details")}
            </AppText>
            <View className="flex-row items-center gap-1.5 bg-slate-50 px-3 py-1.5 rounded-full border border-slate-100">
              <WalletIcon size={14} color={primary.base} weight="fill" />
              <Text className="text-xs font-manrope-bold text-slate-600">
                {siteCurrency.symbol}
                {translateNumber(user?.balance || 0)}
              </Text>
            </View>
          </View>

          <View>
            <InputGroup control={control} label={tran("Amount to withdraw")} name="amount" error={errors.amount} backendError={backendErrors?.amount} keyboardType="numeric" />
            {Number(amountValue) > (user?.balance || 0) && <Text className="text-red-500 text-xs mt-1 font-manrope-semibold">{tran("Insufficient balance")}</Text>}
          </View>

          {/* Dynamic Fields — rendered directly in JSX, NOT inside useMemo */}
          {sortedFields.map((field: any, idx: number) => (
            <Controller
              key={`${selectedMethod.slug}-${field.name}-${idx}`}
              control={control}
              name={`user_data.${field.name}`}
              rules={{
                required: field.is_required === "1" || field.required ? `${field.label || field.name} is required` : false,
              }}
              render={({ field: { onChange, value } }) => (
                <DynamicFormFields
                  id={field.name}
                  label={field.label || field.name}
                  type={field.field_type || field.type || "text"}
                  required={field.is_required === "1" || field.required}
                  options={field.options}
                  value={value}
                  onChange={onChange}
                  validationError={backendErrors?.[`fields.${idx}.value`]}
                />
              )}
            />
          ))}

          {/* Summary Card */}
          <View className="bg-white p-7 rounded-[40px] border border-slate-100 shadow-sm mt-6">
            <View className="flex-row items-center gap-x-2.5 mb-6">
              <View className="size-10 rounded-xl bg-slate-50 items-center justify-center">
                <ReceiptIcon size={20} color={primary.base} weight="duotone" />
              </View>
              <Text className="text-lg font-manrope-bold text-slate-800">{tran("Transaction Summary")}</Text>
            </View>

            <View className="gap-y-4">
              <View className="flex-row justify-between items-center">
                <Text className="text-slate-500 font-manrope-semibold text-[13px] uppercase tracking-wider">{tran("Requested")}</Text>
                <Text className="text-slate-900 font-manrope-bold text-base">
                  {siteCurrency.symbol}
                  {translateNumber(Number(amountValue || 0))}
                </Text>
              </View>

              <View className="flex-row justify-between items-center">
                <Text className="text-slate-500 font-manrope-semibold text-[13px] uppercase tracking-wider">{tran("Fixed Fee")}</Text>
                <Text className="text-red-500 font-manrope-bold">
                  - {siteCurrency.symbol}
                  {translateNumber(withdrawalSummary.fixed)}
                </Text>
              </View>

              <View className="flex-row justify-between items-center">
                <Text className="text-slate-500 font-manrope-semibold text-[13px] uppercase tracking-wider">
                  {tran("System Fee")} ({selectedMethod.percent_charge}%)
                </Text>
                <Text className="text-red-500 font-manrope-bold">
                  - {siteCurrency.symbol}
                  {translateNumber(withdrawalSummary.percent)}
                </Text>
              </View>

              <View className="mt-4 pt-5 border-t border-slate-100 flex-row justify-between items-center">
                <View>
                  <Text className="text-slate-900 font-manrope-extrabold text-base">{tran("Net Amount")}</Text>
                  <Text className="text-slate-400 font-manrope-medium text-[11px]">{tran("Estimated payout")}</Text>
                </View>
                <Text className="text-slate-900 font-manrope-extrabold text-2xl" style={{ color: primary.base }}>
                  {siteCurrency.symbol}
                  {translateNumber(withdrawalSummary.receive)}
                </Text>
              </View>

              <View className="mt-3 flex-row items-center gap-x-2 bg-slate-50 p-3 rounded-2xl">
                <InfoIcon size={14} color="#94a3b8" />
                <Text className="text-[10px] text-slate-500 font-manrope-bold uppercase tracking-tight">
                  {tran("Limits")}: {selectedMethod.min} - {selectedMethod.max} {siteCurrency.code}
                </Text>
              </View>
            </View>
          </View>
        </View>
      )}

      <View className="pt-8">
        <Button onPress={onSubmit} text={tran("Submit Withdrawal")} disabled={isSubmitting} isLoading={isSubmitting} />
      </View>
    </View>
  );
}
