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

import React, { useState, useEffect, useReducer, useCallback, memo } from "react";
import { Link, useNavigate } from "react-router";
import { useAuthManager } from "../../../../../services/Services";
import {
  ComputerDesktopIcon,
  CalendarDaysIcon,
  ClockIcon,
  ArrowLeftIcon,
  ChartBarIcon,
  UserGroupIcon,
  LinkIcon,
  VideoCameraIcon,
  DocumentTextIcon,
  TagIcon,
  ExclamationCircleIcon,
  XMarkIcon,
  UserPlusIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  useUIXTheme,
  Breadcrumb,
  Button,
  Input,
  Select,
  TextArea,
  Alert,
  Modal,
  PageHeader,
  FormCard,
  FormSection,
  Checkbox,
  Spinner,
} from "../../../../../components/UIX";
import {
  EVENT_SECTOR_OPTIONS,
  EVENT_SHSM_OPTIONS,
  FACILITATOR_TIME_OPTIONS,
  DAY_OF_WEEK_OPTIONS,
  EVENT_FIELD_LABELS,
  EVENT_TYPE_VIRTUAL,
} from "../../../../../constants/Event.js";

// Form state reducer for better performance
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;
  }
};

// Initial form state
const initialFormState = {
  // Event Details
  eventName: "",
  description: "",
  partners: "",
  listingURL: "",
  sector: "",
  // Date & Time
  startDate: "",
  dayOfWeek: "",
  startTime: "",
  endTime: "",
  // Virtual Meeting Details
  meetingURL: "",
  meetingPlatform: "",
  meetingID: "",
  accessCode: "",
  dialInNumber: "",
  // Attendees & Facilitators
  attendeeCount: "",
  attendeeCapacity: "",
  facilitatorTime: "",
  facilitatorAM: false,
  facilitatorPM: false,
  // Additional Details
  isSHSM: "",
  skillSetIDs: [],
  tagIDs: [],
  specialRequirements: "",
};

// 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 AdminEventVirtualAddPage() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelWarning, setShowCancelWarning] = useState(false);

  // Form state using reducer for better performance
  const [formData, dispatchFormData] = useReducer(formReducer, initialFormState);

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
  }, [authManager, navigate]);

  // Optimized form field update handler
  const updateField = useCallback((field, value) => {
    dispatchFormData({ type: 'SET_FIELD', field, value });
  }, []);

  // Optimized multiple field update handler
  const updateMultipleFields = useCallback((fields) => {
    dispatchFormData({ type: 'SET_MULTIPLE_FIELDS', fields });
  }, []);

  // Handle form submission
  const onSubmitClick = useCallback(async (e) => {
    e.preventDefault();

    // Basic validation
    const newErrors = {};
    if (!formData.eventName.trim()) newErrors.eventName = "Event name is required";
    if (!formData.startDate) newErrors.startDate = "Start date is required";
    if (!formData.startTime) newErrors.startTime = "Start time is required";
    if (!formData.endTime) newErrors.endTime = "End time is required";
    if (!formData.meetingURL.trim()) newErrors.meetingURL = "Meeting URL is required for virtual events";
    if (!formData.attendeeCapacity) newErrors.attendeeCapacity = "Attendee capacity is required";

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setIsLoading(true);
    setErrors({});

    try {
      const submitData = {
        eventName: formData.eventName.trim(),
        description: formData.description.trim(),
        partners: formData.partners.trim(),
        listingURL: sanitizeURL(formData.listingURL),
        sector: formData.sector,
        type: EVENT_TYPE_VIRTUAL,
        startDate: formData.startDate,
        dayOfWeek: formData.dayOfWeek,
        startTime: formData.startTime,
        endTime: formData.endTime,
        meetingURL: sanitizeURL(formData.meetingURL),
        meetingPlatform: formData.meetingPlatform.trim(),
        meetingID: formData.meetingID.trim(),
        accessCode: formData.accessCode.trim(),
        dialInNumber: formData.dialInNumber.trim(),
        attendeeCount: parseInt(formData.attendeeCount) || 0,
        attendeeCapacity: parseInt(formData.attendeeCapacity),
        facilitatorAM: formData.facilitatorAM,
        facilitatorPM: formData.facilitatorPM,
        isSHSM: formData.isSHSM,
        skillSetIDs: formData.skillSetIDs,
        tagIDs: formData.tagIDs,
        specialRequirements: formData.specialRequirements.trim(),
      };

      // TODO: Implement actual API call
      // await eventManager.createVirtualEvent(submitData);

      // For now, just navigate back
      navigate("/admin/events/virtuals");
    } catch (error) {
      // Log error for debugging but don't expose details to console in production
      if (process.env.NODE_ENV === 'development') {
        console.error("Error creating virtual event:", error);
      }
      setErrors({ general: "Failed to create virtual event. Please try again." });
    } finally {
      setIsLoading(false);
    }
  }, [formData, navigate]);

  // Handle cancel - optimized with useCallback
  const handleCancel = useCallback(() => {
    const hasData = formData.eventName || formData.description || formData.meetingURL || formData.startDate;
    if (hasData) {
      setShowCancelWarning(true);
    } else {
      navigate("/admin/events/virtuals");
    }
  }, [formData.eventName, formData.description, formData.meetingURL, formData.startDate, navigate]);

  // Confirm cancel - optimized with useCallback
  const handleConfirmCancel = useCallback(() => {
    setShowCancelWarning(false);
    navigate("/admin/events/virtuals");
  }, [navigate]);

  return (
    <UIXThemeProvider>
      <AdminEventVirtualAddPageContent
        errors={errors}
        setErrors={setErrors}
        isLoading={isLoading}
        showCancelWarning={showCancelWarning}
        setShowCancelWarning={setShowCancelWarning}
        formData={formData}
        updateField={updateField}
        updateMultipleFields={updateMultipleFields}
        onSubmitClick={onSubmitClick}
        handleCancel={handleCancel}
        handleConfirmCancel={handleConfirmCancel}
      />
    </UIXThemeProvider>
  );
}

