// File Path: monorepo/web/frontend/src/pages/Admin/Division/Add/Step5Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  useAuthManager,
  useDivisionWizardStorage,
} from "../../../../services/Services";
import {
  TagIcon,
  CalendarIcon,
  ChatBubbleBottomCenterTextIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
} from "@heroicons/react/24/outline";
import { TagsMultiSelect } from "../../../../components/business/selects";
import {
  StaffWizardFormStep,
  UIXThemeProvider,
  useUIXTheme,
  Input,
  Textarea,
  FormSection,
  FormRow,
  Alert,
} from "../../../../components/UIX";

// PERFORMANCE: Move constants outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Additional" },
  { title: "Review" },
];

// SECURITY: Input sanitization
const sanitizeInput = (input) => {
  if (typeof input !== 'string') return input;
  return input.trim().replace(/[<>]/g, '');
};

// UTILITY: Get today's date in local timezone as YYYY-MM-DD
const getTodayLocalDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

function AdminDivisionAddStep5Page() {
  const authManager = useAuthManager();
  const wizardStorage = useDivisionWizardStorage();
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();

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

  // Personal Information form data
  const [tags, setTags] = useState([]);
  const [joinDate, setJoinDate] = useState(getTodayLocalDate());
  const [additionalComment, setAdditionalComment] = useState("");

  // PERFORMANCE: Memoize theme classes
  const themeClasses = useMemo(() => ({
    textPrimary: getThemeClasses('text-primary'),
    textSecondary: getThemeClasses('text-secondary'),
    bgCard: getThemeClasses('bg-card'),
    borderSecondary: getThemeClasses('border-secondary'),
  }), [getThemeClasses]);

  // PERFORMANCE: Load existing data from wizard storage (run once on mount)
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const step5Data = wizardStorage.getStepData("step5Data");
    if (step5Data) {
      setTags(Array.isArray(step5Data.tags) ? step5Data.tags : []);
      setJoinDate(step5Data.joinDate || getTodayLocalDate());
      setAdditionalComment(sanitizeInput(step5Data.additionalComment || ""));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

  // SECURITY: Enhanced validation function
  const validateForm = useCallback(() => {
    const newErrors = {};

    if (!joinDate) {
      newErrors.joinDate = "Join date is required";
    } else {
      // Validate join date is not in the future
      const selectedDate = new Date(joinDate);
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      if (selectedDate > today) {
        newErrors.joinDate = "Join date cannot be in the future";
      }
    }

    // Validate additional comment length
    const trimmedComment = additionalComment.trim();
    if (trimmedComment && trimmedComment.length > 638) {
      newErrors.additionalComment = "Comment is too long (max 638 characters)";
    }

    return newErrors;
  }, [joinDate, additionalComment]);

  // Handle form submission
  const handleSubmit = useCallback(() => {
    const validationErrors = validateForm();
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }

    setIsLoading(true);
    setErrors({});

    try {
      // SECURITY: Save additional information with sanitization
      const additionalData = {
        tags: Array.isArray(tags) ? tags : [],
        joinDate,
        additionalComment: sanitizeInput(additionalComment),
        timestamp: new Date().toISOString(),
      };

      wizardStorage.saveStepData("step5Data", additionalData);

      // Navigate to next step
      navigate("/admin/divisions/add/step-6");
    } catch (error) {
      setErrors({ submit: error.message || "Failed to save additional information" });
    } finally {
      setIsLoading(false);
    }
  }, [validateForm, tags, joinDate, additionalComment, wizardStorage, navigate]);

  // Handle cancel
  const handleCancel = useCallback(() => {
    wizardStorage.clearWizardData();
    navigate("/admin/divisions");
  }, [wizardStorage, navigate]);

  // Handle previous step
  const handlePrevious = useCallback(() => {
    navigate("/admin/divisions/add/step-4");
  }, [navigate]);

  // PERFORMANCE: Memoize actions
  const actions = useMemo(() => [
    {
      label: "Continue to Review",
      onClick: handleSubmit,
      variant: "primary",
      disabled: isLoading,
      loading: isLoading,
    }
  ], [handleSubmit, isLoading]);

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={WIZARD_STEPS}
        currentStep={5}
        wizardTitle="Add New Division"
        wizardIcon={BuildingOffice2Icon}
        stepTitle="Additional Information"
        stepSubtitle="Enter optional additional details for the division"
        errors={errors}
        isLoading={isLoading}
        showFormCard={false}
        contentMaxWidth="7xl"
        actionLayout="between"
        onBack={handlePrevious}
        onCancel={handleCancel}
        backLabel="Back to Address"
        cancelLabel="Cancel"
        actions={actions}
      >
        {/* Division Classification */}
        <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6 mb-6`}>
          <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
            <TagIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
            Division Classification
          </h3>
          <FormSection>
            <FormRow>
              <TagsMultiSelect
                label="Tags"
                value={tags}
                onChange={setTags}
                onUnauthorized={onUnauthorized}
                placeholder="Select or create tags to categorize this division"
              />
            </FormRow>
          </FormSection>
        </div>

        {/* Join Date */}
        <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6 mb-6`}>
          <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
            <CalendarIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
            Join Date
          </h3>
          <FormSection>
            <FormRow>
              <Input
                label="Join Date"
                type="date"
                value={joinDate}
                onChange={setJoinDate}
                error={errors.joinDate}
                required={true}
                helperText="When did this division join?"
              />
            </FormRow>
          </FormSection>
        </div>

        {/* Additional Comments */}
        <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${themeClasses.borderSecondary} p-6 mb-6`}>
          <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
            <ChatBubbleBottomCenterTextIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
            Additional Comments
          </h3>
          <FormSection>
            <FormRow>
              <Textarea
                label="Additional Notes"
                value={additionalComment}
                onChange={setAdditionalComment}
                error={errors.additionalComment}
                placeholder="Enter any additional information or comments..."
                rows={5}
                maxLength={638}
                showCharacterCount={true}
                helperText="Add any additional notes or comments about this division"
              />
            </FormRow>
          </FormSection>
        </div>

        {/* Information Note */}
        <Alert
          type="info"
          message="Almost done!"
          className="mb-6"
        >
          Review all information on the next step before creating the division.
        </Alert>
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminDivisionAddStep5Page;
