// File Path: monorepo/web/frontend/src/pages/Admin/Incident/Detail/Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  FireIcon,
  InformationCircleIcon,
  ChevronLeftIcon,
  HomeIcon,
  CalendarDaysIcon,
  PencilSquareIcon,
} from "@heroicons/react/24/outline";
import {
  useIncidentManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  INCIDENT_STATUS,
  INCIDENT_SEVERITY,
  INCIDENT_INITIATED_BY,
} from "../../../../constants/Incident";
import {
  DetailLiteView,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminIncidentDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const incidentManager = useIncidentManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [incident, setIncident] = useState({});

  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

  // Fetch incident detail - memoized
  const fetchIncidentDetail = useCallback(
    async (incidentId) => {
      try {
        setFetching(true);
        setErrors({});

        const response = await incidentManager.getIncidentDetail(
          incidentId,
          onUnauthorized,
        );
        setIncident(response);
      } catch (error) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch incident detail:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
      }
    },
    [incidentManager, onUnauthorized],
  );

  // Lifecycle
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    if (id) {
      fetchIncidentDetail(id);
    }
  }, [id, authManager, navigate, fetchIncidentDetail]);

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

  const getSeverityDisplay = useCallback((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";
    }
  }, []);

  const getInitiatedByDisplay = useCallback((initiatedBy) => {
    switch (initiatedBy) {
      case INCIDENT_INITIATED_BY.OTHER:
        return "Other";
      case INCIDENT_INITIATED_BY.ORGANIZATION:
        return "Organization";
      case INCIDENT_INITIATED_BY.DIVISION:
        return "Division";
      case INCIDENT_INITIATED_BY.CUSTOMER:
        return "Customer";
      case INCIDENT_INITIATED_BY.FACILITATOR:
        return "Facilitator";
      case INCIDENT_INITIATED_BY.SPEAKER:
        return "Speaker";
      case INCIDENT_INITIATED_BY.STAFF:
        return "Staff";
      case INCIDENT_INITIATED_BY.END_USER:
        return "End User";
      default:
        return "Unknown";
    }
  }, []);

  // Get entity name and details based on initiatedBy type
  const getEntityDetails = useCallback((incident) => {
    if (!incident.initiatedBy) return null;

    const details = {
      type: getInitiatedByDisplay(incident.initiatedBy),
      name: null,
      id: null,
      additionalInfo: null,
    };

    switch (incident.initiatedBy) {
      case INCIDENT_INITIATED_BY.ORGANIZATION:
        if (incident.organizationName) {
          details.name = incident.organizationName;
          details.id = incident.organizationPublicId;
          if (incident.organizationShortName) {
            details.additionalInfo = `Short Name: ${incident.organizationShortName}`;
          }
        }
        break;

      case INCIDENT_INITIATED_BY.DIVISION:
        if (incident.divisionName) {
          details.name = incident.divisionName;
          details.id = incident.divisionPublicId;
          if (incident.divisionShortName) {
            details.additionalInfo = `Short Name: ${incident.divisionShortName}`;
          }
        }
        break;

      case INCIDENT_INITIATED_BY.CUSTOMER:
        if (incident.customerName) {
          details.name = incident.customerName;
          details.id = incident.customerPublicId;
          const orgInfo = [];
          if (incident.customerOrganizationName) {
            orgInfo.push(`Organization: ${incident.customerOrganizationName}`);
          }
          if (incident.customerDivisionName) {
            orgInfo.push(`Division: ${incident.customerDivisionName}`);
          }
          if (orgInfo.length > 0) {
            details.additionalInfo = orgInfo.join(", ");
          }
        }
        break;

      case INCIDENT_INITIATED_BY.FACILITATOR:
        if (incident.facilitatorName) {
          details.name = incident.facilitatorName;
          details.id = incident.facilitatorPublicId;
          if (incident.facilitatorRepresentitiveOrganizationName) {
            details.additionalInfo = `Organization: ${incident.facilitatorRepresentitiveOrganizationName}`;
          }
        }
        break;

      case INCIDENT_INITIATED_BY.SPEAKER:
        if (incident.speakerName) {
          details.name = incident.speakerName;
          details.id = incident.speakerPublicId;
        }
        break;

      case INCIDENT_INITIATED_BY.STAFF:
        if (incident.staffName) {
          details.name = incident.staffName;
          details.id = incident.staffPublicId;
        }
        break;

      case INCIDENT_INITIATED_BY.OTHER:
        if (incident.initiatedByOther) {
          details.name = incident.initiatedByOther;
        }
        break;

      default:
        break;
    }

    return details;
  }, [getInitiatedByDisplay]);

  // Create status badge
  const getStatusBadge = useCallback((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>
    );
  }, [getStatusDisplay]);

  // Create severity badge
  const getSeverityBadge = useCallback((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>
    );
  }, [getSeverityDisplay]);

  // Configure DetailLiteView props - memoized
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Incidents",
        to: "/admin/incidents",
        icon: FireIcon,
      },
      {
        label: "Detail",
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [],
  );

  const headerConfig = useMemo(
    () => ({
      title: "Incident Details",
      icon: FireIcon,
      loadingText: "Loading incident details...",
      notFoundTitle: "Incident Not Found",
      notFoundMessage:
        "The incident you're looking for doesn't exist or you don't have permission to view it.",
      notFoundAction: {
        label: "Back to Incidents",
        icon: ChevronLeftIcon,
        onClick: () => navigate("/admin/incidents"),
      },
    }),
    [navigate],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: () => navigate("/admin/incidents"),
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: () => navigate(`/admin/incidents/${id}/edit`),
        icon: PencilSquareIcon,
        label: "Edit",
      },
    ],
    [navigate, id],
  );

  const fieldSections = useMemo(
    () => [
      // Primary column sections
      {
        column: "primary",
        className: "mb-4",
        component: (
          <div>
            <h3
              className={`text-2xl font-semibold ${getThemeClasses("text-primary")} flex items-center`}
            >
              <FireIcon className="w-6 h-6 mr-2" />
              Incident #{incident.publicId || incident.id}
            </h3>
            <div className="mt-2 space-x-2">
              {incident.status !== undefined && getStatusBadge(incident.status)}
              {incident.severity && getSeverityBadge(incident.severity)}
            </div>
          </div>
        ),
      },
      {
        column: "primary",
        className: "mb-4",
        component: (
          <div className="space-y-4">
            {incident.title && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Title
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                >
                  {incident.title}
                </p>
              </div>
            )}

            {incident.description && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Description
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1 whitespace-pre-wrap`}
                >
                  {incident.description}
                </p>
              </div>
            )}
          </div>
        ),
      },
      // Secondary column sections
      {
        column: "secondary",
        className: "mb-4",
        component: (
          <div className="space-y-4">
            {incident.date && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Date
                </label>
                <div className="flex items-center mt-1">
                  <CalendarDaysIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span className={`text-base ${getThemeClasses("text-primary")}`}>
                    {formatDateForDisplay(incident.date)}
                  </span>
                </div>
              </div>
            )}

            {incident.initiatedBy !== undefined && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Initiated By
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                >
                  {getInitiatedByDisplay(incident.initiatedBy)}
                </p>
              </div>
            )}

            {(() => {
              const entityDetails = getEntityDetails(incident);
              if (!entityDetails || !entityDetails.name) return null;

              return (
                <div className="space-y-2">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      {entityDetails.type} Details
                    </label>
                    <div className={`mt-1 ${getThemeClasses("bg-hover")} p-3 rounded-lg`}>
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <p className={`text-base font-medium ${getThemeClasses("text-primary")}`}>
                            {entityDetails.name}
                          </p>
                          {entityDetails.id && (
                            <p className={`text-sm ${getThemeClasses("text-muted")} mt-1`}>
                              ID: {entityDetails.id}
                            </p>
                          )}
                          {entityDetails.additionalInfo && (
                            <p className={`text-sm ${getThemeClasses("text-secondary")} mt-1`}>
                              {entityDetails.additionalInfo}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })()}

            {incident.createdAt && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Created At
                </label>
                <div className="flex items-center mt-1">
                  <CalendarDaysIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span className={`text-base ${getThemeClasses("text-primary")}`}>
                    {formatDateForDisplay(incident.createdAt)}
                  </span>
                </div>
              </div>
            )}

            {incident.modifiedAt && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Last Modified
                </label>
                <div className="flex items-center mt-1">
                  <CalendarDaysIcon
                    className={`w-5 h-5 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <span className={`text-base ${getThemeClasses("text-primary")}`}>
                    {formatDateForDisplay(incident.modifiedAt)}
                  </span>
                </div>
              </div>
            )}
          </div>
        ),
      },
    ],
    [
      incident,
      getStatusBadge,
      getSeverityBadge,
      getInitiatedByDisplay,
      getEntityDetails,
      getThemeClasses,
    ],
  );

  // Early returns AFTER all hooks
  if (!authManager.isAuthenticated()) {
    return (
      <DetailLiteView
        isLoading={true}
        headerConfig={{
          loadingText: "Checking authentication...",
        }}
      />
    );
  }

  if (isFetching && !incident.id) {
    return (
      <DetailLiteView
        isLoading={isFetching}
        headerConfig={{
          loadingText: "Loading incident details...",
        }}
      />
    );
  }

  return (
    <DetailLiteView
      entityData={incident}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching}
      error={
        errors && typeof errors === "object" && Object.keys(errors).length > 0
          ? Object.entries(errors)
              .map(
                ([key, value]) =>
                  `${key}: ${Array.isArray(value) ? value.join(", ") : value}`,
              )
              .join("; ")
          : null
      }
      onErrorClose={() => setErrors({})}
    />
  );
}

export default AdminIncidentDetailPage;
