// File Path: monorepo/web/frontend/src/pages/Admin/Incident/List/Page.jsx
import React from "react";
import {
  FireIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  HomeIcon,
  CalendarDaysIcon,
} from "@heroicons/react/24/outline";
import {
  UniversalListPage,
  ViewButton,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  INCIDENT_STATUS,
  INCIDENT_SEVERITY,
  INCIDENT_SEVERITY_OPTIONS,
} from "../../../../constants/Incident";
import { INCIDENT_SORT_OPTIONS } from "../../../../constants/FieldOptions";
import { useIncidentManager } from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminIncidentListPage() {
  const incidentManager = useIncidentManager();
  const { getThemeClasses } = useUIXTheme();

  // Helper functions for formatting
  const getStatusDisplay = (status) => {
    switch (status) {
      case INCIDENT_STATUS.OPEN:
        return "Open";
      case INCIDENT_STATUS.CLOSED:
        return "Closed";
      default:
        return "Unknown";
    }
  };

  const getSeverityDisplay = (severity) => {
    switch (severity) {
      case INCIDENT_SEVERITY.LOW:
        return "Low";
      case INCIDENT_SEVERITY.MEDIUM:
        return "Medium";
      case INCIDENT_SEVERITY.HIGH:
        return "High";
      case INCIDENT_SEVERITY.SHOWSTOPPER:
        return "Showstopper";
      default:
        return "Unknown";
    }
  };

  // Get badge component for status
  const getStatusBadge = (status) => {
    const variantMap = {
      [INCIDENT_STATUS.OPEN]: "info",
      [INCIDENT_STATUS.CLOSED]: "default",
    };
    const variant = variantMap[status] || "default";

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

  // Get badge component for severity
  const getSeverityBadge = (severity) => {
    const variantMap = {
      [INCIDENT_SEVERITY.LOW]: "default",
      [INCIDENT_SEVERITY.MEDIUM]: "info",
      [INCIDENT_SEVERITY.HIGH]: "warning",
      [INCIDENT_SEVERITY.SHOWSTOPPER]: "danger",
    };
    const variant = variantMap[severity] || "default";

    return (
      <Badge variant={variant} size="sm">
        {getSeverityDisplay(severity)}
      </Badge>
    );
  };

  // Build params function for the API
  const buildParams = (params) => {
    const {
      pageSize = 50,
      currentPage = 1,
      sortBy,
      sortOrder,
      status,
      type, // UniversalListPage passes the typeOptions filter as 'type'
      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;
    }
    // Map 'type' filter to 'severity' for API
    if (type && type !== "") {
      apiParams.severity = type;
    }

    // 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 incidentManager.getIncidents(
      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/incidents/${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`}
              >
                <FireIcon className="w-5 h-5 mr-2" />
                Incident #
                {incident.public_id || incident.publicId || incident.id}
              </h3>
              {getStatusBadge(incident.status)}
            </div>
            {incident.severity && getSeverityBadge(incident.severity)}
          </div>

          <div
            className={`space-y-2 text-base ${getThemeClasses("text-primary")} mb-4`}
          >
            {incident.title && (
              <div>
                <strong>Title:</strong> {incident.title}
              </div>
            )}
            {incident.description && (
              <div className="line-clamp-2">
                <strong>Description:</strong> {incident.description}
              </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/incidents/${incident.id}`}
              text="View Details"
              fullWidth={true}
            />
          </div>
        </div>
      </div>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "ID",
      accessor: "publicId",
      type: "link",
      linkPath: "/admin/incidents/:id",
      render: (value, row) => (
        <span className="text-lg font-medium">#{value || row.id}</span>
      ),
    },
    {
      header: "Title",
      accessor: "title",
      render: (title) => (
        <span className={getThemeClasses("text-primary")}>{title || "—"}</span>
      ),
    },
    {
      header: "Description",
      accessor: "description",
      render: (description) => (
        <span className={`${getThemeClasses("text-primary")} line-clamp-2`}>
          {description || "—"}
        </span>
      ),
    },
    {
      header: "Severity",
      accessor: "severity",
      render: (severity) =>
        severity ? getSeverityBadge(severity) : <span>—</span>,
    },
    {
      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/incidents/${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" },
  ];

  // Severity filter options (using custom name 'severity' instead of 'type')
  const severityOptions = INCIDENT_SEVERITY_OPTIONS;

  // Sort options (transform from INCIDENT_SORT_OPTIONS)
  const sortOptions = 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: "Incident",
    entityNamePlural: "Incidents",
    icon: FireIcon,
    searchIcon: MagnifyingGlassIcon,
    createIcon: PlusIcon,
    createLabel: "Create Incident",
    showCreateButton: true,
    showSearchButton: false,
    routes: {
      search: "/admin/incidents/search",
      create: "/admin/incidents/create",
      detail: "/admin/incidents/:id",
    },
    breadcrumbItems: [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Incidents",
        icon: FireIcon,
        isActive: true,
      },
    ],
    columns,
    statusOptions,
    typeOptions: severityOptions, // Use custom 'severity' filter as 'type'
    typeFilterLabel: "Severity", // Custom label for the type filter
    sortOptions,
    extendedFilters,
    pageSizeOptions,
    searchPlaceholder:
      "Search incidents by title, description, or other details...",
    emptyState: {
      title: "No Incidents Found",
      filterDescription:
        "No incidents match your current filters. Try adjusting your search criteria.",
      emptyDescription: "No incidents have been reported yet.",
      actionLabel: "Create Incident",
    },
    fetchData,
    buildParams,
    renderGridItem,
    defaultStatus: "",
    defaultType: "", // This will be the severity filter
    defaultSort: "created_at",
    defaultSortOrder: "DESC",
    defaultPageSize: 50,
    defaultViewType: "grid",
    title: "Incident Management",
    subtitle: "Track and manage system incidents and issues",
    showAdvancedSearch: true,
    // Use standard pagination instead of cursor-based
    useCursorPagination: false,
  };

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

export default AdminIncidentListPage;
