import BackButtonTitle from "@/components/ui/BackButtonTitle";
import Button from "@/components/ui/Button";
import DynamicFormFields from "@/components/ui/DynamicFormFields";
import { API_BASE_URL, ONBOARDING_POSITION, ONBOARDING_STEPS } from "@/configs";
import { storage } from "@/configs/storage";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useAuthHandler } from "@/hooks/useAuthHandler";
import { useColor } from "@/hooks/useColor";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { useTranslations } from "@/providers/TranslationProviders";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { ListChecksIcon, ShieldCheckIcon } from "phosphor-react-native";
import { useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { ActivityIndicator, Pressable, ScrollView, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

type KycFormData = {
  fields: Record<string, any>;
};

export default function KYC() {
  const { primary } = useColor();
  const [currentStep, setCurrentStep] = useState(0);
  const [allStepsData, setAllStepsData] = useState<Record<string, any>>({});

  const { data: kycFields, isLoading: isFieldsLoading } = useGetQuery({
    url: "/client/kyc",
  });

  const { tran } = useTranslations();
  const { user, getUser } = useAuthStore((state) => state);
  const { setKycWaitingStep, redirect } = useAuthHandler();
  const [token, setToken] = useState<string | null>(null);

  const { control, handleSubmit, reset } = useForm<KycFormData>();

  const { mutate, isLoading, backendErrors } = useQueryMutation({
    url: "client/kyc",
    isUpdateMethod: true,
  });

  useEffect(() => {
    (() => setToken(storage.getString("token") ?? null))();
  }, []);

  useEffect(() => {
    (async () => {
      if (token && ONBOARDING_STEPS.waiting.value === storage.getString(ONBOARDING_POSITION) && user?.kyc?.status === "pending") {
        router.push(redirect(user) as any);
      }
    })();
  }, [user, token, redirect]);

  // Reset form when step changes
  useEffect(() => {
    reset({ fields: {} });
  }, [currentStep]);

  // kycFields.fields is an array of steps: [[...step1fields], [...step2fields]]
  const allSteps: any[][] = useMemo(() => {
    return kycFields?.fields || [];
  }, [kycFields]);

  const totalSteps = allSteps.length;

  // Current step's sorted fields
  const currentStepFields = useMemo(() => {
    const stepFields = allSteps[currentStep] || [];
    return stepFields.sort((a: any, b: any) => a.position - b.position);
  }, [allSteps, currentStep]);

  // Build rendered form fields for current step
  const forms = useMemo(() => {
    return currentStepFields.map((form: any) => ({
      ...form,
      field: (
        <Controller
          key={form.id}
          control={control}
          name={`fields.${form.id}`}
          rules={{ required: form.required }}
          render={({ field: { onChange, value } }) => (
            <DynamicFormFields
              id={form.id}
              label={form.label}
              type={form.field_type}
              required={form.required}
              options={form.options}
              value={value}
              onChange={onChange}
              validationError={backendErrors?.fields?.[form.id]}
            />
          )}
        />
      ),
    }));
  }, [currentStepFields, control, backendErrors]);

  const onSubmit = handleSubmit(async (data: KycFormData) => {
    const mergedFields = { ...allStepsData, ...data.fields };

    if (currentStep < totalSteps - 1) {
      setAllStepsData(mergedFields);
      setCurrentStep((prev) => prev + 1);
      reset({ fields: {} }); // reset only AFTER saving
      return;
    }

    const formData = new FormData();

    // Build fields[id] = value structure
    Object.entries(mergedFields).forEach(([key, value]) => {
      if (value && value.uri) {
        // File field
        formData.append(`fields[${key}]`, {
          uri: value.uri.startsWith("file://") ? value.uri : "file://" + value.uri,
          name: value.name || `file_${Date.now()}.jpg`,
          type: value.type || "image/jpeg",
        } as any);
      } else {
        formData.append(`fields[${key}]`, value ?? "");
      }
    });

    try {
      const response = await fetch(`${API_BASE_URL}/client/kyc`, {
        method: "POST",
        headers: {
          Accept: "application/json",
          Authorization: `Bearer ${token}`,
          "mobile-app-key": process.env.EXPO_PUBLIC_MOBILE_APP_KEY || "",
        },
        body: formData,
      });

      const result = await response.json();

      if (response.ok && result.status !== false) {
        showToast({ type: "success", text: "KYC submitted successfully" });
        const updatedUser = await getUser();
        if (updatedUser) {
          setKycWaitingStep();
          router.push("/(tabs)");
        }
      } else {
        showToast({
          type: "error",
          text: result?.message || "Failed to submit KYC",
        });
      }
    } catch (error: any) {
      console.log("❌ Upload error:", error);
      showToast({
        type: "error",
        text: error?.message || "Failed to submit KYC",
      });
    }
  });

  const handleBack = () => {
    if (currentStep > 0) {
      // Restore the saved data for the previous step's fields
      const prevStepFields = allSteps[currentStep - 1] || [];
      const prevFieldValues = prevStepFields.reduce((acc: any, field: any) => {
        if (allStepsData[field.id] !== undefined) {
          acc[field.id] = allStepsData[field.id];
        }
        return acc;
      }, {});
      reset({ fields: prevFieldValues });
      setCurrentStep((prev) => prev - 1);
    } else {
      router.back();
    }
  };

  const isLastStep = currentStep === totalSteps - 1;
  const currentStepMeta = kycFields?.steps?.[currentStep];

  return (
    <SafeAreaView className="flex-1 bg-slate-50">
      <View className="px-5 bg-slate-50 ">
        <BackButtonTitle title={tran("KYC Verification")} />
      </View>

      <ScrollView className="flex-1 px-5 " showsVerticalScrollIndicator={false}>
        {isFieldsLoading ? (
          <View className="flex-1 justify-center items-center py-20">
            <ActivityIndicator size="large" color={primary.base} />
            <Text className="mt-4 font-manrope-medium text-slate-500">{tran("Loading identity fields...")}</Text>
          </View>
        ) : (
          <>
            <View className="mt-6 mb-6 p-6 rounded-3xl" style={{ backgroundColor: primary[10] }}>
              <View className="size-14 rounded-2xl justify-center items-center shadow-sm" style={{ backgroundColor: "white" }}>
                <ShieldCheckIcon size={32} color={primary.base} weight="duotone" />
              </View>
              <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">{currentStepMeta?.name || tran("Verify Identity")}</Text>
              <Text className="text-slate-500 pt-2 text-lg font-manrope-medium leading-relaxed">{tran("Protect your account by completing our secure verification process.")}</Text>

              {/* Step indicator bubbles */}
              {totalSteps > 1 && (
                <View className="flex-row items-center gap-x-2.5 pt-6">
                  {Array.from({ length: totalSteps }).map((_, index) => (
                    <View key={index} className="h-1.5 flex-1 rounded-full overflow-hidden" style={{ backgroundColor: "rgba(255, 255, 255, 0.5)" }}>
                      {index <= currentStep && (
                        <View
                          className="h-full rounded-full"
                          style={{
                            backgroundColor: index === currentStep ? primary.base : primary.base,
                            opacity: index === currentStep ? 1 : 0.4,
                          }}
                        />
                      )}
                    </View>
                  ))}
                </View>
              )}
            </View>

            <View className="bg-white rounded-[32px] p-6 shadow-sm border border-slate-100 mb-8">
              <View className="flex-row items-center gap-x-2.5 mb-6">
                <View className="size-10 rounded-xl justify-center items-center" style={{ backgroundColor: primary[5] }}>
                  <ListChecksIcon size={20} color={primary.base} weight="bold" />
                </View>
                <View>
                  <Text className="text-lg font-manrope-bold text-slate-800">{tran("Verification Details")}</Text>
                  {totalSteps > 1 && (
                    <Text className="text-slate-500 font-manrope-semibold text-xs">
                      {tran("Step")} {currentStep + 1} {tran("of")} {totalSteps}
                    </Text>
                  )}
                </View>
              </View>

              <View className="gap-y-6">
                {forms.map((form: any) => (
                  <View key={form.id}>{form.field}</View>
                ))}
              </View>

              <View className="pt-10">
                <Button onPress={onSubmit} isLoading={isLoading} className="w-full" text={isLastStep ? tran("Submit Verification") : tran("Continue")} />

                {currentStep > 0 && (
                  <Pressable onPress={handleBack} className="mt-4 py-4 justify-center items-center">
                    <Text className="font-manrope-bold text-slate-400">{tran("Go Back")}</Text>
                  </Pressable>
                )}
              </View>
            </View>
          </>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}
