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

import React, { useCallback } from "react";
import {
  UserGroupIcon,
  CameraIcon,
  ArchiveBoxIcon,
  ArchiveBoxXMarkIcon,
  TrashIcon,
  LockClosedIcon,
  DevicePhoneMobileIcon,
  NoSymbolIcon,
  CheckCircleIcon,
  ArrowUpCircleIcon,
  ArrowDownCircleIcon,
  EllipsisHorizontalIcon,
  ChartBarIcon,
  XCircleIcon,
  ClockIcon,
  BuildingOfficeIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import { StarIcon as StarIconSolid } from "@heroicons/react/24/solid";
import { useFacilitatorManager } from "../../../../../services/Services";
import { EntityMorePage } from "../../../../../components/business/views";
import {
  Avatar,
  Badge,
  ContactLink,
  AddressDisplay,
} from "../../../../../components/UIX";
import {
  TagsDisplay,
  SkillSetsDisplay,
  CertificationDisplay,
} from "../../../../../components/business/displays";
import { formatDateForDisplay } from "../../../../../services/Helpers/DateFormatter";

// Facilitator constants
const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;
const INDIVIDUAL_FACILITATOR_TYPE_OF_ID = 1;
const RESIDENTIAL_FACILITATOR_TYPE_OF_ID = 2; // Residential type
const COMMERCIAL_FACILITATOR_TYPE_OF_ID = 3; // Commercial type
const FACILITATOR_STATUS_ACTIVE = 1;
const FACILITATOR_STATUS_ARCHIVED = 2;

const FACILITATOR_CONSTANTS = {
  RESIDENTIAL_FACILITATOR_TYPE_OF_ID,
  COMMERCIAL_FACILITATOR_TYPE_OF_ID,
  FACILITATOR_STATUS_ACTIVE,
  FACILITATOR_STATUS_ARCHIVED,
};

// Helper function to get facilitator level label
const getLevelLabel = (level) => {
  switch (level) {
    case 1:
      return "Level 1 (in training)";
    case 2:
      return "Level 2 (secondary facilitator)";
    case 3:
      return "Level 3 (lead facilitator)";
    case 4:
      return "Level 4 (trainer)";
    default:
      return null;
  }
};

// Helper function to format score rating
const formatScoreRating = (score) => {
  if (!score)
    return (
      <span className="opacity-60 text-sm sm:text-base lg:text-lg">
        No rating
      </span>
    );
  return (
    <div className="flex items-center gap-1">
      {[...Array(5)].map((_, i) => (
        <StarIconSolid
          key={i}
          className={`w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 ${
            i < Math.floor(score) ? "text-yellow-400" : "text-gray-300"
          }`}
        />
      ))}
      <span className="ml-2 text-sm sm:text-base lg:text-lg opacity-70 font-medium">
        ({score}/5)
      </span>
    </div>
  );
};

// Helper function to extract IDs from array of objects
const extractIds = (items) => {
  if (!items || !Array.isArray(items)) return [];
  return items.map((item) => item.id || item.value).filter(Boolean);
};

// Function to create tab items for facilitator
const createFacilitatorTabItems = (facilitator, facilitatorId) => [
  {
    label: "Summary",
    href: `/admin/facilitator/${facilitator.id}`,
    isActive: false,
  },
  {
    label: "Full Details",
    href: `/admin/facilitator/${facilitator.id}/detail`,
    isActive: false,
  },
  {
    label: "Event Contracts",
    href: `/admin/facilitator/${facilitator.id}/event-contracts`,
    isActive: false,
  },
  {
    label: "Comments",
    href: `/admin/facilitator/${facilitator.id}/comments`,
    isActive: false,
  },
  {
    label: "Attachments",
    href: `/admin/facilitator/${facilitator.id}/attachments`,
    isActive: false,
  },
  {
    label: "More",
    href: `/admin/facilitator/${facilitator.id}/more`,
    isActive: true,
    icon: EllipsisHorizontalIcon,
  },
];

// Function to create action cards for facilitator
const createFacilitatorActionCards = (
  facilitator,
  facilitatorId,
  constants,
) => {
  const actionCards = [];

  if (facilitator) {
    // Avatar - Available for all facilitators
    actionCards.push({
      key: "avatar",
      title: "Avatar",
      subtitle: "Change the facilitator's profile picture",
      icon: CameraIcon,
      path: `/admin/facilitator/${facilitatorId}/avatar`,
      disabled: false,
    });

    // Archive/Unarchive
    if (facilitator.status === constants.FACILITATOR_STATUS_ARCHIVED) {
      actionCards.push({
        key: "unarchive",
        title: "Unarchive",
        subtitle: "Make facilitator visible in list and search results",
        icon: ArchiveBoxXMarkIcon,
        path: `/admin/facilitator/${facilitatorId}/unarchive`,
        disabled: false,
      });
    } else {
      actionCards.push({
        key: "archive",
        title: "Archive",
        subtitle: "Make facilitator hidden from list and search results",
        icon: ArchiveBoxIcon,
        path: `/admin/facilitator/${facilitatorId}/archive`,
        disabled: false,
      });
    }

    // Upgrade/Downgrade - Only for active facilitators
    if (facilitator.status === constants.FACILITATOR_STATUS_ACTIVE) {
      if (facilitator.type === constants.COMMERCIAL_FACILITATOR_TYPE_OF_ID) {
        actionCards.push({
          key: "downgrade",
          title: "Downgrade",
          subtitle: "Change facilitator to residential facilitator",
          icon: ArrowDownCircleIcon,
          path: `/admin/facilitator/${facilitatorId}/downgrade`,
          disabled: false,
        });
      } else {
        actionCards.push({
          key: "upgrade",
          title: "Upgrade",
          subtitle: "Change facilitator to commercial facilitator",
          icon: ArrowUpCircleIcon,
          path: `/admin/facilitator/${facilitatorId}/upgrade`,
          disabled: false,
        });
      }

      // Password - Only for active facilitators
      actionCards.push({
        key: "password",
        title: "Password",
        subtitle: "Change or reset the facilitator's password",
        icon: LockClosedIcon,
        path: `/admin/facilitator/${facilitatorId}/change-password`,
        disabled: false,
      });

      // 2FA - Only for active facilitators
      actionCards.push({
        key: "2fa",
        title: "2FA",
        subtitle: "Enable or disable two-factor authentication",
        icon: DevicePhoneMobileIcon,
        path: `/admin/facilitator/${facilitatorId}/change-2fa`,
        disabled: false,
      });

      // Delete - Only for active facilitators
      actionCards.push({
        key: "delete",
        title: "Delete",
        subtitle: "Permanently delete this facilitator and all related data",
        icon: TrashIcon,
        path: `/admin/facilitator/${facilitatorId}/permadelete`,
        disabled: false,
      });
    }

    // Ban/Unban
    if (facilitator.isBanned) {
      actionCards.push({
        key: "unban",
        title: "Unban",
        subtitle: "Remove ban from facilitator",
        icon: CheckCircleIcon,
        path: `/admin/facilitator/${facilitatorId}/unban`,
        disabled: false,
      });
    } else {
      actionCards.push({
        key: "ban",
        title: "Ban",
        subtitle: "Mark the facilitator as banned",
        icon: NoSymbolIcon,
        path: `/admin/facilitator/${facilitatorId}/ban`,
        disabled: false,
      });
    }
  }

  return actionCards;
};

// Function to build field sections for facilitator
const buildFacilitatorFieldSections = (facilitator) => {
  if (!facilitator || !facilitator.id) return [];

  return [
    {
      type: "avatar",
      component: (
        <Avatar
          src={facilitator.avatarObjectUrl}
          alt={
            facilitator.avatarObjectUrl
              ? "Profile Picture"
              : "No Profile Picture"
          }
          size="lg"
          borderStyle="default"
          showFallbackIcon={true}
        />
      ),
    },
    {
      column: "primary",
      className: "mb-3 sm:mb-4 lg:mb-5",
      component: (
        <div>
          {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID &&
            facilitator.representitiveOrganizationName && (
              <h2 className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold opacity-90 flex items-center justify-center xl:justify-start mb-2">
                <BuildingOfficeIcon className="w-5 sm:w-6 h-5 sm:h-6 lg:w-8 lg:h-8 mr-2 lg:mr-3 flex-shrink-0 opacity-80" />
                <span className="break-words">
                  {facilitator.representitiveOrganizationName}
                </span>
              </h2>
            )}
          <h3 className="text-base sm:text-lg md:text-xl lg:text-2xl font-semibold opacity-90 flex items-center justify-center xl:justify-start">
            {facilitator.type === INDIVIDUAL_FACILITATOR_TYPE_OF_ID && (
              <HomeIcon className="w-4 sm:w-5 h-4 sm:h-5 lg:w-7 lg:h-7 mr-2 flex-shrink-0 opacity-80" />
            )}
            <span className="break-words">
              {facilitator.name ||
                `${facilitator.firstName} ${facilitator.lastName}`}
            </span>
          </h3>
          <div className="mt-2 text-sm lg:text-base opacity-70 flex flex-wrap gap-2 justify-center xl:justify-start">
            {facilitator.level && getLevelLabel(facilitator.level) && (
              <Badge variant="info" size="md">
                {getLevelLabel(facilitator.level)}
              </Badge>
            )}
            {facilitator.isBanned ? (
              <Badge variant="error" size="sm">
                <XCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                Banned
              </Badge>
            ) : facilitator.status === 1 ? (
              <Badge variant="primary" size="sm">
                <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                Active
              </Badge>
            ) : (
              <Badge variant="secondary" size="sm">
                <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
                Archived
              </Badge>
            )}
          </div>
        </div>
      ),
    },
    {
      column: "primary",
      className: "mb-3 sm:mb-4 lg:mb-5",
      component: (
        <div className="space-y-3">
          {facilitator.certifications &&
            facilitator.certifications.length > 0 && (
              <div className="flex flex-wrap gap-2 justify-center xl:justify-start">
                <CertificationDisplay
                  values={extractIds(facilitator.certifications)}
                  onUnauthorized={() => {}}
                />
              </div>
            )}
          {facilitator.skillSets && facilitator.skillSets.length > 0 && (
            <div className="flex flex-wrap gap-2 justify-center xl:justify-start">
              <SkillSetsDisplay
                values={extractIds(facilitator.skillSets)}
                onUnauthorized={() => {}}
              />
            </div>
          )}
        </div>
      ),
    },
    {
      column: "primary",
      className: "mb-3 sm:mb-4 lg:mb-5",
      component: (
        <AddressDisplay
          addressData={facilitator}
          size="md"
          showIcon={true}
          showMapsLink={true}
        />
      ),
    },
    {
      column: "primary",
      className: "space-y-2 sm:space-y-3",
      component: (
        <div className="space-y-2 sm:space-y-3">
          <ContactLink
            type="email"
            value={facilitator.email}
            size="md"
            fallbackText="No email"
          />
          <ContactLink
            type="phone"
            value={facilitator.phone}
            size="md"
            fallbackText="No phone"
          />
          {facilitator.otherPhone && (
            <ContactLink
              type="phone"
              value={facilitator.otherPhone}
              size="md"
              fallbackText="No phone"
            />
          )}
        </div>
      ),
    },
    {
      column: "secondary",
      className: "mb-4 sm:mb-5",
      component: (
        <div className="space-y-4">
          <div>
            <label className="text-sm font-medium opacity-70">Type</label>
            <p className="text-base opacity-90 mt-1">
              {facilitator.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID
                ? "Representative"
                : facilitator.type === INDIVIDUAL_FACILITATOR_TYPE_OF_ID
                  ? "Individual"
                  : "Unassigned"}
            </p>
          </div>

          <div>
            <label className="text-sm font-medium opacity-70">Rating</label>
            <div className="mt-1">{formatScoreRating(facilitator.score)}</div>
          </div>
        </div>
      ),
    },
    {
      column: "secondary",
      component: (
        <div className="space-y-2 text-xs sm:text-sm lg:text-base opacity-70">
          {facilitator.createdAt && (
            <div className="flex items-center justify-center xl:justify-start">
              <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 mr-2 opacity-60" />
              <span className="font-medium">Created:</span>
              <span className="ml-2">
                {formatDateForDisplay(facilitator.createdAt)}
              </span>
            </div>
          )}
          {facilitator.modifiedAt && (
            <div className="flex items-center justify-center xl:justify-start">
              <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 lg:w-5 lg:h-5 mr-2 opacity-60" />
              <span className="font-medium">Last Modified:</span>
              <span className="ml-2">
                {formatDateForDisplay(facilitator.modifiedAt)}
              </span>
            </div>
          )}
        </div>
      ),
    },
  ].filter((section) => section.component);
};

function AdminFacilitatorDetailMorePage() {
  const facilitatorManager = useFacilitatorManager();

  // Custom get facilitator detail function wrapped with useCallback to prevent infinite loops
  const getFacilitatorDetailWithManager = useCallback(
    async (facilitatorId, onUnauthorized) => {
      return new Promise((resolve, reject) => {
        facilitatorManager.getFacilitatorDetailWithCallbacks(
          facilitatorId,
          (facilitatorData) => resolve(facilitatorData), // onSuccess
          (error) => reject(error), // onError
          () => {}, // onDone
          onUnauthorized, // onUnauthorized
        );
      });
    },
    [facilitatorManager],
  );

  return (
    <EntityMorePage
      entityIcon={UserGroupIcon}
      entityType="Facilitator"
      entityTypePlural="Facilitators"
      basePath="/admin/facilitators"
      entityParamName="aid"
      entityManager={facilitatorManager}
      getEntityDetail={getFacilitatorDetailWithManager}
      createTabItems={createFacilitatorTabItems}
      createActionCards={createFacilitatorActionCards}
      constants={FACILITATOR_CONSTANTS}
      infoMessage="Some actions are only available for active facilitators. Archived facilitators must be unarchived first before performing other actions."
      buildFieldSections={buildFacilitatorFieldSections}
    />
  );
}

export default AdminFacilitatorDetailMorePage;
