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

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

function AdminSpeakerDetailMoreChangePasswordPage() {
  const { aid } = useParams();
  const speakerManager = useSpeakerManager();
  const authManager = useAuthManager();

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

  // Fetch speaker function
  const fetchSpeaker = async (speakerId, onUnauthorized, forceRefresh) => {
    return await speakerManager.getSpeakerDetail(speakerId, onUnauthorized);
  };

  // Change password function
  const changePassword = async (passwordData, onUnauthorized) => {
    const data = {
      speaker_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/speakers/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 = (speaker) => {
    return `${speaker.firstName} ${speaker.lastName}`;
  };

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

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

export default AdminSpeakerDetailMoreChangePasswordPage;
