import React from "react";
import {
  FireIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  UserIcon,
  CalendarDaysIcon,
  DocumentTextIcon,
  ShieldExclamationIcon,
  BriefcaseIcon,
  UserGroupIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import { ORDER_INCIDENT_SORT_OPTIONS } from "../../../../constants/FieldOptions";
import { useOrderIncidentManager } from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminOrderIncidentListPage() {
  const orderIncidentManager = useOrderIncidentManager();
  const { getThemeClasses } = useUIXTheme();

  // Status constants
  const INCIDENT_STATUS_OPEN = "open";
  const INCIDENT_STATUS_CLOSED = "closed";

  // Helper functions for formatting
  const getInitiatorDisplay = (initiator) => {
    switch (initiator) {
      case 1:
        return "Client";
      case 2:
        return "Facilitator";
      case 3:
        return "Staff";
      default:
        return "Unknown";
    }
  };

  // Get initiator icon
  const getInitiatorIcon = (initiator) => {
    switch (initiator) {
      case 1:
        return <UserGroupIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case 2:
        return <BriefcaseIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      case 3:
        return <UserIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
      default:
        return <UserIcon className="w-5 h-5 mr-2 flex-shrink-0" />;
    }
  };

  // Get badge component for initiator
  const getInitiatorBadge = (initiator) => {
    const variantMap = {
      1: "info",      // Client
      2: "success",   // Facilitator
      3: "primary",   // Staff
    };
    const variant = variantMap[initiator] || "default";

    return (
      <Badge variant={variant} size="sm">
        {getInitiatorDisplay(initiator)}
      </Badge>
    );
  };

  // Get badge component for status
  const getStatusBadge = (status) => {
    const variantMap = {
      [INCIDENT_STATUS_OPEN]: "warning",
      [INCIDENT_STATUS_CLOSED]: "success",
    };
    const variant = variantMap[status] || "default";

    return (
      <Badge variant={variant} size="sm">
        {status === INCIDENT_STATUS_OPEN ? "Open" : "Closed"}
      </Badge>
    );
  };

  // Build params function for the API
  const buildParams = (params) => {
    const {
      pageSize = 50,
      currentPage = 1,
      sortBy,
      sortOrder,
      status,
      initiator,
      searchQuery,
      createdDateGte,
      createdDateLte,
    } = params || {};

    const apiParams = {
      page: currentPage,
      limit: pageSize,
    };

    // Add sorting
    if (sortBy && sortOrder) {
      apiParams.sortBy = `${sortBy},${sortOrder}`;
    }

    // Add search
    if (searchQuery && searchQuery.trim()) {
      apiParams.search = searchQuery.trim();
    }

    // Add filters
    if (status && status !== "") {
      apiParams.status = status;
    }
    if (initiator && initiator !== "") {
      apiParams.initiator = initiator;
    }

    // Add date filters
    if (createdDateGte) {
      apiParams.createdDateGte = createdDateGte;
    }
    if (createdDateLte) {
      apiParams.createdDateLte = createdDateLte;
    }

    return apiParams;
  };

  // Fetch data function
  const fetchData = async (params, onUnauthorized, forceRefresh) => {
    const apiParams = buildParams(params);
    return await orderIncidentManager.getOrderIncidents(
      apiParams,
      onUnauthorized,
      forceRefresh
    );
  };

  // Custom grid item renderer
  const renderGridItem = (incident, navigate) => {
    return (
      <div
        key={incident.id}
        className={`${getThemeClasses('bg-card')} border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow cursor-pointer`}
        onClick={() => navigate(`/admin/order-incident/${incident.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')} flex items-center`}>
                <ShieldExclamationIcon className="w-5 h-5 mr-2" />
                Incident #{incident.id}
              </h3>
              {getStatusBadge(incident.status)}
            </div>
            {getInitiatorBadge(incident.initiator)}
          </div>

          <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4`}>
            {incident.title && (
              <div>
                <strong>Title:</strong> {incident.title}
              </div>
            )}
            {incident.orderWjid && (
              <div>
                <strong>Order #:</strong> {incident.orderWjid}
              </div>
            )}
            <div className="flex items-center">
              <CalendarDaysIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
              <span>Created: {formatDateForDisplay(incident.createdAt)}</span>
            </div>
          </div>

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

  // Column configuration for DataList
  const columns = [
    {
      header: "ID",
      accessor: "id",
      type: "link",
      linkPath: "/admin/order-incident/:id",
      render: (value) => (
        <span className="text-lg font-medium">#{value}</span>
      )
    },
    {
      header: "Title",
      accessor: "title",
      render: (title) => (
        <span className={getThemeClasses('text-primary')}>
          {title || "—"}
        </span>
      )
    },
    {
      header: "Order #",
      accessor: "orderWjid",
      render: (orderWjid) => (
        <span className={getThemeClasses('text-primary')}>
          {orderWjid || "—"}
        </span>
      )
    },
    {
      header: "Initiator",
      accessor: "initiator",
      render: (initiator, incident) => (
        <div className="flex items-center">
          {getInitiatorIcon(initiator)}
          {getInitiatorBadge(initiator)}
        </div>
      )
    },
    {
      header: "Created Date",
      accessor: "createdAt",
      render: (date) => (
        <div className="flex items-center">
          <CalendarDaysIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
          <span>{formatDateForDisplay(date)}</span>
        </div>
      )
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      render: (value, incident) => (
        <ViewButton
          to={`/admin/order-incident/${incident.id}`}
          text="View Details"
        />
      )
    }
  ];

  // Extended filters configuration
  const extendedFilters = [
    {
      name: "createdDateGte",
      label: "Created From",
      type: "date",
      placeholder: "Select start date"
    },
    {
      name: "createdDateLte",
      label: "Created To",
      type: "date",
      placeholder: "Select end date"
    }
  ];

  // Status filter options
  const statusOptions = [
    { value: "", label: "All Statuses" },
    { value: INCIDENT_STATUS_OPEN, label: "Open" },
    { value: INCIDENT_STATUS_CLOSED, label: "Closed" },
  ];

  // Initiator filter options (using custom name 'initiator' instead of 'type')
  const initiatorOptions = [
    { value: "", label: "All Initiators" },
    { value: "1", label: "Client" },
    { value: "2", label: "Facilitator" },
    { value: "3", label: "Staff" },
  ];

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

  // Page size options
  const pageSizeOptions = [
    { value: 25, label: "25 per page" },
    { value: 50, label: "50 per page" },
    { value: 100, label: "100 per page" },
    { value: 250, label: "250 per page" },
  ];

  // UniversalListPage configuration
  const config = {
    entityName: "Order Incident",
    entityNamePlural: "Order Incidents",
    icon: FireIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Incident",
    routes: {
      search: "/admin/order-incident/search",
      create: "/admin/order-incident/add",
      detail: "/admin/order-incident/:id",
    },
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: HomeIcon
      },
      {
        label: 'Order Incidents',
        icon: FireIcon,
        isActive: true
      }
    ],
    columns,
    statusOptions,
    typeOptions: initiatorOptions, // Use custom 'initiator' filter as 'type'
    sortOptions,
    extendedFilters,
    pageSizeOptions,
    searchPlaceholder: "Search incidents by title, order number, or description...",
    emptyState: {
      title: "No Order Incidents Found",
      filterDescription: "No incidents match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No order incidents have been reported yet.",
      actionLabel: "Create Incident"
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: "",
    defaultType: "", // This will be the initiator filter
    defaultSort: "created_at",
    defaultSortOrder: "DESC",
    defaultPageSize: 50,
    defaultViewType: "grid",
    title: "Order Incident Management",
    subtitle: "Track and manage order-related incidents and issues",
    showAdvancedSearch: true,
    // Custom filter labels
    filterLabels: {
      status: "Status",
      type: "Initiator", // Override the type label to show "Initiator"
    },
    // Use standard pagination instead of cursor-based
    useCursorPagination: false,
  };

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

export default AdminOrderIncidentListPage;