// File Path: monorepo/web/frontend/src/pages/Admin/Facilitator/Detail/More/ChangePassword/Page.jsx

import React, { useMemo } from "react";
import { useParams } from "react-router";
import {
  useFacilitatorManager,
  useAuthManager,
} from "../../../../../../services/Services";
import { ChangePasswordPage, Badge } from "../../../../../../components/UIX";
import { FACILITATOR_STATUS_ARCHIVED } from "../../../../../../constants/Facilitator";
import axios from "axios";

function AdminFacilitatorDetailMoreChangePasswordPage() {
  const { aid } = useParams();
  const facilitatorManager = useFacilitatorManager();
  const authManager = useAuthManager();

  // Breadcrumb items
  const breadcrumbItems = useMemo(
    () => [
      { label: "Dashboard", to: "/admin/dashboard" },
      { label: "Facilitators", to: "/admin/facilitators" },
      { label: "Detail (More)", to: `/admin/facilitator/${aid}/more` },
      { label: "Change Password" },
    ],
    [aid],
  );

  // Fetch facilitator function
  const fetchFacilitator = async (
    facilitatorId,
    onUnauthorized,
    forceRefresh,
  ) => {
    return await facilitatorManager.getFacilitatorDetail(
      facilitatorId,
      onUnauthorized,
    );
  };

  // Change password function
  const changePassword = async (passwordData, onUnauthorized) => {
    const data = {
      facilitator_id: aid,
      ...passwordData,
    };

    // Get access token
    let accessToken =
      localStorage.getItem("FLASHPOINTTRAINING_ACCESS_TOKEN") ||
      localStorage.getItem("FLASHPOINTTRAINING_TENANT_ACCESS_TOKEN") ||
      localStorage.getItem("access_token") ||
      localStorage.getItem("accessToken");

    if (!accessToken) {
      const tokenKey = Object.keys(localStorage).find(
        (key) =>
          key.toLowerCase().includes("token") &&
          !key.toLowerCase().includes("refresh") &&
          !key.toLowerCase().includes("timestamp"),
      );

      if (tokenKey) {
        accessToken = localStorage.getItem(tokenKey);
      }
    }

    if (!accessToken) {
      throw new Error("No access token found. Please login again.");
    }

    const apiBaseUrl =
      process.env.NODE_ENV === "development"
        ? "http://127.0.0.1:8000"
        : window.location.origin;

    const endpoint = "/api/v1/facilitators/operations/change-password";
    const fullUrl = `${apiBaseUrl}${endpoint}`;

    await axios.post(fullUrl, data, {
      headers: {
        Authorization: `JWT ${accessToken}`,
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
  };

  // Get entity name
  const getEntityName = (facilitator) => {
    return `${facilitator.firstName} ${facilitator.lastName}`;
  };

  // Get badges
  const getBadges = (facilitator) => {
    return (
      <>
        {facilitator.status === FACILITATOR_STATUS_ARCHIVED && (
          <Badge variant="secondary">Archived</Badge>
        )}
      </>
    );
  };

  return (
    <ChangePasswordPage
      entityId={aid}
      onFetchEntity={fetchFacilitator}
      onChangePassword={changePassword}
      onUnauthorized={() => (window.location.href = "/login?unauthorized=true")}
      isAuthenticated={() => authManager.isAuthenticated()}
      breadcrumbItems={breadcrumbItems}
      backUrl={`/admin/facilitator/${aid}/more`}
      successRedirectUrl={`/admin/facilitator/${aid}/more`}
      pageTitle="Change Password"
      getEntityName={getEntityName}
      getBadges={getBadges}
      minPasswordLength={8}
    />
  );
}

export default AdminFacilitatorDetailMoreChangePasswordPage;
