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

import React, { useState, useEffect, memo } from "react";
import { useNavigate } from "react-router";
import { useIncidentManager, useAuthManager } from "../../../../services/Services";
import {
  INCIDENT_SEVERITY,
  INCIDENT_SEVERITY_OPTIONS,
  INCIDENT_INITIATED_BY,
  INCIDENT_INITIATED_BY_OPTIONS,
  INCIDENT_LIMITS,
} from "../../../../constants/Incident";
import {
  FireIcon,
  PlusCircleIcon,
  CalendarIcon,
  DocumentTextIcon,
  ChartBarIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  Breadcrumb,
  Alert,
  Input,
  Textarea,
  Select,
  Button,
  BackButton,
  useUIXTheme,
} from "../../../../components/UIX";
import OrganizationSelect from "../../../../components/business/selects/OrganizationSelect";
import DivisionSelect from "../../../../components/business/selects/DivisionSelect";
import CustomerSelect from "../../../../components/business/selects/CustomerSelect";
import FacilitatorSelect from "../../../../components/business/selects/FacilitatorSelect";
import SpeakerSelect from "../../../../components/business/selects/SpeakerSelect";
import StaffSelect from "../../../../components/business/selects/StaffSelect";

const AdminIncidentCreatePageContent = memo(function AdminIncidentCreatePageContent() {
  const incidentManager = useIncidentManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [date, setDate] = useState("");
  const [severity, setSeverity] = useState(0);
  const [initiatedBy, setInitiatedBy] = useState(0);
  const [initiatedByOther, setInitiatedByOther] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);

  // Entity selection states
  const [selectedOrganizationId, setSelectedOrganizationId] = useState("");
  const [selectedDivisionId, setSelectedDivisionId] = useState("");
  const [selectedCustomerId, setSelectedCustomerId] = useState("");
  const [selectedFacilitatorId, setSelectedFacilitatorId] = useState("");
  const [selectedSpeakerId, setSelectedSpeakerId] = useState("");
  const [selectedStaffId, setSelectedStaffId] = useState("");

  // For division flow - need to select organization first
  const [divisionOrganizationId, setDivisionOrganizationId] = useState("");

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

  // Handler to clear entity selections when initiatedBy changes
  const handleInitiatedByChange = (value) => {
    setInitiatedBy(value);
    // Clear all entity selections when changing initiatedBy
    setSelectedOrganizationId("");
    setSelectedDivisionId("");
    setSelectedCustomerId("");
    setSelectedFacilitatorId("");
    setSelectedSpeakerId("");
    setSelectedStaffId("");
    setDivisionOrganizationId("");
  };

  // Handle form submission
  const onSubmitClick = async () => {
    if (import.meta.env.DEV) {
      console.log("onSubmitClick: Beginning...");
    }

    // Prepare payload
    const incidentData = {
      title: title.trim(),
      description: description.trim(),
      date: date,
      severity: severity,
      initiatedBy: initiatedBy,
      initiatedByOther: initiatedByOther.trim(),
    };

    // Add entity ID based on initiatedBy value
    if (initiatedBy === INCIDENT_INITIATED_BY.ORGANIZATION && selectedOrganizationId) {
      incidentData.organizationId = selectedOrganizationId;
    } else if (initiatedBy === INCIDENT_INITIATED_BY.DIVISION && selectedDivisionId) {
      incidentData.divisionId = selectedDivisionId;
    } else if (initiatedBy === INCIDENT_INITIATED_BY.CUSTOMER && selectedCustomerId) {
      incidentData.customerId = selectedCustomerId;
    } else if (initiatedBy === INCIDENT_INITIATED_BY.FACILITATOR && selectedFacilitatorId) {
      incidentData.facilitatorId = selectedFacilitatorId;
    } else if (initiatedBy === INCIDENT_INITIATED_BY.SPEAKER && selectedSpeakerId) {
      incidentData.speakerId = selectedSpeakerId;
    } else if (initiatedBy === INCIDENT_INITIATED_BY.STAFF && selectedStaffId) {
      incidentData.staffId = selectedStaffId;
    }

    if (import.meta.env.DEV) {
      console.log("onSubmitClick | payload:", incidentData);
    }

    setIsSubmitting(true);
    setErrors({});

    try {
      const response = await incidentManager.createIncident(
        incidentData,
        onUnauthorized,
      );

      if (import.meta.env.DEV) {
        console.log("AdminIncidentCreatePage: Incident created successfully");
      }

      // Validate response contains ID before redirecting
      if (!response || !response.id) {
        if (import.meta.env.DEV) {
          console.error("AdminIncidentCreatePage: Invalid response - missing ID");
        }
        setErrors({ general: "Incident created but navigation failed. Please refresh the page." });
        setIsSubmitting(false);
        return;
      }

      // Show success message
      setShowSuccessMessage(true);

      // Redirect after 2 seconds to the created incident
      setTimeout(() => {
        navigate(`/admin/incidents/${encodeURIComponent(response.id)}`);
      }, 2000);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error(
          "AdminIncidentCreatePage: Failed to create incident:",
          error,
        );
      }
      setErrors(error);
      window.scrollTo(0, 0);
      setIsSubmitting(false);
    }
  };

  // Check authentication on mount
  useEffect(() => {
    let mounted = true;

    if (mounted) {
      window.scrollTo(0, 0);

      if (!authManager.isAuthenticated()) {
        navigate("/login?unauthorized=true");
        return;
      }
    }

    return () => {
      mounted = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        {/* Breadcrumb */}
        <Breadcrumb
          items={[
            {
              label: "Dashboard",
              to: "/admin/dashboard",
              icon: HomeIcon,
            },
            {
              label: "Incidents",
              to: "/admin/incidents",
              icon: FireIcon,
            },
            {
              label: "New Incident",
              icon: PlusCircleIcon,
              isActive: true,
            },
          ]}
        />

        {/* Success Message */}
        {showSuccessMessage && (
          <div className="mb-6">
            <Alert
              type="success"
              message="Incident created successfully! Redirecting..."
            />
          </div>
        )}

        {/* Page Title */}
        <div className={`mb-6 ${getThemeClasses("bg-card")} rounded-lg shadow-sm p-4 sm:p-6 border ${getThemeClasses("card-border")}`}>
          <div className="flex items-center justify-between">
            <div>
              <h1 className={`text-xl sm:text-2xl font-bold ${getThemeClasses("text-primary")} flex items-center`}>
                <FireIcon className={`w-6 h-6 sm:w-7 sm:h-7 mr-2 sm:mr-3 ${getThemeClasses("text-error")}`} />
                New Incident
              </h1>
              <p className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}>
                Create a new incident report for tracking issues
              </p>
            </div>
          </div>
        </div>

        {/* Main Content Card */}
        <div className={`${getThemeClasses("bg-card")} shadow-lg rounded-lg overflow-hidden border ${getThemeClasses("card-border")}`}>
          <div className={`px-4 sm:px-6 py-4 ${getThemeClasses("bg-gradient-header")} border-b ${getThemeClasses("border-color")}`}>
            <h2 className={`text-base sm:text-lg font-semibold ${getThemeClasses("text-header")} flex items-center`}>
              <PlusCircleIcon className="w-5 h-5 mr-2" />
              New Incident Form
            </h2>
            <p className={`text-xs sm:text-sm ${getThemeClasses("text-header-secondary")} mt-1`}>
              Please fill out all the required fields before submitting
            </p>
          </div>

          <div className="p-4 sm:p-6">
            {/* Error Display */}
            {errors && Object.keys(errors).length > 0 && (
              <div className="mb-6">
                <Alert
                  type="error"
                  message="There were errors with your submission:"
                />
                <ul className={`list-disc list-inside mt-2 text-sm ${getThemeClasses("text-error")}`}>
                  {Object.entries(errors).map(([key, value]) => (
                    <li key={key}>
                      <strong>{key}:</strong> {typeof value === "string" ? value : "Invalid value"}
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* Title Field */}
            <div className="mb-6">
              <Input
                label="Title"
                name="title"
                type="text"
                placeholder="Enter incident title"
                value={title}
                onChange={(value) => setTitle(value)}
                maxLength={INCIDENT_LIMITS.MAX_TITLE_LENGTH}
                error={errors.title}
                required
                icon={DocumentTextIcon}
                helperText={`${title.length}/${INCIDENT_LIMITS.MAX_TITLE_LENGTH} characters`}
              />
            </div>

            {/* Description Field */}
            <div className="mb-6">
              <Textarea
                label="Description"
                name="description"
                placeholder="Describe the incident in detail"
                value={description}
                onChange={(value) => setDescription(value)}
                rows={5}
                maxLength={INCIDENT_LIMITS.MAX_DESCRIPTION_LENGTH}
                error={errors.description}
                required
                helperText={`${description.length}/${INCIDENT_LIMITS.MAX_DESCRIPTION_LENGTH} characters`}
              />
            </div>

            {/* Date Field */}
            <div className="mb-6">
              <Input
                label="Incident Date"
                name="date"
                type="date"
                value={date}
                onChange={(value) => setDate(value)}
                error={errors.date}
                required
                icon={CalendarIcon}
                helperText="The date (without time) this incident occurred"
              />
            </div>

            {/* Severity Field */}
            <div className="mb-6">
              <Select
                label="Severity"
                name="severity"
                value={severity}
                onChange={(value) => setSeverity(parseInt(value))}
                options={INCIDENT_SEVERITY_OPTIONS}
                error={errors.severity}
                required
                helperText="Select the severity level of this incident"
              />
            </div>

            {/* Initiated By Field */}
            <div className="mb-6">
              <Select
                label="Initiated By"
                name="initiatedBy"
                value={initiatedBy}
                onChange={(value) => handleInitiatedByChange(parseInt(value))}
                options={INCIDENT_INITIATED_BY_OPTIONS}
                error={errors.initiatedBy}
                required
                helperText="Select who initiated this incident"
              />
            </div>

            {/* Initiated By Other Field - Only show when "Other" is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.OTHER && (
              <div className="mb-6">
                <Input
                  label="Please Specify Other"
                  name="initiatedByOther"
                  type="text"
                  placeholder="Specify who initiated this incident"
                  value={initiatedByOther}
                  onChange={(value) => setInitiatedByOther(value)}
                  maxLength={200}
                  error={errors.initiatedByOther}
                  required
                  icon={DocumentTextIcon}
                  helperText="Please specify who initiated this incident (required when 'Other' is selected)"
                />
              </div>
            )}

            {/* Organization Select - Show when Organization is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.ORGANIZATION && (
              <div className="mb-6">
                <OrganizationSelect
                  value={selectedOrganizationId}
                  onChange={setSelectedOrganizationId}
                  error={errors.organizationId}
                  required={true}
                  onUnauthorized={onUnauthorized}
                  label="Organization"
                  helperText="Select the organization that initiated this incident"
                />
              </div>
            )}

            {/* Division Select - Show when Division is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.DIVISION && (
              <>
                <div className="mb-6">
                  <OrganizationSelect
                    value={divisionOrganizationId}
                    onChange={(value) => {
                      setDivisionOrganizationId(value);
                      // Clear division selection when organization changes
                      setSelectedDivisionId("");
                    }}
                    error={errors.organizationId}
                    required={true}
                    onUnauthorized={onUnauthorized}
                    label="Organization"
                    helperText="First, select the organization that contains the division"
                  />
                </div>
                <div className="mb-6">
                  <DivisionSelect
                    value={selectedDivisionId}
                    onChange={setSelectedDivisionId}
                    error={errors.divisionId}
                    required={true}
                    onUnauthorized={onUnauthorized}
                    organizationId={divisionOrganizationId}
                    label="Division"
                    helperText="Select the division that initiated this incident"
                  />
                </div>
              </>
            )}

            {/* Customer Select - Show when Customer is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.CUSTOMER && (
              <div className="mb-6">
                <CustomerSelect
                  value={selectedCustomerId}
                  onChange={setSelectedCustomerId}
                  error={errors.customerId}
                  required={true}
                  onUnauthorized={onUnauthorized}
                  label="Customer"
                  helperText="Select the customer that initiated this incident"
                />
              </div>
            )}

            {/* Facilitator Select - Show when Facilitator is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.FACILITATOR && (
              <div className="mb-6">
                <FacilitatorSelect
                  value={selectedFacilitatorId}
                  onChange={setSelectedFacilitatorId}
                  error={errors.facilitatorId}
                  required={true}
                  onUnauthorized={onUnauthorized}
                  label="Facilitator"
                  helperText="Select the facilitator that initiated this incident"
                />
              </div>
            )}

            {/* Speaker Select - Show when Speaker is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.SPEAKER && (
              <div className="mb-6">
                <SpeakerSelect
                  value={selectedSpeakerId}
                  onChange={setSelectedSpeakerId}
                  error={errors.speakerId}
                  required={true}
                  onUnauthorized={onUnauthorized}
                  label="Speaker"
                  helperText="Select the speaker that initiated this incident"
                />
              </div>
            )}

            {/* Staff Select - Show when Staff is selected */}
            {initiatedBy === INCIDENT_INITIATED_BY.STAFF && (
              <div className="mb-6">
                <StaffSelect
                  value={selectedStaffId}
                  onChange={setSelectedStaffId}
                  error={errors.staffId}
                  required={true}
                  onUnauthorized={onUnauthorized}
                  label="Staff"
                  helperText="Select the staff member that initiated this incident"
                />
              </div>
            )}

            {/* Action Buttons */}
            <div className={`flex flex-col sm:flex-row justify-between pt-6 border-t ${getThemeClasses("border-color")} gap-3`}>
              <BackButton to="/admin/incidents" label="Back to Incidents" />

              <Button
                onClick={onSubmitClick}
                disabled={isSubmitting}
                variant="success"
                loading={isSubmitting}
                loadingText="Submitting..."
              >
                Create Incident
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
});

AdminIncidentCreatePageContent.displayName = "AdminIncidentCreatePageContent";

function AdminIncidentCreatePage() {
  return (
    <UIXThemeProvider>
      <AdminIncidentCreatePageContent />
    </UIXThemeProvider>
  );
}

export default AdminIncidentCreatePage;
