// monorepo/web/frontend/src/pages/Admin/Organization/Add/Step5Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import {
  UIXThemeProvider,
  useUIXTheme,
  StaffWizardFormStep,
  FormSection,
  FormRow,
  Input,
  Textarea,
  Checkbox,
  Alert,
  Modal,
  Button,
} from "../../../../components/UIX";
import {
  BuildingOfficeIcon,
  DocumentTextIcon,
  CalendarIcon,
  ChatBubbleBottomCenterTextIcon,
  Cog6ToothIcon,
  TagIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import { TagsMultiSelect } from "../../../../components/business/selects";

// PERFORMANCE: Move constants outside component
const WIZARD_STEPS = [
  { id: 1, title: "Search", subtitle: "Find Org", isActive: false, isCompleted: true },
  { id: 2, title: "Type", subtitle: "Select", isActive: false, isCompleted: true },
  { id: 3, title: "Contact", subtitle: "Information", isActive: false, isCompleted: true },
  { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: true },
  { id: 5, title: "Additional", subtitle: "Extra Info", isActive: true, isCompleted: false },
  { id: 6, title: "Review", subtitle: "Confirm", isActive: false, isCompleted: false },
];

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

function AdminOrganizationAddStep5Page() {
  const navigate = useNavigate();
  const { getThemeClasses } = useUIXTheme();
  const [showCancelWarning, setShowCancelWarning] = useState(false);
  const [errors, setErrors] = useState({});
  const [isInitialized, setIsInitialized] = useState(false);

  // Form states
  const [tags, setTags] = useState([]);
  const [joinDate, setJoinDate] = useState(new Date().toISOString().split("T")[0]);
  const [additionalComment, setAdditionalComment] = useState("");
  const [taxId, setTaxId] = useState("");
  const [registrationNumber, setRegistrationNumber] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [allowOnlineBookings, setAllowOnlineBookings] = useState(false);
  const [requireApprovalForBookings, setRequireApprovalForBookings] = useState(false);

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

  // SECURITY: Load and validate data on mount
  useEffect(() => {
    const initializeData = async () => {
      try {
        // Validate previous steps exist
        const step1Data = sessionStorage.getItem("step1Data");
        const step2Data = sessionStorage.getItem("step2Data");
        const step3Data = sessionStorage.getItem("step3Data");
        const step4Data = sessionStorage.getItem("step4Data");

        if (!step1Data || !step2Data || !step3Data || !step4Data) {
          navigate("/admin/organizations/add/step-1");
          return;
        }

        // Load Step 5 data if exists
        const step5Data = sessionStorage.getItem("step5Data");
        if (step5Data) {
          try {
            const parsed = JSON.parse(step5Data);

            // SECURITY: Sanitize loaded data
            setTags(Array.isArray(parsed.tags) ? parsed.tags : []);
            setJoinDate(parsed.joinDate || new Date().toISOString().split("T")[0]);
            setAdditionalComment(sanitizeInput(parsed.additionalComment || ""));
            setTaxId(sanitizeInput(parsed.taxId || ""));
            setRegistrationNumber(sanitizeInput(parsed.registrationNumber || ""));
            setIsActive(parsed.isActive !== undefined ? Boolean(parsed.isActive) : true);
            setAllowOnlineBookings(Boolean(parsed.allowOnlineBookings));
            setRequireApprovalForBookings(Boolean(parsed.requireApprovalForBookings));
          } catch (error) {
            if (import.meta.env.DEV) {
              console.error("Step 5: Error parsing step data:", error);
            }
          }
        }

        setIsInitialized(true);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Step 5: Initialization error:", error);
        }
        navigate("/admin/organizations/add/step-1");
      }
    };

    initializeData();
  }, [navigate]);

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

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

  const handleConfirmCancel = useCallback(() => {
    setShowCancelWarning(false);
    try {
      sessionStorage.removeItem("step1Data");
      sessionStorage.removeItem("step2Data");
      sessionStorage.removeItem("step3Data");
      sessionStorage.removeItem("step4Data");
      sessionStorage.removeItem("step5Data");
      sessionStorage.removeItem("step6Data");
      sessionStorage.removeItem("WORKERY_ORGANIZATION_CREATION_STATE");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error clearing session storage:", error);
      }
    }
    navigate("/admin/organizations");
  }, [navigate]);

  const handleBack = useCallback(() => {
    // Save current state before going back
    const step5Data = {
      tags,
      joinDate,
      additionalComment: sanitizeInput(additionalComment),
      taxId: sanitizeInput(taxId),
      registrationNumber: sanitizeInput(registrationNumber),
      isActive,
      allowOnlineBookings,
      requireApprovalForBookings,
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step5Data", JSON.stringify(step5Data));
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving step5Data:", error);
      }
    }

    navigate("/admin/organizations/add/step-4");
  }, [
    tags, joinDate, additionalComment, taxId, registrationNumber,
    isActive, allowOnlineBookings, requireApprovalForBookings, navigate
  ]);

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

    // Validate optional fields if provided
    const trimmedTaxId = taxId.trim();
    const trimmedRegNumber = registrationNumber.trim();
    const trimmedComment = additionalComment.trim();

    if (trimmedTaxId && trimmedTaxId.length > 50) {
      newErrors.taxId = "Tax ID is too long (max 50 characters)";
    }

    if (trimmedRegNumber && trimmedRegNumber.length > 50) {
      newErrors.registrationNumber = "Registration number is too long (max 50 characters)";
    }

    if (trimmedComment && trimmedComment.length > 638) {
      newErrors.additionalComment = "Comment is too long (max 638 characters)";
    }

    // Join date validation
    if (!joinDate) {
      newErrors.joinDate = "Join date is required";
    } else {
      const selectedDate = new Date(joinDate);
      const today = new Date();
      today.setHours(0, 0, 0, 0); // Reset time to compare dates only

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

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [taxId, registrationNumber, additionalComment, joinDate]);

  const handleNext = useCallback((e) => {
    e.preventDefault();

    if (!validateForm()) {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }

    // SECURITY: Sanitize data before saving
    const step5Data = {
      tags,
      joinDate,
      additionalComment: sanitizeInput(additionalComment),
      taxId: sanitizeInput(taxId),
      registrationNumber: sanitizeInput(registrationNumber),
      isActive: Boolean(isActive),
      allowOnlineBookings: Boolean(allowOnlineBookings),
      requireApprovalForBookings: Boolean(requireApprovalForBookings),
      timestamp: new Date().toISOString(),
    };

    try {
      sessionStorage.setItem("step5Data", JSON.stringify(step5Data));
      navigate("/admin/organizations/add/step-6");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Step 5: Error saving data:", error);
      }
      setErrors({ message: "Failed to save data. Please try again." });
    }
  }, [
    validateForm, tags, joinDate, additionalComment, taxId, registrationNumber,
    isActive, allowOnlineBookings, requireApprovalForBookings, navigate
  ]);

  // PERFORMANCE: Memoize actions configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Review",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: handleNext,
      disabled: false,
    }
  ], [handleNext]);

  // Show loading state
  if (!isInitialized) {
    return (
      <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} flex items-center justify-center`}>
        <div className="text-center">
          <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}></div>
          <p className={`mt-4 ${themeClasses.textSecondary}`}>Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')} px-4 sm:px-6 lg:px-8`}>
      <div className="max-w-7xl mx-auto py-6 sm:py-8">
        <StaffWizardFormStep
          wizardSteps={WIZARD_STEPS}
          currentStep={5}
          wizardTitle="Add New Organization"
          wizardIcon={BuildingOfficeIcon}
          stepTitle="Additional Information"
          stepSubtitle="Provide extra details and configure settings"
          stepIcon={DocumentTextIcon}
          errors={errors}
          showFormCard={false}
          contentMaxWidth="7xl"
          actions={actions}
          onCancel={handleCancel}
          onBack={handleBack}
          actionLayout="end"
        >
          {/* Error Alert */}
          {Object.keys(errors).length > 0 && errors.message && (
            <Alert
              type="error"
              message={errors.message || "Please correct the errors below before proceeding"}
              className="mb-6"
              dismissible
              onDismiss={() => setErrors({})}
            />
          )}

          {/* Organization Information Section */}
          <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} 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')}`} />
              Organization Information
            </h3>
            <FormSection>
              <FormRow>
                <TagsMultiSelect
                  value={tags}
                  onChange={setTags}
                  error={errors.tags}
                  required={false}
                  label="Tags"
                  placeholder="Select tags to categorize this organization"
                  onUnauthorized={onUnauthorized}
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Tax ID / Business Number"
                  value={taxId}
                  onChange={setTaxId}
                  placeholder="Enter tax ID or business number (optional)"
                  error={errors.taxId}
                  required={false}
                  icon={DocumentTextIcon}
                  maxLength={50}
                  helperText="Organization's tax identification or business registration number"
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Registration Number"
                  value={registrationNumber}
                  onChange={setRegistrationNumber}
                  placeholder="Enter registration number (optional)"
                  error={errors.registrationNumber}
                  required={false}
                  icon={DocumentTextIcon}
                  maxLength={50}
                  helperText="Official registration or license number"
                />
              </FormRow>

              <FormRow>
                <Input
                  label="Join Date"
                  type="date"
                  value={joinDate}
                  onChange={setJoinDate}
                  error={errors.joinDate}
                  required={true}
                  icon={CalendarIcon}
                  helperText="The date this organization joined (defaults to today)"
                />
              </FormRow>

              <FormRow>
                <Textarea
                  label="Additional Comment"
                  value={additionalComment}
                  onChange={setAdditionalComment}
                  placeholder="Enter any additional comments or notes about this organization (optional)"
                  rows={4}
                  maxLength={638}
                  error={errors.additionalComment}
                  required={false}
                  showCharacterCount={true}
                  icon={ChatBubbleBottomCenterTextIcon}
                />
              </FormRow>
            </FormSection>
          </div>

          {/* Organization Settings Section */}
          <div className={`${themeClasses.bgCard} rounded-lg shadow-sm border ${getThemeClasses('border-secondary')} p-6 mb-6`}>
            <h3 className={`text-lg font-semibold ${themeClasses.textPrimary} mb-4 flex items-center`}>
              <Cog6ToothIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-primary')}`} />
              Organization Settings
            </h3>
            <FormSection>
              <FormRow>
                <Checkbox
                  label="Organization is Active"
                  checked={isActive}
                  onChange={setIsActive}
                  helperText="Active organizations can access the system and book services"
                />
              </FormRow>

              <FormRow>
                <Checkbox
                  label="Allow Online Bookings"
                  checked={allowOnlineBookings}
                  onChange={setAllowOnlineBookings}
                  helperText="Enable this organization to make online bookings through the portal"
                />
              </FormRow>

              <FormRow>
                <Checkbox
                  label="Require Approval for Bookings"
                  checked={requireApprovalForBookings}
                  onChange={setRequireApprovalForBookings}
                  helperText="Bookings from this organization require admin approval before confirmation"
                />
              </FormRow>
            </FormSection>
          </div>
        </StaffWizardFormStep>

        {/* Cancel Confirmation Modal */}
        <Modal
          isOpen={showCancelWarning}
          onClose={() => setShowCancelWarning(false)}
          title="Are you sure?"
          footer={
            <div className="flex justify-end space-x-3">
              <Button
                variant="secondary"
                onClick={() => setShowCancelWarning(false)}
              >
                No, Keep Working
              </Button>
              <Button
                variant="danger"
                onClick={handleConfirmCancel}
              >
                Yes, Cancel
              </Button>
            </div>
          }
        >
          <p className={themeClasses.textSecondary}>
            Your Organization record will be cancelled and your work will be
            lost. This cannot be undone. Do you want to continue?
          </p>
        </Modal>
      </div>
    </div>
  );
}

function AdminOrganizationAddStep5PageWrapper() {
  return (
    <UIXThemeProvider>
      <AdminOrganizationAddStep5Page />
    </UIXThemeProvider>
  );
}

export default AdminOrganizationAddStep5PageWrapper;
