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

import React from "react";
import {
  BriefcaseIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  EnvelopeIcon,
  PhoneIcon,
  UserCircleIcon,
  ShieldCheckIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  FACILITATOR_STATUS_ACTIVE,
} from "../../../../constants/Facilitator";
import { useFacilitatorManager } from "../../../../services/Services";

function AdminFacilitatorListPage() {
  const facilitatorManager = useFacilitatorManager();
  const { getThemeClasses } = useUIXTheme();

  // Get badge component for facilitator status
  const getStatusBadge = (status) => {
    const variantMap = {
      1: "success", // Active
      2: "secondary", // Archived
    };
    const variant = variantMap[status] || "default";

    const statusLabels = {
      1: "Active",
      2: "Archived",
    };

    return (
      <Badge variant={variant} size="sm">
        {statusLabels[status] || "Unknown"}
      </Badge>
    );
  };

  // Build params function for the API
  const buildParams = (params) => {
    const {
      pageSize = 25,
      currentCursor,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
    } = params || {};

    const filtersMap = new Map();
    filtersMap.set("page_size", String(pageSize));

    // Add cursor for pagination
    if (currentCursor) {
      filtersMap.set("cursor", currentCursor);
    }

    // Add sorting
    if (sortBy && sortOrder) {
      filtersMap.set("sortField", sortBy);
      filtersMap.set("sortOrder", sortOrder);
    }

    // Add filters
    if (status && status !== "0" && status !== "") {
      filtersMap.set("status", parseInt(status));
    }

    if (searchQuery && searchQuery.trim()) {
      filtersMap.set("search", searchQuery.trim());
    }

    return filtersMap;
  };

  // Fetch data function
  const fetchData = async (params, onUnauthorized, forceRefresh) => {
    const filtersMap = buildParams(params);
    return new Promise((resolve, reject) => {
      facilitatorManager.getFacilitatorsWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          resolve({
            results: response.results || [],
            count: response.count || 0,
            nextCursor: response.nextCursor || ""
          });
        },
        reject,
        () => {}, // onDone callback
        onUnauthorized,
        forceRefresh,
      );
    });
  };

  // Custom grid item renderer
  const renderGridItem = (facilitator, navigate) => {
    return (
      <div
        key={facilitator.id}
        className={`${getThemeClasses('bg-card')} border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow cursor-pointer`}
        onClick={() => navigate(`/admin/facilitator/${facilitator.id}`)}
      >
        <div className="p-6">
          <div className="mb-4">
            <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} flex items-start`}>
              <BriefcaseIcon className={`w-6 h-6 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses('text-muted')}`} />
              <span>
                {facilitator.name || `${facilitator.firstName} ${facilitator.lastName}`}
              </span>
            </h3>
            {facilitator.jobTitle && (
              <p className={`text-sm ${getThemeClasses('text-secondary')} mt-1 ml-8`}>
                {facilitator.jobTitle}
              </p>
            )}
            <div className="flex items-center gap-2 mt-2 ml-8">
              {getStatusBadge(facilitator.status)}
            </div>
          </div>

          <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4`}>
            {facilitator.email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span className={`${getThemeClasses('link-primary')} truncate`}>
                  {facilitator.email}
                </span>
              </div>
            )}
            {facilitator.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{facilitator.phone}</span>
              </div>
            )}
          </div>

          {/* Action buttons */}
          <div className="flex gap-2">
            <ViewButton
              to={`/admin/facilitator/${facilitator.id}`}
              text="View Details"
              fullWidth={true}
            />
          </div>
        </div>
      </div>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/facilitator/:id",
      render: (value, facilitator) => {
        const displayName = facilitator.name || `${facilitator.firstName} ${facilitator.lastName}`;
        return (
          <div className="flex items-center">
            <BriefcaseIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>
              <span>{displayName}</span>
              {facilitator.jobTitle && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {facilitator.jobTitle}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, facilitator) => {
        if (!email && !facilitator.phone) return null;
        return (
          <div className="space-y-1">
            {email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`mailto:${email}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {email}
                </a>
              </div>
            )}
            {facilitator.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{facilitator.phone}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      render: (value, facilitator) => (
        <ViewButton
          to={`/admin/facilitator/${facilitator.id}`}
          text="View Facilitator"
        />
      )
    }
  ];

  // Status filter options
  const statusOptions = [
    { value: "0", label: "All Statuses" },
    { value: "1", label: "Active" },
    { value: "2", label: "Archived" },
  ];

  // Sort options
  const sortOptions = [
    { value: "name,ASC", label: "Name (A → Z)" },
    { value: "name,DESC", label: "Name (Z → A)" },
    { value: "createdAt,DESC", label: "Created Date (Newest → Oldest)" },
    { value: "createdAt,ASC", label: "Created Date (Oldest → Newest)" },
  ];

  // UniversalListPage configuration
  const config = {
    entityName: "Facilitator",
    entityNamePlural: "Facilitators",
    icon: BriefcaseIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Facilitator",
    routes: {
      search: "/admin/facilitators/search",
      create: "/admin/facilitators/add/step-1-part-a",
      detail: "/admin/facilitator/:id",
    },
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: HomeIcon
      },
      {
        label: 'Facilitators',
        icon: BriefcaseIcon,
        isActive: true
      }
    ],
    columns,
    statusOptions,
    typeOptions: [], // No type filter for facilitators
    sortOptions,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    searchPlaceholder: "Search facilitators by name, email, or phone...",
    emptyState: {
      title: "No Facilitators Found",
      filterDescription: "No facilitators match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No facilitators have been added yet.",
      actionLabel: "Add Facilitator"
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: "1", // Active
    defaultType: "0",
    defaultSort: "name",
    defaultSortOrder: "ASC",
    defaultPageSize: 25,
    defaultViewType: "grid"
  };

  return <UniversalListPage config={config} />;
}

export default AdminFacilitatorListPage;