import React from "react";
import {
  CurrencyDollarIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  CalendarIcon,
  BuildingOffice2Icon,
  UserCircleIcon,
  DocumentDuplicateIcon,
  QuestionMarkCircleIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  PAGE_SIZE_OPTIONS,
  ORDER_SORT_OPTIONS,
  ORDER_STATUS_FILTER_OPTIONS,
  ORDER_TYPE_FILTER_OPTIONS,
  DEFAULT_ORDER_LIST_SORT_BY_VALUE,
} from "../../../../constants/FieldOptions";
import {
  ORDER_STATUS_NEW,
  ORDER_STATUS_DECLINED,
  ORDER_STATUS_PENDING,
  ORDER_STATUS_CANCELLED,
  ORDER_STATUS_ONGOING,
  ORDER_STATUS_IN_PROGRESS,
  ORDER_STATUS_COMPLETED_BUT_UNPAID,
  ORDER_STATUS_COMPLETED_AND_PAID,
  ORDER_STATUS_ARCHIVED,
  ORDER_TYPE_UNASSIGNED,
  ORDER_TYPE_RESIDENTIAL,
  ORDER_TYPE_COMMERCIAL,
} from "../../../../constants/Order";
import { useEventOrderManager } from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminFinancialListPage() {
  const eventOrderManager = useEventOrderManager();
  const { getThemeClasses } = useUIXTheme();

  // Helper functions for formatting
  const formatStatus = (statusValue) => {
    switch (statusValue) {
      case ORDER_STATUS_NEW:
        return "New";
      case ORDER_STATUS_DECLINED:
        return "Declined";
      case ORDER_STATUS_PENDING:
        return "Pending";
      case ORDER_STATUS_CANCELLED:
        return "Cancelled";
      case ORDER_STATUS_ONGOING:
        return "Ongoing";
      case ORDER_STATUS_IN_PROGRESS:
        return "In Progress";
      case ORDER_STATUS_COMPLETED_BUT_UNPAID:
        return "Completed but Unpaid";
      case ORDER_STATUS_COMPLETED_AND_PAID:
        return "Completed and Paid";
      case ORDER_STATUS_ARCHIVED:
        return "Archived";
      default:
        return `Unknown (${statusValue})`;
    }
  };

  const formatType = (typeValue) => {
    switch (typeValue) {
      case ORDER_TYPE_UNASSIGNED:
        return "Unassigned";
      case ORDER_TYPE_RESIDENTIAL:
        return "Residential";
      case ORDER_TYPE_COMMERCIAL:
        return "Commercial";
      default:
        return `Unknown (${typeValue})`;
    }
  };

  // Get type icon for order type
  const getTypeIcon = (type) => {
    switch (type) {
      case ORDER_TYPE_COMMERCIAL:
        return <BuildingOffice2Icon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case ORDER_TYPE_RESIDENTIAL:
        return <HomeIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      default:
        return <QuestionMarkCircleIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
    }
  };

  // Get badge component for order type
  const getTypeBadge = (type) => {
    const variantMap = {
      [ORDER_TYPE_COMMERCIAL]: "info",
      [ORDER_TYPE_RESIDENTIAL]: "success",
      [ORDER_TYPE_UNASSIGNED]: "secondary",
    };
    const variant = variantMap[type] || "default";

    return (
      <Badge variant={variant} size="sm">
        {formatType(type)}
      </Badge>
    );
  };

  // Get badge component for order status
  const getStatusBadge = (status) => {
    const variantMap = {
      [ORDER_STATUS_NEW]: "primary",
      [ORDER_STATUS_PENDING]: "warning",
      [ORDER_STATUS_ONGOING]: "warning",
      [ORDER_STATUS_IN_PROGRESS]: "warning",
      [ORDER_STATUS_COMPLETED_AND_PAID]: "success",
      [ORDER_STATUS_COMPLETED_BUT_UNPAID]: "warning",
      [ORDER_STATUS_DECLINED]: "error",
      [ORDER_STATUS_CANCELLED]: "error",
      [ORDER_STATUS_ARCHIVED]: "secondary",
    };
    const variant = variantMap[status] || "default";

    return (
      <Badge variant={variant} size="sm">
        {formatStatus(status)}
      </Badge>
    );
  };

  // Build params function for the API
  const buildParams = (params) => {
    const {
      pageSize = 50,
      currentCursor,
      sortBy,
      sortOrder,
      status,
      type,
      searchQuery,
      startDate,
      endDate,
    } = 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("sort_field", sortBy);
      filtersMap.set("sort_order", sortOrder === "DESC" ? "-1" : "1");
    }

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

    // Add filters only if not 0 (All)
    if (status && status !== "0" && status !== "") {
      filtersMap.set("status", String(status));
    }
    if (type && type !== "0" && type !== "") {
      filtersMap.set("type", String(type));
    }

    // Add date filters if provided
    if (startDate) {
      const date = new Date(startDate);
      filtersMap.set("start_date", date.getTime().toString());
    }
    if (endDate) {
      const date = new Date(endDate);
      filtersMap.set("end_date", date.getTime().toString());
    }

    return filtersMap;
  };

  // Fetch data function
  const fetchData = async (params, onUnauthorized, forceRefresh) => {
    const filtersMap = buildParams(params);
    return await eventOrderManager.getOrdersWithFiltersMap(
      filtersMap,
      onUnauthorized,
      forceRefresh
    );
  };

  // Custom grid item renderer
  const renderGridItem = (order, navigate) => {
    return (
      <div
        key={order.wjid || order.id}
        className={`${getThemeClasses('bg-card')} border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow cursor-pointer`}
        onClick={() => navigate(`/admin/financial/${order.wjid || order.id}`)}
      >
        <div className="p-6">
          <div className="mb-4">
            <div className="flex items-center justify-between mb-2">
              <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')}`}>
                Job #{order.wjid || order.id}
              </h3>
              {getTypeBadge(order.type)}
            </div>
            {getStatusBadge(order.status)}
          </div>

          <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4`}>
            {order.customerName && (
              <div>
                <strong>Client:</strong>{" "}
                <span className={getThemeClasses('link-primary')}>
                  {order.customerName}
                </span>
              </div>
            )}
            {order.facilitatorName && (
              <div>
                <strong>Facilitator:</strong>{" "}
                <span className={getThemeClasses('link-primary')}>
                  {order.facilitatorName}
                </span>
              </div>
            )}
            <div className="flex items-center">
              <CalendarIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
              <span>Start: {formatDateForDisplay(order.startDate)}</span>
            </div>
          </div>

          <div className="flex gap-2">
            <ViewButton
              to={`/admin/financial/${order.wjid || order.id}`}
              text="View Details"
              fullWidth={true}
            />
            {order.status === ORDER_STATUS_COMPLETED_BUT_UNPAID && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  navigate(`/admin/financial/${order.wjid || order.id}/invoice`);
                }}
                className={`inline-flex items-center justify-center px-3 py-2 text-sm font-medium rounded-lg transition-colors ${getThemeClasses('btn-secondary')}`}
                title="Generate Invoice"
              >
                <DocumentDuplicateIcon className="w-4 h-4" />
              </button>
            )}
          </div>
        </div>
      </div>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Type",
      accessor: "type",
      render: (type, order) => (
        <div className="flex items-center">
          {getTypeIcon(type)}
          {getTypeBadge(type)}
        </div>
      )
    },
    {
      header: "Job #",
      accessor: "wjid",
      type: "link",
      linkPath: "/admin/financial/:wjid",
      render: (value, order) => (
        <span className="text-lg font-medium">
          {order.wjid || order.id}
        </span>
      )
    },
    {
      header: "Client",
      accessor: "customerName",
      render: (customerName, order) => {
        if (!customerName) {
          return <span className="text-gray-400 italic">—</span>;
        }
        return (
          <span className={`text-lg ${getThemeClasses('link-primary')}`}>
            {customerName}
          </span>
        );
      }
    },
    {
      header: "Facilitator",
      accessor: "facilitatorName",
      render: (facilitatorName, order) => {
        if (!facilitatorName) {
          return <span className="text-gray-400 italic">—</span>;
        }
        return (
          <span className={`text-lg ${getThemeClasses('link-primary')}`}>
            {facilitatorName}
          </span>
        );
      }
    },
    {
      header: "Assigned Date",
      accessor: "assignmentDate",
      render: (date) => (
        <span className="text-lg">
          {formatDateForDisplay(date)}
        </span>
      )
    },
    {
      header: "Start Date",
      accessor: "startDate",
      render: (date) => (
        <span className="text-lg">
          {formatDateForDisplay(date)}
        </span>
      )
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "center",
      render: (value, order) => (
        <div className="flex items-center justify-center gap-2">
          <ViewButton
            to={`/admin/financial/${order.wjid || order.id}`}
            text="View"
          />
          {order.status === ORDER_STATUS_COMPLETED_BUT_UNPAID && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                window.location.href = `/admin/financial/${order.wjid || order.id}/invoice`;
              }}
              className={`inline-flex items-center px-4 py-2 text-sm font-medium rounded-lg transition-colors ${getThemeClasses('btn-secondary')}`}
            >
              <DocumentDuplicateIcon className="w-4 h-4 mr-1.5" />
              Invoice
            </button>
          )}
        </div>
      )
    }
  ];

  // Extended filters configuration
  const extendedFilters = [
    {
      name: "startDate",
      label: "Start Date",
      type: "date",
      placeholder: "Select start date"
    },
    {
      name: "endDate",
      label: "End Date",
      type: "date",
      placeholder: "Select end date"
    }
  ];

  // Sort options (transform from ORDER_SORT_OPTIONS)
  const sortOptions = ORDER_SORT_OPTIONS.map(option => ({
    value: option.value,
    label: option.label
  }));

  // Status filter options (transform from ORDER_STATUS_FILTER_OPTIONS)
  const statusOptions = ORDER_STATUS_FILTER_OPTIONS.map(option => ({
    value: String(option.value),
    label: option.label
  }));

  // Type filter options (transform from ORDER_TYPE_FILTER_OPTIONS)
  const typeOptions = ORDER_TYPE_FILTER_OPTIONS.map(option => ({
    value: String(option.value),
    label: option.label
  }));

  // UniversalListPage configuration
  const config = {
    entityName: "Financial Record",
    entityNamePlural: "Financial Records",
    icon: CurrencyDollarIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Add Order",
    routes: {
      search: "/admin/orders/search",
      create: "/admin/orders/add/step-1-search",
      detail: "/admin/financial/:wjid",
    },
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: HomeIcon
      },
      {
        label: 'Financials',
        icon: CurrencyDollarIcon,
        isActive: true
      }
    ],
    columns,
    statusOptions,
    typeOptions,
    sortOptions,
    extendedFilters,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    searchPlaceholder: "Search financial records...",
    emptyState: {
      title: "No Financial Records Found",
      filterDescription: "No records match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No financial records have been added yet.",
      actionLabel: "Add First Order"
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: "0",
    defaultType: "0",
    defaultSort: DEFAULT_ORDER_LIST_SORT_BY_VALUE.split(',')[0],
    defaultSortOrder: DEFAULT_ORDER_LIST_SORT_BY_VALUE.split(',')[1] || "DESC",
    defaultPageSize: 50,
    defaultViewType: "grid",
    title: "Financial Management",
    subtitle: "Manage orders, billing, and financial records",
    showAdvancedSearch: true,
  };

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

export default AdminFinancialListPage;