/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import React, { useEffect, useState } from "react";
import SettingsLayout from "../../components/settings/SettingsLayout";
import { ProfileSection } from "../../components/settings/ProfileSection";
import { PasswordSection } from "../../components/settings/PasswordSection";
import { WithdrawSection } from "../../components/settings/WithdrawSection";
import { useAuth } from "../../context/AuthContext";
import { fetchProfileData, updateProfileData, setNewPassword, fetchBankDetails, setAuthToken, withdrawToBank, fetchBankList, addBankDetails } from "../../lib/api/api";
import Loader from "../../components/loader";
import { getUserFriendlyError } from "../../lib/utils/helpers";
import { AddBankSection } from "../../components/settings/AddBankSection";

export default function SettingsPage() {
  const { token, user }: { token: string | null; user?: any } = useAuth(); 

  setAuthToken(token);
  const [loading, setLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [success, isSuccess] = useState(false);
  const [message, setMessage] = useState("");
  const [bankDetails, setBankDetails] = useState<{
    bankName: string;
    accountNumber: string;
    accountName: string;
  } | null>(null);  

  const [passwords, setPasswords] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });

  const [initialValues, setInitialValues] = useState({
    phoneNumber: "",
    emailAddress: "",
    firstName: "",
    lastName: "",
    dateOfBirth: "",
    address: "",
    imageUrl: "",
  });

  useEffect(() => {
    if (!token) return;

    let isMounted = true;
    setLoading(true);

    const profileData = async () => {
      try {
        const res = await fetchProfileData();
        const userData = res.data?.data;

        if (isMounted && userData) {
          setInitialValues({
            phoneNumber: userData.phoneNumber || "",
            emailAddress: userData.emailAddress || "",
            firstName: userData.firstName || "",
            lastName: userData.lastName || "",
            dateOfBirth: userData.dateOfBirth || "",
            address: userData.address || "",
            imageUrl: userData.imageUrl || "",
          });
        }
      } catch (error) {
        console.error("Error fetching profile data:", error);
      } finally {
        if (isMounted) setLoading(false);
      }
    };
    
    const fetchWithdrawalData = async () => {
      try {
        const res = await fetchBankDetails();
        setBankDetails(res.data.data); 

      } catch (error: any) {
        if (error.response && error.response.data && error.response.data.errors && error.response.data.errors.length > 0) {
          console.log('Error fetching bank accounts:', error.response.data.errors[0].message);
        } else {
          console.log('Error fetching bank accounts:', error);
        }
      } finally {
        if (isMounted) setLoading(false);
      }
    };

    profileData();
    fetchWithdrawalData();

    return () => {
      isMounted = false;
    };
  }, [token]);

  const handleProfileChange = (field: keyof typeof initialValues, value: string) => {
    setInitialValues((prev) => ({ ...prev, [field]: value }));
  };

  const handlePasswordChange = (field: keyof typeof passwords, value: string) => {
    setPasswords((prev) => ({ ...prev, [field]: value }));
  };

  const handleProfileUpdate = async () => {
    setLoading(true);
    try {
      const payload = { ...initialValues };
      const response = await updateProfileData(payload);

      if (response.data?.isSuccessful) {
        isSuccess(true);
        setMessage(response.data?.message || "Profile updated successfully!");
      } else {
        const errorMessage = getUserFriendlyError(
          response?.data?.message || "Profile update failed."
        );
        setMessage(errorMessage);
        isSuccess(false);
      }
    } catch (err: any) {
      const userError = getUserFriendlyError(
        err.response?.data?.message || "An error occurred. Please try again."
      );
      setMessage(userError);
      isSuccess(false);
    } finally {
      setLoading(false);
      setModalVisible(true);
    }
  };

  const handlePasswordUpdate = async () => {
    if (
      !passwords.currentPassword.trim() ||
      !passwords.newPassword.trim() ||
      !passwords.confirmPassword.trim()
    ) {
      setMessage("Please fill in all fields.");
      isSuccess(false);
      setModalVisible(true);
      return;
    }

    if (passwords.newPassword !== passwords.confirmPassword) {
      setMessage("New password and confirmation do not match.");
      isSuccess(false);
      setModalVisible(true);
      return;
    }

    const passwordRegex =
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#^()_+])[A-Za-z\d@$!%*?&#^()_+]{8,}$/;

    if (!passwordRegex.test(passwords.newPassword)) {
      setMessage(
        "Password must be at least 8 characters long, contain uppercase, lowercase, number, and a special character."
      );
      isSuccess(false);
      setModalVisible(true);
      return;
    }

    setLoading(true);
    try {
      const payload = {
        OldPassword: passwords.currentPassword,
        newPassword: passwords.newPassword,
        ConfirmNewPassword: passwords.confirmPassword,
      };

      const response = await setNewPassword(payload);

      if (response.data?.isSuccessful) {
        isSuccess(true);
        setMessage(response.data?.message || "Password updated successfully!");
        setPasswords({ currentPassword: "", newPassword: "", confirmPassword: "" });
      } else {
        const errorMessage = getUserFriendlyError(
          response?.data?.message || "Password update failed."
        );
        setMessage(errorMessage);
        isSuccess(false);
      }
    } catch (err: any) {
      const userError = getUserFriendlyError(
        err.response?.data?.message || "An error occurred. Please try again."
      );
      setMessage(userError);
      isSuccess(false);
    } finally {
      setLoading(false);
      setModalVisible(true);
    }
  };

  const handleWithdrawToBank = async (withdrawalData: { amount: string; pin: string; narration: string }) => {
    setLoading(true);
  
    try {
      const cleanAmount = parseFloat(withdrawalData.amount.replace(/[₦,]/g, ""));
      const userId = user?.id || "";
  
      const payload = {
        amount: cleanAmount,
        pin: withdrawalData.pin,
        narration: withdrawalData.narration || "Withdrawal",
      };
  
      const response = await withdrawToBank(userId, payload);
  
      const api = response.data;
  
      if (api?.success) {
        // Success handling
        isSuccess(true);
  
        const successMsg =
          api?.data?.message ||
          api?.message ||
          "Withdrawal successful";
  
        setMessage(successMsg);
      } else {
        const backendMsg =
        api?.errors?.[0] ||
        api?.message ||
        "Withdrawal failed.";   
  
        setMessage(getUserFriendlyError(backendMsg));
        isSuccess(false);
      }
    } catch (err: any) {
      const backendMsg =
      err.response?.data?.errors?.[0] ||
      err.response?.data?.message ||
      err.message;
  
      const userError = getUserFriendlyError(backendMsg);
      setMessage(userError);
      isSuccess(false);
    } finally {
      setLoading(false);
      setModalVisible(true);
    }
  };
  
  const saveBankDetails = async (bankData: {
    bankName: string;
    bankcode: string;
    accountNumber: string;
    accountName: string;
  }) => {
    setLoading(true);
    try {

      const payload = {
        bankName: bankData.bankName,
        bankCode: bankData.bankcode,
        accountNumber: bankData.accountNumber,
        accountName: bankData.accountName,
      };

      const response = await addBankDetails( payload);

      if (response.data?.isSuccessful) {
        isSuccess(true);
        setMessage(response.data?.message || "Bank account added successfully!");
      } else {
        const backendMsg =
          response.data?.errors?.[0]?.message ||
          response.data?.message ||
          "Failed to add bank account.";

        const friendly = getUserFriendlyError(backendMsg);
        setMessage(friendly);
        isSuccess(false);
      }
    } catch (err: any) {
      const backendMsg =
        err.response?.data?.errors?.[0]?.message ||
        err.response?.data?.message ||
        err.message;

      const friendly = getUserFriendlyError(backendMsg);
      setMessage(friendly);
      isSuccess(false);
    } finally {
      setLoading(false);
      setModalVisible(true);
    }
  };


  const fetchBank = async () => {
    const response = await fetchBankList();
    return response.data;
  };

  const handleCloseModal = () => setModalVisible(false);

  if (loading) {
    return (
      <main className="flex justify-center items-center h-screen bg-white">
        <Loader />
      </main>
    );
  }

  return (
    <SettingsLayout>
      {(activeSection) => (
        <>
          {activeSection === "profile" && (
            <ProfileSection
              profileData={initialValues}
              onProfileChange={handleProfileChange}
              onUpdate={handleProfileUpdate}
            />
          )}

          {activeSection === "password" && (
            <PasswordSection
              passwords={passwords}
              onPasswordChange={handlePasswordChange}
              onUpdate={handlePasswordUpdate}
            />
          )}

          {activeSection === "withdraw" && (
            <WithdrawSection
              bankDetails={bankDetails}
              onContinue={handleWithdrawToBank}
              onCancel={() => console.log("Withdraw cancelled")}
            />
          )}
          {activeSection === "addBank" && (
            <AddBankSection
              fetchBanks={fetchBank}
              onContinue={(bankDetails) => {saveBankDetails(bankDetails)}}
              onCancel={() => console.log("Withdraw cancelled")}
            />
          )}

          {/* {activeSection === "delete" && (
            <DeleteAccountSection
              onDelete={() => console.log("Delete account")}
              onCancel={() => console.log("Delete cancelled")}
            />
          )} */}

          {modalVisible && (
            <div className="fixed inset-0 flex items-center justify-center bg-black/40 z-50">
              <div className="bg-white rounded-xl p-6 text-center max-w-sm">
                <h3 className={`text-lg font-bold mb-3 ${success ? "text-green-600" : "text-red-600"}`}>
                  {success ? "Success" : "Error!"}
                </h3>
                <p className="text-gray-700 mb-4">{message}</p>
                <button
                  onClick={handleCloseModal}
                  className={`px-6 py-2 rounded-lg text-white ${
                    success ? "bg-green-600 hover:bg-green-700" : "bg-red-600 hover:bg-red-700"
                  }`}
                >
                  {success ? "Continue" : "Try Again"}
                </button>
              </div>
            </div>
          )}
        </>
      )}

    </SettingsLayout>
  );
}