// Memoized content component for better performance
const AdminEventVirtualAddPageContent = memo(function AdminEventVirtualAddPageContent({
  errors,
  setErrors,
  isLoading,
  showCancelWarning,
  setShowCancelWarning,
  formData,
  updateField,
  updateMultipleFields,
  onSubmitClick,
  handleCancel,
  handleConfirmCancel,
}) {
  const { getThemeClasses } = useUIXTheme();

  // Breadcrumb items
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: ChartBarIcon,
    },
    {
      label: "Virtual Events",
      to: "/admin/events/virtuals",
      icon: ComputerDesktopIcon,
    },
    {
      label: "Add",
      icon: UserPlusIcon,
    },
  ];

  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">
        {/* UIX Breadcrumb */}
        <Breadcrumb items={breadcrumbItems} className="mb-4 sm:mb-6" />

        {/* UIX Page Header */}
        <PageHeader
          title="Add Virtual Event"
          subtitle="Create a new virtual training event with online meeting details"
          icon={ComputerDesktopIcon}
          className="mb-4 sm:mb-6"
        />

        {/* UIX Alert for Errors */}
        {errors.general && (
          <Alert
            type="error"
            message={errors.general}
            onClose={() => setErrors({ ...errors, general: undefined })}
            className="mb-4 sm:mb-6"
          />
        )}

        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-8">
            <Spinner size="lg" />
            <p className={`mt-4 text-center ${getThemeClasses("text-secondary")}`}>
              Creating virtual event...
            </p>
          </div>
        ) : (
          <form onSubmit={onSubmitClick}>
            {/* Event Details */}
            <FormCard
              title="Event Details"
              icon={DocumentTextIcon}
              className="mb-6"
            >
              <FormSection title="Basic Information">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="md:col-span-2">
                    <Input
                      label={EVENT_FIELD_LABELS.eventName}
                      type="text"
                      value={formData.eventName}
                      onChange={(e) => updateField('eventName', e.target.value)}
                      placeholder="Enter event name"
                      icon={DocumentTextIcon}
                      required
                      error={errors.eventName}
                    />
                  </div>

                  <div className="md:col-span-2">
                    <TextArea
                      label={EVENT_FIELD_LABELS.description}
                      value={formData.description}
                      onChange={(e) => updateField('description', e.target.value)}
                      placeholder="Enter event description"
                      rows={4}
                      error={errors.description}
                    />
                  </div>

                  <Input
                    label={EVENT_FIELD_LABELS.partners}
                    type="text"
                    value={formData.partners}
                    onChange={(e) => updateField('partners', e.target.value)}
                    placeholder="Enter partner organizations"
                    icon={UserGroupIcon}
                    error={errors.partners}
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.listingURL}
                    type="text"
                    prefix="https://"
                    value={formData.listingURL}
                    onChange={(value) => updateField('listingURL', value)}
                    placeholder="example.com/event"
                    error={errors.listingURL}
                  />

                  <Select
                    label="Event Sector"
                    value={formData.sector}
                    onChange={(e) => updateField('sector', e.target.value)}
                    options={EVENT_SECTOR_OPTIONS}
                    placeholder="Select sector"
                    error={errors.sector}
                  />
                </div>
              </FormSection>
            </FormCard>

            {/* Date & Time */}
            <FormCard
              title="Date & Time"
              icon={CalendarDaysIcon}
              className="mb-6"
            >
              <FormSection title="Scheduling">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Input
                    label={EVENT_FIELD_LABELS.startDate}
                    type="date"
                    value={formData.startDate}
                    onChange={(e) => updateField('startDate', e.target.value)}
                    icon={CalendarDaysIcon}
                    required
                    error={errors.startDate}
                  />

                  <Select
                    label={EVENT_FIELD_LABELS.dayOfWeek}
                    value={formData.dayOfWeek}
                    onChange={(e) => updateField('dayOfWeek', e.target.value)}
                    options={DAY_OF_WEEK_OPTIONS}
                    placeholder="Select day"
                    error={errors.dayOfWeek}
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.startTime}
                    type="time"
                    value={formData.startTime}
                    onChange={(e) => updateField('startTime', e.target.value)}
                    icon={ClockIcon}
                    required
                    error={errors.startTime}
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.endTime}
                    type="time"
                    value={formData.endTime}
                    onChange={(e) => updateField('endTime', e.target.value)}
                    icon={ClockIcon}
                    required
                    error={errors.endTime}
                  />
                </div>
              </FormSection>
            </FormCard>

            {/* Virtual Meeting Details */}
            <FormCard
              title="Virtual Meeting Details"
              icon={VideoCameraIcon}
              className="mb-6"
            >
              <FormSection title="Meeting Information">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="md:col-span-2">
                    <Input
                      label="Meeting URL"
                      type="text"
                      prefix="https://"
                      value={formData.meetingURL}
                      onChange={(value) => updateField('meetingURL', value)}
                      placeholder="zoom.us/j/123456789 or teams.microsoft.com/..."
                      required
                      error={errors.meetingURL}
                    />
                  </div>

                  <Input
                    label="Platform"
                    type="text"
                    value={formData.meetingPlatform}
                    onChange={(e) => updateField('meetingPlatform', e.target.value)}
                    placeholder="Zoom, Teams, WebEx, etc."
                    icon={ComputerDesktopIcon}
                    error={errors.meetingPlatform}
                  />

                  <Input
                    label="Meeting ID"
                    type="text"
                    value={formData.meetingID}
                    onChange={(e) => updateField('meetingID', e.target.value)}
                    placeholder="123 456 789"
                    error={errors.meetingID}
                  />

                  <Input
                    label="Access Code/Passcode"
                    type="text"
                    value={formData.accessCode}
                    onChange={(e) => updateField('accessCode', e.target.value)}
                    placeholder="Optional meeting passcode"
                    error={errors.accessCode}
                  />

                  <Input
                    label="Dial-in Number"
                    type="tel"
                    value={formData.dialInNumber}
                    onChange={(e) => updateField('dialInNumber', e.target.value)}
                    placeholder="+1-234-567-8901"
                    error={errors.dialInNumber}
                  />
                </div>

                <Alert
                  type="info"
                  message="Provide complete virtual meeting details to ensure attendees can join successfully. Include backup dial-in options when available."
                  className="mt-6"
                />
              </FormSection>
            </FormCard>

            {/* Attendees & Facilitators */}
            <FormCard
              title="Attendees & Facilitators"
              icon={UserGroupIcon}
              className="mb-6"
            >
              <FormSection title="Capacity & Staff">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Input
                    label={EVENT_FIELD_LABELS.attendeeCount}
                    type="number"
                    value={formData.attendeeCount}
                    onChange={(e) => updateField('attendeeCount', e.target.value)}
                    placeholder="Current registered count"
                    icon={UserGroupIcon}
                    min="0"
                    error={errors.attendeeCount}
                  />

                  <Input
                    label={EVENT_FIELD_LABELS.attendeeCapacity}
                    type="number"
                    value={formData.attendeeCapacity}
                    onChange={(e) => updateField('attendeeCapacity', e.target.value)}
                    placeholder="Maximum attendees"
                    icon={UserGroupIcon}
                    min="1"
                    required
                    error={errors.attendeeCapacity}
                  />

                  <div className="md:col-span-2">
                    <Select
                      label="Facilitator Time Preference"
                      value={formData.facilitatorTime}
                      onChange={(e) => updateField('facilitatorTime', e.target.value)}
                      options={FACILITATOR_TIME_OPTIONS}
                      placeholder="Select time preference"
                      error={errors.facilitatorTime}
                    />
                  </div>

                  <div className="flex items-center space-x-6">
                    <Checkbox
                      label={EVENT_FIELD_LABELS.facilitatorAM}
                      checked={formData.facilitatorAM}
                      onChange={(e) => updateField('facilitatorAM', e.target.checked)}
                    />
                    <Checkbox
                      label={EVENT_FIELD_LABELS.facilitatorPM}
                      checked={formData.facilitatorPM}
                      onChange={(e) => updateField('facilitatorPM', e.target.checked)}
                    />
                  </div>
                </div>
              </FormSection>
            </FormCard>

            {/* Additional Details */}
            <FormCard
              title="Additional Details"
              icon={TagIcon}
              className="mb-6"
            >
              <FormSection title="Classification & Requirements">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Select
                    label={EVENT_FIELD_LABELS.isSHSM}
                    value={formData.isSHSM}
                    onChange={(e) => updateField('isSHSM', e.target.value)}
                    options={EVENT_SHSM_OPTIONS}
                    placeholder="Select SHSM status"
                    error={errors.isSHSM}
                  />

                  <div className="md:col-span-2">
                    <TextArea
                      label="Special Requirements"
                      value={formData.specialRequirements}
                      onChange={(e) => updateField('specialRequirements', e.target.value)}
                      placeholder="Technical requirements, accessibility needs, etc."
                      rows={3}
                      error={errors.specialRequirements}
                    />
                  </div>
                </div>

                <Alert
                  type="info"
                  message="Virtual events may have specific technical requirements. Consider internet bandwidth, device compatibility, and accessibility features."
                  className="mt-6"
                />
              </FormSection>
            </FormCard>

            {/* Form Actions */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mt-6">
              <Button
                type="button"
                variant="secondary"
                onClick={handleCancel}
                icon={XMarkIcon}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="primary"
                icon={UserPlusIcon}
                size="lg"
              >
                Create Virtual Event
              </Button>
            </div>
          </form>
        )}

        {/* Back Link */}
        <div className="mt-6">
          <Link
            to="/admin/events/virtuals"
            className={`inline-flex items-center text-sm ${getThemeClasses("link-primary")}`}
          >
            <ArrowLeftIcon className="w-4 h-4 mr-1" />
            Back to Virtual Events List
          </Link>
        </div>
      </div>

      {/* UIX Cancel Confirmation Modal */}
      <Modal
        isOpen={showCancelWarning}
        onClose={() => setShowCancelWarning(false)}
        title="Are you sure?"
        icon={ExclamationCircleIcon}
      >
        <div className="py-4">
          <p className={`text-sm ${getThemeClasses('text-muted')}`}>
            Your virtual event 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 AdminEventVirtualAddPage;
