// File Path: monorepo/web/frontend/src/pages/Admin/Organization/Update/Page.jsx

import React, { useMemo, useCallback } from "react";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
  PencilSquareIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import { useOrganizationManager } from "../../../../services/Services";
import { EntityUpdatePage } from "../../../../components/UIX";
import {
  OrganizationBasicInfoSection,
  OrganizationContactInfoSection,
  OrganizationAddressSection,
  OrganizationBusinessInfoSection,
  OrganizationAdditionalInfoSection,
} from "../../../../components/UIX/EntityUpdatePage/examples/OrganizationFormSections";

/**
 * Admin Organization Update Page
 * Uses the reusable EntityUpdatePage component
 */
function AdminOrganizationUpdatePage() {
  const organizationManager = useOrganizationManager();

  // Memoize formatDataFromResponse to prevent infinite loops
  const formatDataFromResponse = useCallback((response) => {
    try {
      if (!response) {
        if (process.env.NODE_ENV === 'development') {
          console.error("OrganizationUpdatePage: Response is null or undefined!");
        }
        throw new Error("Response is null or undefined");
      }

      // Transform tags: Use tagIds if available, otherwise extract from tags array
      let tags = [];
      if (response.tagIds && Array.isArray(response.tagIds)) {
        // Backend provides tagIds array directly (snake_case tag_ids becomes camelCase tagIds)
        tags = response.tagIds;
      } else if (response.tags && Array.isArray(response.tags)) {
        // Fallback: extract IDs from tags array of objects
        tags = response.tags.map(tag => {
          // If tag is an object with id field, extract the id
          if (typeof tag === 'object' && tag !== null && tag.id) {
            return tag.id;
          }
          // If tag is already a string (legacy format), use it as-is
          return tag;
        }).filter(id => id); // Remove any null/undefined values
      }

      // Map organization type from number to string
      const typeMapping = {
        1: "educational",
        2: "corporate",
        3: "non-profit",
        4: "government",
      };
      const organizationType = response.organizationType ? typeMapping[response.organizationType] || "" : "";

      const formattedData = {
        organizationName: response.organizationName || "",
        organizationShortName: response.organizationShortName || "",
        organizationType: organizationType,
        name: response.name || "",
        description: response.description || "",
        taxId: response.taxId || "",
        registrationNumber: response.registrationNumber || "",
        website: response.website || "",
        country: response.country || "",
        region: response.region || "",
        city: response.city || "",
        addressLine1: response.addressLine1 || "",
        addressLine2: response.addressLine2 || "",
        postalCode: response.postalCode || "",
        hasShippingAddress: response.hasShippingAddress || false,
        shippingName: response.shippingName || "",
        shippingPhone: response.shippingPhone || "",
        shippingCountry: response.shippingCountry || "",
        shippingRegion: response.shippingRegion || "",
        shippingCity: response.shippingCity || "",
        shippingAddressLine1: response.shippingAddressLine1 || "",
        shippingAddressLine2: response.shippingAddressLine2 || "",
        shippingPostalCode: response.shippingPostalCode || "",
        allowOnlineBookings: response.allowOnlineBookings || false,
        requireApprovalForBookings: response.requireApprovalForBookings || false,
        tags: tags,
        contacts: response.contacts && Array.isArray(response.contacts) && response.contacts.length > 0
          ? response.contacts
          : [{
              firstName: "",
              lastName: "",
              title: "",
              email: "",
              isOkToEmail: true,
              phone: "",
              phoneType: 0,
              phoneExtension: "",
              otherPhone: "",
              otherPhoneType: 0,
              otherPhoneExtension: "",
            }],
      };

      return formattedData;
    } catch (error) {
      if (process.env.NODE_ENV === 'development') {
        console.error("OrganizationUpdatePage: Error formatting response data:", error);
        console.error("OrganizationUpdatePage: Response that caused error:", response);
      }
      // Return the response as-is if formatting fails
      return response;
    }
  }, []);

  // Memoize validateForm to prevent infinite loops
  const validateForm = useCallback((formData) => {
    const newErrors = {};

    if (!formData.organizationName.trim()) {
      newErrors.organizationName = "Organization name is required";
    }
    if (!formData.organizationType.trim()) {
      newErrors.organizationType = "Organization type is required";
    }

    // Validate contacts
    const contacts = formData.contacts || [];
    contacts.forEach((contact, index) => {
      if (!contact.firstName.trim()) {
        newErrors[`contact_${index}_firstName`] = "First name is required";
      }
      if (!contact.lastName.trim()) {
        newErrors[`contact_${index}_lastName`] = "Last name is required";
      }
      if (!contact.email.trim()) {
        newErrors[`contact_${index}_email`] = "Email is required";
      }
      if (!contact.phone.trim()) {
        newErrors[`contact_${index}_phone`] = "Phone is required";
      }
    });

    return newErrors;
  }, []);

  // Memoize formatDataForSubmit to prevent infinite loops
  const formatDataForSubmit = useCallback((formData, entityId) => {
    // Map organization type from string back to number for backend
    const typeMapping = {
      "educational": 1,
      "corporate": 2,
      "non-profit": 3,
      "government": 4,
    };

    const mappedType = typeMapping[formData.organizationType];

    const result = {
      ...formData,
      id: entityId,
      organizationType: mappedType || parseInt(formData.organizationType) || 1,
      contacts: formData.contacts || [],
    };

    return result;
  }, []);

  // Configuration object for the EntityUpdatePage - memoized to prevent infinite loops
  const config = useMemo(() => ({
    // Basic entity information
    entityName: "Organization",
    entityType: "organization",
    idParam: "organizationId", // URL parameter name for organization ID

    // Icons
    icon: BuildingOffice2Icon,
    dashboardIcon: ChartBarIcon,
    detailIcon: InformationCircleIcon,
    updateIcon: PencilSquareIcon,

    // Manager with CRUD operations
    manager: {
      getDetail: async (id, onUnauthorized, options) => {
        try {
          const result = await organizationManager.getOrganizationDetail(id, onUnauthorized);
          return result;
        } catch (error) {
          if (process.env.NODE_ENV === 'development') {
            console.error("Config manager.getDetail error:", error);
          }
          throw error;
        }
      },
      update: (id, data, onUnauthorized) => organizationManager.updateOrganization(id, data, onUnauthorized),
    },

    // Initial form data structure
    initialFormData: {
      organizationName: "",
      organizationShortName: "",
      organizationType: "",
      name: "",
      description: "",
      taxId: "",
      registrationNumber: "",
      website: "",
      country: "",
      region: "",
      city: "",
      addressLine1: "",
      addressLine2: "",
      postalCode: "",
      hasShippingAddress: false,
      shippingName: "",
      shippingPhone: "",
      shippingCountry: "",
      shippingRegion: "",
      shippingCity: "",
      shippingAddressLine1: "",
      shippingAddressLine2: "",
      shippingPostalCode: "",
      allowOnlineBookings: false,
      requireApprovalForBookings: false,
      tags: [],
      contacts: [{
        firstName: "",
        lastName: "",
        title: "",
        email: "",
        isOkToEmail: true,
        phone: "",
        phoneType: 0,
        phoneExtension: "",
        otherPhone: "",
        otherPhoneType: 0,
        otherPhoneExtension: "",
      }],
    },

    // Form sections to render
    formSections: [
      OrganizationBasicInfoSection,
      OrganizationContactInfoSection,
      OrganizationAddressSection,
      OrganizationBusinessInfoSection,
      OrganizationAdditionalInfoSection,
    ],

    // Custom form validation - use memoized function
    validateForm,

    // Format data from API response to form data - use memoized function
    formatDataFromResponse,

    // Format form data for API submission - use memoized function
    formatDataForSubmit,

    // Custom breadcrumb items (optional - will use defaults if not provided)
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: ChartBarIcon,
        hideOnMobile: false,
        mobileLabel: 'Dash'
      },
      {
        label: 'Organizations',
        to: '/admin/organizations',
        icon: BuildingOffice2Icon
      },
      {
        label: 'Detail',
        icon: InformationCircleIcon
      },
      {
        label: 'Update',
        icon: PencilSquareIcon,
        isActive: true
      }
    ],

    // Custom tab items (optional - will use defaults if not provided)
    tabItems: [
      {
        label: "Summary",
        to: `/admin/organization/{organizationId}`
      },
      {
        label: "Full Details",
        to: `/admin/organization/{organizationId}/full`
      },
      {
        label: "Events",
        to: `/admin/organization/{organizationId}/events`
      },
      {
        label: "Update",
        isActive: true
      },
      {
        label: "Comments",
        to: `/admin/organization/{organizationId}/comments`
      },
      {
        label: "Attachments",
        to: `/admin/organization/{organizationId}/attachments`
      },
      {
        label: "More",
        to: `/admin/organization/{organizationId}/more`,
        icon: EllipsisHorizontalIcon
      }
    ],
  }), [organizationManager, validateForm, formatDataFromResponse, formatDataForSubmit]);

  return <EntityUpdatePage config={config} />;
}

export default AdminOrganizationUpdatePage;
