// File Path: monorepo/web/frontend/src/pages/Admin/Event/InSchool/Add/Page.jsx

import React, {
  useState,
  useEffect,
  useCallback,
  memo,
  useReducer,
} from "react";
import { Link, useNavigate } from "react-router";
import {
  useAuthManager,
  useEventManager,
} from "../../../../../services/Services";
import {
  EVENT_TYPE_ONSITE,
  EVENT_STATUS_ACTIVE,
  EVENT_SHSM_UNSET,
  EVENT_SHSM_OPTIONS,
  EVENT_FIELD_LABELS,
  DAY_OF_WEEK_OPTIONS,
  FACILITATOR_TIME_OPTIONS,
} from "../../../../../constants/Event";
import {
  PlusIcon,
  ArrowRightIcon,
  ChartBarIcon,
  ExclamationCircleIcon,
  AcademicCapIcon,
  CalendarIcon,
  ClockIcon,
  UserGroupIcon,
  TagIcon,
  MapPinIcon,
  CheckIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  useUIXTheme,
  Breadcrumb,
  Button,
  Input,
  Textarea,
  Select,
  Alert,
  Modal,
  PageHeader,
  FormCard,
  FormSection,
  Spinner,
} from "../../../../../components/UIX";
import {
  OrganizationSelect,
  DivisionSelect,
  FacilitatorSelect,
  SkillSetsMultiSelect,
  TagsMultiSelect,
} from "../../../../../components/business";

const initialFormState = {
  organizationId: "",
  divisionId: "",
  eventName: "",
  description: "",
  partners: "",
  listingURL: "",
  startDate: "",
  attendeeCapacity: "",
  dayOfWeek: "",
  startTime: "",
  endTime: "",
  isSHSM: EVENT_SHSM_UNSET,
  facilitatorRequirements: "none",
  facilitatorIds: [],
  skillSetIds: [],
  tagIds: [],
  address: "",
  city: "",
  province: "ON",
  postalCode: "",
  country: "Canada",
};

const formReducer = (state, action) => {
  switch (action.type) {
    case "SET_FIELD":
      return { ...state, [action.field]: action.value };
    case "SET_MULTIPLE_FIELDS":
      return { ...state, ...action.fields };
    case "RESET_FORM":
      return initialFormState;
    default:
      return state;
  }
};

// Security: Sanitize URL to prevent protocol injection
const sanitizeURL = (url) => {
  if (!url || !url.trim()) return "";
  const trimmed = url.trim();
  // Remove any existing protocol (http://, https://, //, etc.)
  const withoutProtocol = trimmed.replace(/^(https?:\/\/|\/\/)/i, "");
  return `https://${withoutProtocol}`;
};

