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

import React, { useMemo, useCallback } from "react";
import {
  UserGroupIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  EnvelopeIcon,
  PhoneIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
  AcademicCapIcon,
  HeartIcon,
  UserCircleIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  CUSTOMER_TYPE_VALUES,
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STATUS,
  CUSTOMER_STATUS_LABELS,
} from "../../../../constants/Customer";
import { useCustomerManager } from "../../../../services/Services";

function AdminCustomerListPage() {
  const customerManager = useCustomerManager();
  const { getThemeClasses } = useUIXTheme();

  // Get type icon for customer type - memoized
  const getCustomerTypeIcon = useCallback((type) => {
    switch (type) {
      case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
        return <AcademicCapIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case CUSTOMER_TYPE_VALUES.CORPORATE:
        return <BuildingOffice2Icon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case CUSTOMER_TYPE_VALUES.NON_PROFIT:
        return <HeartIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case CUSTOMER_TYPE_VALUES.GOVERNMENT:
        return <BuildingOfficeIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      default:
        return <UserGroupIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
    }
  }, []);

  // Get badge component for customer type - memoized
  const getTypeBadge = useCallback((customerType) => {
    // Map customer types to badge variants
    const variantMap = {
      [CUSTOMER_TYPE_VALUES.EDUCATIONAL]: "info",
      [CUSTOMER_TYPE_VALUES.CORPORATE]: "success",
      [CUSTOMER_TYPE_VALUES.NON_PROFIT]: "primary",
      [CUSTOMER_TYPE_VALUES.GOVERNMENT]: "warning",
    };
    const variant = variantMap[customerType] || "default";

    return (
      <Badge variant={variant} size="sm">
        {CUSTOMER_TYPE_LABELS[customerType] || "Unknown"}
      </Badge>
    );
  }, []);

  // Get badge component for customer status - memoized
  const getStatusBadge = useCallback((status) => {
    const variantMap = {
      [CUSTOMER_STATUS.ACTIVE]: "success",
      [CUSTOMER_STATUS.INACTIVE]: "secondary",
      [CUSTOMER_STATUS.PENDING]: "warning",
      [CUSTOMER_STATUS.SUSPENDED]: "error",
    };
    const variant = variantMap[status] || "default";

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

  // Build params function for the API - memoized
  const buildParams = useCallback((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 (type && type !== "0" && type !== "") {
      filtersMap.set("type", type);
    }

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

    return filtersMap;
  }, []);

  // Fetch data function - memoized
  const fetchData = useCallback(async (params, onUnauthorized, forceRefresh) => {
    // If params is already a Map (from UniversalListPage calling buildParams),
    // use it directly. Otherwise, build the Map.
    const filtersMap = params instanceof Map ? params : buildParams(params);

    return new Promise((resolve, reject) => {
      customerManager.getCustomersWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          resolve({
            results: response.results || [],
            count: response.count || 0,
            nextCursor: response.nextCursor || ""
          });
        },
        reject,
        () => {}, // onDone callback
        onUnauthorized,
        forceRefresh,
      );
    });
  }, [customerManager, buildParams]);

  // Custom grid item renderer - memoized
  const renderGridItem = useCallback((customer) => {
    return (
      <div
        key={customer.id}
        className={`${getThemeClasses('bg-card')} border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow h-full flex flex-col`}
      >
        <div className="p-6 flex flex-col flex-grow">
          <div className="mb-4">
            <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} flex items-start`}>
              {getCustomerTypeIcon(customer.type)}
              <span>
                {customer.name}
              </span>
            </h3>
            {customer.divisionShortName && (
              <p className={`text-sm ${getThemeClasses('text-secondary')} mt-1 ml-7`}>
                {customer.divisionShortName}
              </p>
            )}
            <div className="flex items-center gap-2 mt-2 ml-7">
              {getTypeBadge(customer.type)}
              {getStatusBadge(customer.status)}
            </div>
          </div>

          <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4 flex-grow`}>
            {customer.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`}>
                  {customer.email}
                </span>
              </div>
            )}
            {customer.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{customer.phone}</span>
              </div>
            )}
          </div>

          {/* Action buttons */}
          <div className="flex gap-2 mt-auto">
            <ViewButton
              to={`/admin/customer/${customer.id}`}
              text="View Details"
              fullWidth={true}
            />
          </div>
        </div>
      </div>
    );
  }, [getThemeClasses, getCustomerTypeIcon, getTypeBadge, getStatusBadge]);

  // Column configuration for DataList - memoized
  const columns = useMemo(() => [
    {
      header: "Name",
      accessor: "name",
      type: "link",
      linkPath: "/admin/customer/:id",
      render: (value, customer) => (
        <div className="flex items-center">
          {getCustomerTypeIcon(customer.type)}
          <span>{customer.name}</span>
        </div>
      )
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, customer) => {
        if (!email && !customer.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>
            )}
            {customer.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{customer.phone}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Division",
      accessor: "divisionShortName",
      render: (value) => value || "-"
    },
    {
      header: "Actions",
      align: "right",
      render: (value, customer) => (
        <ViewButton
          to={`/admin/customer/${customer.id}`}
          text="View Customer"
        />
      )
    }
  ], [getCustomerTypeIcon, getTypeBadge]); // getThemeClasses removed - captured in closure

  // Status filter options - memoized
  const statusOptions = useMemo(() => [
    { value: "0", label: "All Statuses" },
    { value: String(CUSTOMER_STATUS.ACTIVE), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.ACTIVE] },
    { value: String(CUSTOMER_STATUS.INACTIVE), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.INACTIVE] },
    { value: String(CUSTOMER_STATUS.PENDING), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.PENDING] },
    { value: String(CUSTOMER_STATUS.SUSPENDED), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.SUSPENDED] },
  ], []);

  // Type filter options - memoized
  const typeOptions = useMemo(() => [
    { value: "0", label: "All Types" },
    { value: CUSTOMER_TYPE_VALUES.EDUCATIONAL, label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.EDUCATIONAL] },
    { value: CUSTOMER_TYPE_VALUES.CORPORATE, label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.CORPORATE] },
    { value: CUSTOMER_TYPE_VALUES.NON_PROFIT, label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.NON_PROFIT] },
    { value: CUSTOMER_TYPE_VALUES.GOVERNMENT, label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.GOVERNMENT] },
  ], []);

  // Sort options - memoized
  const sortOptions = useMemo(() => [
    { value: "lexical_name,ASC", label: "Name (A → Z)" },
    { value: "lexical_name,DESC", label: "Name (Z → A)" },
    { value: "join_date,DESC", label: "Join Date (Newest → Oldest)" },
    { value: "join_date,ASC", label: "Join Date (Oldest → Newest)" },
  ], []);

  // UniversalListPage configuration - memoized
  const config = useMemo(() => ({
    entityName: "Customer",
    entityNamePlural: "Customers",
    icon: UserGroupIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Customer",
    routes: {
      search: "/admin/customers/search",
      create: "/admin/customers/add/step-1-search",
      detail: "/admin/customer/:id",
    },
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: HomeIcon
      },
      {
        label: 'Customers',
        icon: UserGroupIcon,
        isActive: true
      }
    ],
    columns,
    statusOptions,
    typeOptions,
    sortOptions,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    searchPlaceholder: "Search customers by name, email, or phone...",
    emptyState: {
      title: "No Customers Found",
      filterDescription: "No customers match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No customers have been added yet.",
      actionLabel: "Add Customer"
    },
    fetchData,
    buildParams,  // UniversalListPage needs this to build the params before calling fetchData
    renderGridItem,
    defaultStatus: String(CUSTOMER_STATUS.ACTIVE),
    defaultType: "0",
    defaultSort: "lexical_name",
    defaultSortOrder: "ASC",
    defaultPageSize: 25,
    defaultViewType: "grid"
  }), [columns, statusOptions, typeOptions, sortOptions, fetchData, buildParams, renderGridItem]);

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

export default AdminCustomerListPage;