
/* eslint-disable @typescript-eslint/no-explicit-any */
import AdminDashboardLayout from "@/layouts/admin_layout";
import styles from "./user.module.scss";
import PageIntro from "@/components/dashboard/PageIntro";
import { BsArrowLeft } from "react-icons/bs";
import { FaAngleDown, FaAngleUp } from "react-icons/fa";
import { useState } from "react";
import { formatDate } from "@/lib/utils/format-date";

// Action Components
import DeleteConfirmationModal from "@/components/admin/Modals/DeleteConfirmationModal";
import ConfirmActionOnUser from "@/components/admin/Modals/ConfirmActionOnUserModal";
import UpdateUserSignal from "@/components/admin/Modals/UpdateUserTradingSignal";
import { capitalizeFirstLetter } from "@/lib/utils/capitalise-first-letter";

import currencyData from "../../../../../data/countries-currencies.json";
import { formatMoneyComplete } from '@/lib/utils/format-money'
import { usePage } from "@inertiajs/react";


const SingleUser = ({ user, accountTypes }: any) => {
  const { appSettings } = usePage().props as any
  const userId = user?.id;
  console.log("Returned single user", accountTypes);

  const currency = currencyData.find(
    (item) => item.currency_code === appSettings?.base_currency
  )

  const [actionActive, setActionActive] = useState(false);
  const [deleteSignal, setDeleteSignal] = useState(false);
  const [updateSignal, setUpdateSignal] = useState(false);
  const [signal, setSignal] = useState({});

  // Toggle action active state
  const toggleActionActive = () => {
    setActionActive(!actionActive);
  };

  // Go back to users page - admin/users
  const handleGoBack = () => {
    window.location.href = "/admin/users";
  };

  // Delete Purchased Signal
  const toggleDeleteSignal = () => {
    setDeleteSignal(!deleteSignal);
  };

  // Update Purchased Signal
  const toggleUpdatePurchasedSignal = (signal: any) => {
    setUpdateSignal(!updateSignal);
    setSignal(signal);
  };

  // Action states
  const [deleteUser, setDeleteUser] = useState(false);
  const [canWithdraw, setCanWithDraw] = useState(false);
  const [blockModal, setBlockModal] = useState(false);
  const [upgradeAccountModal, setUpgradeAccountModal] = useState(false);
  const [verifyUserModal, setVerifyUserModal] = useState(false);
  const [tradeModal, setTradeModal] = useState(false);
  const [creditModal, setCreditModal] = useState(false);
  const [addTradingPlanModal, setAddTradingPlanModal] = useState(false);
  const [addEstatePlanModal, setAddEstatePlanModal] = useState(false);
  const [messageModal, setMessageModal] = useState(false);
  const [signalModal, setSignalModal] = useState(false);
  const [tradeForUser, setTradeForUser] = useState(false);
  const [editUserModal, setEditUserModal] = useState(false);

  const [upgradeUserAccount, setUpgradeAccount] = useState(false);

  // Action toggles
  const toggleDeleteUser = () => setDeleteUser(!deleteUser);
  const toggleBlockUser = () => setBlockModal(!blockModal);
  const toggleCanWithdrawModal = () => setCanWithDraw(!canWithdraw);
  const toggleUpgradeAccount = () => setUpgradeAccountModal(!upgradeAccountModal);
  const toggleVerifyUser = () => setVerifyUserModal(!verifyUserModal);
  const toggleUserTradeMode = () => setTradeModal(!tradeModal);
  const toggleCreditModal = () => setCreditModal(!creditModal);
  const toggleAddTradingPlan = () => setAddTradingPlanModal(!addTradingPlanModal);
  const toggleAddEstatePlan = () => setAddEstatePlanModal(!addEstatePlanModal);
  const toggleSendMessage = () => setMessageModal(!messageModal);
  const toggleAddSignals = () => setSignalModal(!signalModal);
  const toggleTradeForUser = () => setTradeForUser(!tradeForUser);
  const toggleEditUserModal = () => setEditUserModal(!editUserModal);

   const toggleUpgradeUserAccount = () => setUpgradeAccount(!upgradeUserAccount);

  return (
    <>
      {deleteUser && (
        <DeleteConfirmationModal
          closeModal={toggleDeleteUser}
          title="Delete User"
          description={`You are about to delete ${user?.name} and all records will be deleted from the system. Make sure you are sure before proceeding.`}
          deleteUrl="dldld"
        />
      )}

      {deleteSignal && (
        <DeleteConfirmationModal
          closeModal={toggleDeleteSignal}
          title="Delete User Purchased Signal"
          description="You are about to delete a user purchased signal and all associated records will be deleted from the system. Be sure before proceeding."
          deleteUrl=""
        />
      )}

      {updateSignal && (
        <UpdateUserSignal
          closeModal={toggleUpdatePurchasedSignal}
          action={toggleUpdatePurchasedSignal}
          title="Update User Purchased Signal"
          description="Update the signal details purchased by the user"
          signal={signal}
        />
      )}

      {blockModal && (
        <ConfirmActionOnUser
          closeModal={toggleBlockUser}
          id={userId}
          type="account"
          title={user?.is_account_blocked ? "Unblock User Account" : "Block User Account"}
          description={
            user?.is_account_blocked
              ? "Dear Admin, you are about to unblock this user's account and the user will be able to access the account. Please be sure before confirming the action."
              : "Dear Admin, you are about to block this user's account and user will not have access to the account. Please be sure before confirming the action."
          }
        />
      )}

      {canWithdraw && (
        <ConfirmActionOnUser
          closeModal={toggleCanWithdrawModal}
          id={userId}
          type="withdraw"
          title={user?.can_withdraw ? "Disable Witdhrawal" : "Enable Withdrawal"}
          description={
            user?.can_withdraw
              ? "Dear Admin, you are about to disable withdrawals for this user and will not be able to carry out withdrawals."
              : "Dear Admin, you are about to enable withdrawals for this user and the user will now be able to carry out withdrawals."
          }
        />
      )}

      {upgradeAccountModal && (
        <ConfirmActionOnUser
          closeModal={toggleUpgradeAccount}
          id={userId}
          type="upgrade"
          title={user?.needs_upgrade ? "Upgrade User Account - False" : "Upgrade User Account - True"}
          description={
            user?.needs_upgrade
              ? "Dear Admin, you are about to turn off the upgrade status for this user and will now be able to carry out withdrawals without upgrading the account."
              : "Dear Admin, you are about to turn on the upgrade status for this user and the user will not be able to carry out withdrawals without upgrading the account."
          }
        />
      )}

      {verifyUserModal && (
        <ConfirmActionOnUser
          closeModal={toggleVerifyUser}
          id={userId}
          type="verify"
          title={user?.is_kyc_verified ? "Unverify User KYC Status" : "Verify User KYC Status"}
          description={
            user?.is_kyc_verified
              ? `Dear Admin, you are about to unverify the kyc status for user with id ${userId} and the user will not be able to carry out withdrawals without further actions.`
              : `Dear Admin, you are about to verify the KYC status for user with id ${userId} and the user will now be able to carry out withdrawals without further actions.`
          }
        />
      )}

      {tradeModal && (
        <ConfirmActionOnUser
          closeModal={toggleUserTradeMode}
          id={userId}
          type="trade"
          title={user?.win_trades ? "Set Trades To Loss Mode" : "Set Trades to Win Mode"}
          description={
            user?.win_trades
              ? `Dear Admin, you are about to set trade mode to loss for user with id ${userId} and the user trades will always return a loss. Be sure before confirming the action.`
              : `Dear Admin, you are about to set trade mode to win for user with id ${userId} and the user trades will always return a win. Be sure before confirming the action.`
          }
        />
      )}

      {creditModal && (
        <ConfirmActionOnUser
          closeModal={toggleCreditModal}
          id={userId}
          type="transaction"
          title="Credit/Debit User"
          description="Credit or debit a user account by entering the amount and the column you want to credit or debit."
        />
      )}

      {addTradingPlanModal && (
        <ConfirmActionOnUser
          closeModal={toggleAddTradingPlan}
          id={userId}
          type="trading-plan"
          title="Add Trading Plan For User"
          description={`Add an active trading plan to a user with id ${userId}. It will reflect on the user dashboard when logged in.`}
        />
      )}

      {addEstatePlanModal && (
        <ConfirmActionOnUser
          closeModal={toggleAddEstatePlan}
          id={userId}
          type="estate-plan"
          title="Add Real Estate Plan For User"
          description={`Add an active real estate investment plan to a user with id ${userId}. It will reflect on the user dashboard when logged in.`}
        />
      )}

      {signalModal && (
        <ConfirmActionOnUser
          closeModal={toggleAddSignals}
          id={userId}
          type="signals"
          title="Add Signal To User"
          description={`Add a purchased trading signal to a user with id ${userId}. It will reflect on the user dashboard when logged in.`}
        />
      )}

      {tradeForUser && (
        <ConfirmActionOnUser
          closeModal={toggleTradeForUser}
          id={userId}
          type="trade"
          title="Trade For User"
          description={`Trade for a user user with id ${userId}. Trades will reflect on the user dashboard when logged in.`}
        />
      )}

      {editUserModal && (
        <ConfirmActionOnUser
            closeModal={toggleEditUserModal}
            id={userId}
            user={user}   // 👈 THIS IS WHAT WAS MISSING
            type="user"
            title="Edit User Details"
            description={`Edit details for user with id ${userId}. This will reflect on the user dashboard when logged in.`}
        />
        )}

        {messageModal && (
          <ConfirmActionOnUser
            closeModal={toggleSendMessage}
            id={userId}
            type="message"
            title="Message User"
            description={`Message ${user?.name}. It will reflect on the user dashboard when logged in and also be sent to the user's email address.`}
          />
        )}


        {
          upgradeUserAccount && (
            <ConfirmActionOnUser
              closeModal={toggleUpgradeUserAccount}
              id={user?.id}
              type="upgrade-user-account"
              title="Upgrade User Account"
              description="Assign a new account level to this user."
              accountTypes={accountTypes}
            />
          )
        }

      <div className={styles["user"]}>
        <div className={styles["user__header"]}>
          <PageIntro
            title={`${user?.name}`}
            description={`Account Summary`}
          />

          <div className={styles["user__header__helper"]}>
            <span onClick={handleGoBack} className={styles["user__header__helper--back"]}>
              <BsArrowLeft /> &nbsp;Back
            </span>

            <div onClick={toggleActionActive} className={styles["user__header__helper--actions"]}>
              Actions &nbsp; {actionActive ? <FaAngleUp /> : <FaAngleDown />}

              {actionActive && (
                <span className={styles["user__header__helper--actions--links"]}>
                  <div className={styles["user__header__helper--actions--links--content"]}>
                    <span onClick={toggleActionActive}>Close</span>
                    <h2>User Management Center</h2>
                    <p>
                      Manage account access, trading permissions, withdrawals,
                      portfolio adjustments, communication, and other administrative
                      actions for this user.
                      </p>
                    <div className={styles["user__header__helper--actions--links--menu"]}>
                      <button onClick={toggleBlockUser}>
                        <span>🔒</span>
                        <div>
                          <h4>Block User</h4>
                          <p>Restrict access to the platform</p>
                        </div>
                      </button>

                      <button onClick={toggleCanWithdrawModal}>
                        <span>💳</span>
                        <div>
                          <h4>Withdrawal Access</h4>
                          <p>Enable or disable withdrawals</p>
                        </div>
                      </button>

                      <button onClick={toggleUpgradeAccount}>
                        <span>⭐</span>
                        <div>
                          <h4>Upgrade Account Status</h4>
                          <p>Require account upgrade</p>
                        </div>
                      </button>

                      <button onClick={toggleCreditModal}>
                        <span>💰</span>
                        <div>
                          <h4>Credit / Debit</h4>
                          <p>Adjust balance or ROI</p>
                        </div>
                      </button>

                      <button onClick={toggleTradeForUser}>
                        <span>📈</span>
                        <div>
                          <h4>Trade For User</h4>
                          <p>Create and manage trades</p>
                        </div>
                      </button>

                      <button onClick={toggleEditUserModal}>
                        <span>✏️</span>
                        <div>
                          <h4>Edit User</h4>
                          <p>Update profile information</p>
                        </div>
                      </button>

                      <button onClick={toggleSendMessage}>
                        <span>📨</span>
                        <div>
                          <h4>Send Message</h4>
                          <p>Dashboard notification & email</p>
                        </div>
                      </button>

                      <button onClick={toggleUpgradeUserAccount}>
                        <span>🚀</span>

                        <div>
                          <h4>Upgrade Account</h4>
                          <p>Assign a new account level</p>
                        </div>
                      </button>

                      <button
                        onClick={toggleDeleteUser}
                        className={styles.dangerAction}
                      >
                        <span>🗑️</span>
                        <div>
                          <h4>Delete User</h4>
                          <p>Permanently remove this account</p>
                        </div>
                      </button>
                    </div>
                  </div>
                </span>
              )}
            </div>
          </div>
        </div>

        <div className={styles["user__summary"]}>
          <div className={styles["user__summary__content"]}>
            <div className={styles["user__summary__content--item"]}>
              <h6>Account Balance</h6>
              <p>{currency?.currency_symbol}{formatMoneyComplete(user?.balance)}</p>
            </div>


            <div className={styles["user__summary__content--item"]}>
              <h6>Total Profits</h6>
              <p>{currency?.currency_symbol}{formatMoneyComplete(user?.total_profits)}</p>
            </div>


            <div className={styles["user__summary__content--item"]}>
              <h6>Total Deposits</h6>
              <p>{currency?.currency_symbol}{formatMoneyComplete(user?.total_deposits)}</p>
            </div>


            <div className={styles["user__summary__content--item"]}>
              <h6>Withdrawals</h6>
              <p>{currency?.currency_symbol}{formatMoneyComplete(user?.total_withdrawals)}</p>
            </div>


            <div className={styles["user__summary__content--item"]}>
              <h6>Account Status</h6>
              <p
                className={
                  user?.is_account_active === true
                    ? styles["user__summary__content--item--active"]
                    : styles["user__summary__content--item--notactive"]
                }
              >
                {user?.is_account_active === true ? "Active" : "Disabled"}
              </p>
            </div>


            <div className={styles["user__summary__content--item"]}>
              <h6>KYC Status</h6>
              <p
                className={
                  user?.is_kyc_verified === true
                    ? styles["user__summary__content--item--active"]
                    : styles["user__summary__content--item--notactive"]
                }
              >
                {user?.is_kyc_verified ? "Verified" : "Not Verified"}
              </p>
            </div>
          </div>
        </div>

        <div className={styles["user__details"]}>
          <h1>User Information</h1>
          <div className={styles["user__details__content"]}>
            <div className={styles["user__details__content--item"]}>
              <h6>Full Name</h6>
              <p>{user?.name}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Username</h6>
              <p>{user?.username}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Email Address</h6>
              <p>{user?.email}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Phone Number</h6>
              <p>{user?.phone}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Country</h6>
              <p>{user?.country}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Registered Date</h6>
              <p>{formatDate(user?.created_at)}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Gender</h6>
              <p>{capitalizeFirstLetter(user?.gender)}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Preferred Assets</h6>
              <p>{capitalizeFirstLetter(user?.preferredAsset)}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Trading Experience</h6>
              <p>{capitalizeFirstLetter(user?.experience)}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Needs Account Upgrade</h6>
              <p>{user?.needs_upgrade ? "Yes" : "No"}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Account Blocked</h6>
              <p>{user?.is_account_blocked ? "Yes" : "No"}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Can User Withdraw</h6>
              <p>{user?.can_withdraw ? "Yes" : "No"}</p>
            </div>
            <div className={styles["user__details__content--item"]}>
              <h6>Account Type</h6>
              <p>{capitalizeFirstLetter(user?.account_type)}</p>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

SingleUser.layout = (page: React.ReactNode) => (
  <AdminDashboardLayout title="Manage Users">{page}</AdminDashboardLayout>
);

export default SingleUser;