function AdminEventInSchoolAddPage() {
  const authManager = useAuthManager();
  const eventManager = useEventManager();
  const navigate = useNavigate();

  const [formData, dispatch] = useReducer(formReducer, initialFormState);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [validationErrors, setValidationErrors] = useState({});

  const setField = useCallback(
    (field, value) => {
      dispatch({ type: "SET_FIELD", field, value });
      if (validationErrors[field]) {
        setValidationErrors((prev) => ({ ...prev, [field]: "" }));
      }
      setError("");
    },
    [validationErrors],
  );

  const validateForm = useCallback(() => {
    const errors = {};

    if (!formData.organizationId.trim()) {
      errors.organizationId = "Organization is required";
    }

    if (!formData.eventName.trim()) {
      errors.eventName = "Event name is required";
    }

    if (!formData.description.trim()) {
      errors.description = "Description is required";
    }

    if (!formData.startDate.trim()) {
      errors.startDate = "Start date is required";
    }

    if (!formData.attendeeCapacity.trim()) {
      errors.attendeeCapacity = "Attendee capacity is required";
    } else {
      const capacity = parseInt(formData.attendeeCapacity);
      if (isNaN(capacity) || capacity < 1) {
        errors.attendeeCapacity = "Attendee capacity must be a positive number";
      }
    }

    if (!formData.dayOfWeek.trim()) {
      errors.dayOfWeek = "Day of week is required";
    }

    if (!formData.startTime.trim()) {
      errors.startTime = "Start time is required";
    }

    if (!formData.endTime.trim()) {
      errors.endTime = "End time is required";
    }

    if (!formData.address.trim()) {
      errors.address = "Address is required";
    }

    if (!formData.city.trim()) {
      errors.city = "City is required";
    }

    if (!formData.postalCode.trim()) {
      errors.postalCode = "Postal code is required";
    }

    return errors;
  }, [formData]);

  const scrollToFirstError = useCallback(() => {
    const firstErrorField = document.querySelector(".border-red-300");
    if (firstErrorField) {
      firstErrorField.scrollIntoView({ behavior: "smooth", block: "center" });
      firstErrorField.focus();
    }
  }, []);

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();

      const errors = validateForm();
      setValidationErrors(errors);

      if (Object.keys(errors).length > 0) {
        setError("Please correct the errors below");
        setTimeout(scrollToFirstError, 100);
        return;
      }

      setIsLoading(true);
      setError("");
      setSuccess("");

      try {
        const eventData = {
          organizationId: parseInt(formData.organizationId),
          divisionId: formData.divisionId
            ? parseInt(formData.divisionId)
            : null,
          name: formData.eventName.trim(),
          description: formData.description.trim(),
          partners: formData.partners.trim(),
          listingURL: sanitizeURL(formData.listingURL),
          startDate: formData.startDate,
          attendeeCapacity: parseInt(formData.attendeeCapacity),
          dayOfWeek: formData.dayOfWeek,
          startTime: formData.startTime,
          endTime: formData.endTime,
          isSHSM: parseInt(formData.isSHSM),
          type: EVENT_TYPE_ONSITE,
          status: EVENT_STATUS_ACTIVE,
          facilitatorIds: formData.facilitatorIds.map((id) => parseInt(id)),
          skillSetIds: formData.skillSetIds.map((id) => parseInt(id)),
          tagIds: formData.tagIds.map((id) => parseInt(id)),
          address: formData.address.trim(),
          city: formData.city.trim(),
          province: formData.province.trim(),
          postalCode: formData.postalCode.trim().toUpperCase(),
          country: formData.country.trim(),
        };

        const result = await eventManager.createEvent(eventData);

        if (result && result.id) {
          setSuccess("In-School event created successfully!");
          setTimeout(() => {
            navigate(`/admin/events/in-schools/${result.id}`);
          }, 2000);
        } else {
          throw new Error("Failed to create event");
        }
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Error creating in-school event:", err);
        }
        setError(
          err.message ||
            "An error occurred while creating the event. Please try again.",
        );
        setTimeout(scrollToFirstError, 100);
      } finally {
        setIsLoading(false);
      }
    },
    [formData, validateForm, scrollToFirstError, eventManager, navigate],
  );

  const handleCancel = useCallback(() => {
    setShowCancelWarning(true);
  }, []);

  const handleConfirmCancel = useCallback(() => {
    setShowCancelWarning(false);
    navigate("/admin/events/in-schools");
  }, [navigate]);

  useEffect(() => {
    let mounted = true;

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

    return () => {
      mounted = false;
    };
  }, [authManager, navigate]);

  return (
    <UIXThemeProvider>
      <AdminEventInSchoolAddPageContent
        formData={formData}
        setField={setField}
        isLoading={isLoading}
        error={error}
        success={success}
        showCancelWarning={showCancelWarning}
        setShowCancelWarning={setShowCancelWarning}
        setError={setError}
        validationErrors={validationErrors}
        handleSubmit={handleSubmit}
        handleCancel={handleCancel}
        handleConfirmCancel={handleConfirmCancel}
      />
    </UIXThemeProvider>
  );
}

const AdminEventInSchoolAddPageContent = memo(
  function AdminEventInSchoolAddPageContent({
    formData,
    setField,
    isLoading,
    error,
    success,
    showCancelWarning,
    setShowCancelWarning,
    setError,
    validationErrors,
    handleSubmit,
    handleCancel,
    handleConfirmCancel,
  }) {
    const { getThemeClasses } = useUIXTheme();

    const breadcrumbItems = [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: ChartBarIcon,
      },
      {
        label: "In-School Events",
        to: "/admin/events/in-schools",
        icon: AcademicCapIcon,
      },
      {
        label: "Add",
        icon: PlusIcon,
      },
    ];

    if (isLoading) {
      return (
        <div className={`min-h-screen ${getThemeClasses("page-bg")}`}>
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
            <div className="flex flex-col items-center justify-center py-16">
              <Spinner size="lg" />
              <p className={`mt-4 text-center ${getThemeClasses("text-secondary")}`}>
                Creating in-school event...
              </p>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className={`min-h-screen ${getThemeClasses("page-bg")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
          <Breadcrumb items={breadcrumbItems} className="mb-4 sm:mb-6" />

          <PageHeader
            title="Add In-School Event"
            subtitle="Create a new on-site educational event at a school location"
            icon={AcademicCapIcon}
            className="mb-4 sm:mb-6"
          />

          {error && (
            <Alert
              type="error"
              message={error}
              onClose={() => setError("")}
              className="mb-4 sm:mb-6"
            />
          )}

          {success && (
            <Alert type="success" message={success} className="mb-4 sm:mb-6" />
          )}

          <form onSubmit={handleSubmit}>
            {/* Organization & Division */}
            <FormCard
              title="Organization Details"
              icon={UserGroupIcon}
              className="mb-6"
            >
              <FormSection title="Select Organization and Division">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <div>
                    <OrganizationSelect
                      value={formData.organizationId}
                      onChange={(value) => {
                        setField("organizationId", value);
                        setField("divisionId", "");
                      }}
                      error={validationErrors.organizationId}
                      required
                    />
                  </div>
                  <div>
                    <DivisionSelect
                      organizationId={formData.organizationId}
                      value={formData.divisionId}
                      onChange={(value) => setField("divisionId", value)}
                      error={validationErrors.divisionId}
                      disabled={!formData.organizationId}
                    />
                  </div>
                </div>
              </FormSection>
            </FormCard>

            {/* Event Information */}
            <FormCard
              title="Event Information"
              icon={CalendarIcon}
              className="mb-6"
            >
              <FormSection title="Basic Event Details">
                <div className="grid grid-cols-1 gap-6">
                  <Input
                    label={EVENT_FIELD_LABELS.eventName}
                    value={formData.eventName}
                    onChange={(e) => setField("eventName", e.target.value)}
                    error={validationErrors.eventName}
                    required
                    maxLength={255}
                    placeholder="Enter the event name"
                  />

                  <Textarea
                    label={EVENT_FIELD_LABELS.description}
                    value={formData.description}
                    onChange={(e) => setField("description", e.target.value)}
                    error={validationErrors.description}
                    required
                    rows={4}
                    placeholder="Describe the event, its purpose, and what attendees will learn"
                  />

                  <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <Input
                      label={EVENT_FIELD_LABELS.partners}
                      value={formData.partners}
                      onChange={(e) => setField("partners", e.target.value)}
                      placeholder="Partner organizations (optional)"
                    />

                    <Input
                      label={EVENT_FIELD_LABELS.listingURL}
                      type="text"
                      prefix="https://"
                      value={formData.listingURL}
                      onChange={(value) => setField("listingURL", value)}
                      placeholder="example.com/event"
                    />
                  </div>
                </div>
              </FormSection>
            </FormCard>

            {/* Scheduling */}
            <FormCard
              title="Event Scheduling"
              icon={ClockIcon}
              className="mb-6"
            >
              <FormSection title="Date and Time Details">
                <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                  <Input
                    label={EVENT_FIELD_LABELS.startDate}
                    type="date"
                    value={formData.startDate}
                    onChange={(e) => setField("startDate", e.target.value)}
                    error={validationErrors.startDate}
                    required
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.attendeeCapacity}
                    type="number"
                    min="1"
                    max="1000"
                    value={formData.attendeeCapacity}
                    onChange={(e) =>
                      setField("attendeeCapacity", e.target.value)
                    }
                    error={validationErrors.attendeeCapacity}
                    required
                    placeholder="Maximum number of attendees"
                  />

                  <Select
                    label={EVENT_FIELD_LABELS.dayOfWeek}
                    value={formData.dayOfWeek}
                    onChange={(e) => setField("dayOfWeek", e.target.value)}
                    error={validationErrors.dayOfWeek}
                    required
                    options={[
                      { value: "", label: "Select day of week" },
                      ...DAY_OF_WEEK_OPTIONS,
                    ]}
                  />
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
                  <Input
                    label={EVENT_FIELD_LABELS.startTime}
                    type="time"
                    value={formData.startTime}
                    onChange={(e) => setField("startTime", e.target.value)}
                    error={validationErrors.startTime}
                    required
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.endTime}
                    type="time"
                    value={formData.endTime}
                    onChange={(e) => setField("endTime", e.target.value)}
                    error={validationErrors.endTime}
                    required
                  />
                </div>
              </FormSection>
            </FormCard>

            {/* Location Details */}
            <FormCard
              title="Location Details"
              icon={MapPinIcon}
              className="mb-6"
            >
              <FormSection title="School Address Information">
                <div className="grid grid-cols-1 gap-6">
                  <Input
                    label="Street Address"
                    value={formData.address}
                    onChange={(e) => setField("address", e.target.value)}
                    error={validationErrors.address}
                    required
                    placeholder="School street address"
                  />

                  <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <Input
                      label="City"
                      value={formData.city}
                      onChange={(e) => setField("city", e.target.value)}
                      error={validationErrors.city}
                      required
                      placeholder="City"
                    />

                    <Select
                      label="Province"
                      value={formData.province}
                      onChange={(e) => setField("province", e.target.value)}
                      options={[
                        { value: "ON", label: "Ontario" },
                        { value: "QC", label: "Quebec" },
                        { value: "BC", label: "British Columbia" },
                        { value: "AB", label: "Alberta" },
                        { value: "MB", label: "Manitoba" },
                        { value: "SK", label: "Saskatchewan" },
                        { value: "NS", label: "Nova Scotia" },
                        { value: "NB", label: "New Brunswick" },
                        { value: "NL", label: "Newfoundland and Labrador" },
                        { value: "PE", label: "Prince Edward Island" },
                        { value: "YT", label: "Yukon" },
                        { value: "NT", label: "Northwest Territories" },
                        { value: "NU", label: "Nunavut" },
                      ]}
                    />

                    <Input
                      label="Postal Code"
                      value={formData.postalCode}
                      onChange={(e) =>
                        setField("postalCode", e.target.value.toUpperCase())
                      }
                      error={validationErrors.postalCode}
                      required
                      placeholder="K1A 0A6"
                      maxLength={7}
                    />
                  </div>

                  <Input
                    label="Country"
                    value={formData.country}
                    onChange={(e) => setField("country", e.target.value)}
                    placeholder="Canada"
                  />
                </div>
              </FormSection>
            </FormCard>

            {/* Additional Configuration */}
            <FormCard
              title="Additional Configuration"
              icon={TagIcon}
              className="mb-6"
            >
              <FormSection title="SHSM and Requirements">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <Select
                    label={EVENT_FIELD_LABELS.isSHSM}
                    value={String(formData.isSHSM)}
                    onChange={(e) =>
                      setField("isSHSM", parseInt(e.target.value))
                    }
                    options={EVENT_SHSM_OPTIONS}
                  />

                  <Select
                    label="Facilitator Requirements"
                    value={formData.facilitatorRequirements}
                    onChange={(e) =>
                      setField("facilitatorRequirements", e.target.value)
                    }
                    options={FACILITATOR_TIME_OPTIONS}
                  />
                </div>
              </FormSection>

              {formData.facilitatorRequirements !== "none" && (
                <FormSection title="Select Facilitators" className="mt-6">
                  <FacilitatorSelect
                    value={formData.facilitatorIds}
                    onChange={(value) => setField("facilitatorIds", value)}
                    multiple
                    placeholder="Search and select facilitators"
                  />
                </FormSection>
              )}

              <FormSection title="Skills and Tags" className="mt-6">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <SkillSetsMultiSelect
                    label={EVENT_FIELD_LABELS.skillSetIDs}
                    value={formData.skillSetIds}
                    onChange={(value) => setField("skillSetIds", value)}
                    placeholder="Select relevant skill sets"
                  />

                  <TagsMultiSelect
                    label={EVENT_FIELD_LABELS.tagIDs}
                    value={formData.tagIds}
                    onChange={(value) => setField("tagIds", value)}
                    placeholder="Add tags for categorization"
                  />
                </div>
              </FormSection>
            </FormCard>

            {/* Form Actions */}
            <div className="flex flex-col sm:flex-row sm:justify-end gap-3 py-6">
              <Button
                type="button"
                variant="secondary"
                onClick={handleCancel}
                icon={XMarkIcon}
              >
                Cancel
              </Button>

              <Button
                type="submit"
                variant="primary"
                icon={CheckIcon}
                disabled={isLoading}
              >
                {isLoading ? "Creating..." : "Create In-School Event"}
              </Button>
            </div>
          </form>

          <div className="mt-6">
            <Link
              to="/admin/events/in-schools"
              className={`inline-flex items-center text-sm ${getThemeClasses("link-primary")}`}
            >
              <ArrowRightIcon className="w-4 h-4 mr-1 rotate-180" />
              Back to In-School Events
            </Link>
          </div>
        </div>

        <Modal
          isOpen={showCancelWarning}
          onClose={() => setShowCancelWarning(false)}
          title="Are you sure?"
          icon={ExclamationCircleIcon}
        >
          <div className="py-4">
            <p className={`text-sm ${getThemeClasses("text-muted")}`}>
              Your in-school event creation will be cancelled and your work will
              be lost. This cannot be undone. Do you want to continue?
            </p>
          </div>
          <div className="flex flex-col sm:flex-row sm:justify-end gap-3 pt-4">
            <Button
              onClick={() => setShowCancelWarning(false)}
              variant="secondary"
            >
              No, Keep Working
            </Button>
            <Button onClick={handleConfirmCancel} variant="danger">
              Yes, Cancel
            </Button>
          </div>
        </Modal>
      </div>
    );
  },
);

export default AdminEventInSchoolAddPage;
