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

import React, { useMemo, useCallback } from "react";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import { useCustomerManager } from "../../../../services/Services";
import { EntityUpdatePage, UIXThemeProvider } from "../../../../components/UIX";
import {
  CustomerOrganizationSection,
  CustomerContactInfoSection,
  CustomerAddressSection,
  CustomerMetricsSection,
  CustomerSystemInfoSection,
} from "./CustomerFormSections";
import {
  COMMERCIAL_CUSTOMER_TYPE_OF_ID,
  RESIDENTIAL_CUSTOMER_TYPE_OF_ID,
} from "../../../../constants/Customer";

// Static configuration constants
const ENTITY_NAME = "Customer";
const ENTITY_TYPE = "customer";
const ID_PARAM = "cid";

// Static initial form data template
const INITIAL_FORM_DATA = Object.freeze({
  type: RESIDENTIAL_CUSTOMER_TYPE_OF_ID,
  organizationId: "",
  divisionId: "",
  organizationName: "",
  organizationType: 0,
  firstName: "",
  lastName: "",
  email: "",
  phone: "",
  phoneType: 0,
  phoneExtension: "",
  otherPhone: "",
  otherPhoneType: 0,
  otherPhoneExtension: "",
  isOkToText: false,
  isOkToEmail: false,
  country: "Canada",
  region: "",
  city: "",
  addressLine1: "",
  addressLine2: "",
  postalCode: "",
  hasShippingAddress: false,
  shippingName: "",
  shippingPhone: "",
  shippingCountry: "Canada",
  shippingRegion: "",
  shippingCity: "",
  shippingAddressLine1: "",
  shippingAddressLine2: "",
  shippingPostalCode: "",
  tags: [],
  howDidYouHearAboutUsID: "",
  isHowDidYouHearAboutUsOther: false,
  howDidYouHearAboutUsOther: "",
  gender: 0,
  genderOther: "",
  birthDate: "",
  joinDate: "",
  preferredLanguage: "English",
});

// Static breadcrumb items
const BREADCRUMB_ITEMS = Object.freeze([
  {
    label: "Dashboard",
    to: "/admin/dashboard",
    icon: ChartBarIcon,
    hideOnMobile: false,
    mobileLabel: "Dash",
  },
  {
    label: "Customers",
    to: "/admin/customers",
    icon: UserGroupIcon,
  },
  {
    label: "Detail",
    icon: InformationCircleIcon,
  },
  {
    label: "Update",
    icon: PencilSquareIcon,
    isActive: true,
  },
]);

// Validation function
const validateForm = (formData) => {
  const newErrors = {};

  if (!formData.firstName?.trim()) {
    newErrors.firstName = "First name is required";
  }
  if (!formData.lastName?.trim()) {
    newErrors.lastName = "Last name is required";
  }
  if (!formData.phone?.trim()) {
    newErrors.phone = "Phone number is required";
  }
  if (!formData.type) {
    newErrors.type = "Customer type is required";
  }

  if (formData.type === COMMERCIAL_CUSTOMER_TYPE_OF_ID) {
    if (!formData.organizationName?.trim()) {
      newErrors.organizationName =
        "Organization name is required for commercial customers";
    }
  }

  if (!formData.country) {
    newErrors.country = "Country is required";
  }
  if (!formData.region?.trim()) {
    newErrors.region = "Province/Territory is required";
  }
  if (!formData.city?.trim()) {
    newErrors.city = "City is required";
  }
  if (!formData.addressLine1?.trim()) {
    newErrors.addressLine1 = "Address is required";
  }
  if (!formData.postalCode?.trim()) {
    newErrors.postalCode = "Postal code is required";
  }

  if (formData.hasShippingAddress) {
    if (!formData.shippingName?.trim()) {
      newErrors.shippingName = "Shipping name is required";
    }
    if (!formData.shippingPhone?.trim()) {
      newErrors.shippingPhone = "Shipping phone is required";
    }
    if (!formData.shippingCountry) {
      newErrors.shippingCountry = "Shipping country is required";
    }
    if (!formData.shippingRegion?.trim()) {
      newErrors.shippingRegion = "Shipping province/territory is required";
    }
    if (!formData.shippingCity?.trim()) {
      newErrors.shippingCity = "Shipping city is required";
    }
    if (!formData.shippingAddressLine1?.trim()) {
      newErrors.shippingAddressLine1 = "Shipping address is required";
    }
    if (!formData.shippingPostalCode?.trim()) {
      newErrors.shippingPostalCode = "Shipping postal code is required";
    }
  }

  if (!formData.howDidYouHearAboutUsID) {
    newErrors.howDidYouHearAboutUsID = "How did you hear about us is required";
  }
  if (
    formData.isHowDidYouHearAboutUsOther &&
    !formData.howDidYouHearAboutUsOther?.trim()
  ) {
    newErrors.howDidYouHearAboutUsOther = "Please specify other option";
  }
  if (formData.gender === 1 && !formData.genderOther?.trim()) {
    newErrors.genderOther = "Please specify other gender";
  }

  return newErrors;
};

// Format response data from API
const formatDataFromResponse = (response) => {
  return {
    type: response.type || RESIDENTIAL_CUSTOMER_TYPE_OF_ID,
    organizationId: response.organizationId || response.organizationID || "",
    divisionId: response.divisionId || response.divisionID || "",
    organizationName: response.organizationName || "",
    organizationType: response.organizationType || 0,
    firstName: response.firstName || "",
    lastName: response.lastName || "",
    email: response.email || "",
    phone: response.phone || "",
    phoneType: response.phoneType || 0,
    phoneExtension: response.phoneExtension || "",
    otherPhone: response.otherPhone || "",
    otherPhoneType: response.otherPhoneType || 0,
    otherPhoneExtension: response.otherPhoneExtension || "",
    isOkToText: response.isOkToText || false,
    isOkToEmail: response.isOkToEmail || false,
    country: response.country || "Canada",
    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 || "Canada",
    shippingRegion: response.shippingRegion || "",
    shippingCity: response.shippingCity || "",
    shippingAddressLine1: response.shippingAddressLine1 || "",
    shippingAddressLine2: response.shippingAddressLine2 || "",
    shippingPostalCode: response.shippingPostalCode || "",
    tags:
      response.tags?.map((tag) => tag.id || tag.value).filter(Boolean) || [],
    howDidYouHearAboutUsID:
      response.howDidYouHearAboutUsId || response.howDidYouHearAboutUsID || "",
    isHowDidYouHearAboutUsOther: response.isHowDidYouHearAboutUsOther || false,
    howDidYouHearAboutUsOther: response.howDidYouHearAboutUsOther || "",
    gender: response.gender || 0,
    genderOther: response.genderOther || "",
    birthDate: response.birthDate || "",
    joinDate: response.joinDate || "",
    preferredLanguage: response.preferredLanguage || "English",
  };
};

// Format data for submission
const formatDataForSubmit = (formData, entityId) => {
  return {
    id: entityId,
    type: formData.type,
    organizationId: formData.organizationId || null,
    divisionId: formData.divisionId || null,
    organizationName: formData.organizationName,
    organizationType: formData.organizationType
      ? parseInt(formData.organizationType)
      : null,
    firstName: formData.firstName,
    lastName: formData.lastName,
    email: formData.email,
    phone: formData.phone,
    phoneType: formData.phoneType ? parseInt(formData.phoneType) : null,
    phoneExtension: formData.phoneExtension,
    otherPhone: formData.otherPhone,
    otherPhoneExtension: formData.otherPhoneExtension,
    otherPhoneType: formData.otherPhoneType
      ? parseInt(formData.otherPhoneType)
      : null,
    isOkToText: formData.isOkToText,
    isOkToEmail: formData.isOkToEmail,
    postalCode: formData.postalCode,
    addressLine1: formData.addressLine1,
    addressLine2: formData.addressLine2,
    city: formData.city,
    region: formData.region,
    country: formData.country,
    hasShippingAddress: formData.hasShippingAddress,
    shippingName: formData.shippingName,
    shippingPhone: formData.shippingPhone,
    shippingCountry: formData.shippingCountry,
    shippingRegion: formData.shippingRegion,
    shippingCity: formData.shippingCity,
    shippingAddressLine1: formData.shippingAddressLine1,
    shippingAddressLine2: formData.shippingAddressLine2,
    shippingPostalCode: formData.shippingPostalCode,
    tags: formData.tags.filter(
      (tag) =>
        tag !== null &&
        tag !== undefined &&
        tag !== "" &&
        tag !== "0" &&
        tag !== 0,
    ),
    gender: formData.gender ? parseInt(formData.gender) : null,
    genderOther: formData.genderOther,
    joinDate: formData.joinDate,
    birthDate: formData.birthDate,
    howDidYouHearAboutUsID: formData.howDidYouHearAboutUsID,
    isHowDidYouHearAboutUsOther: formData.isHowDidYouHearAboutUsOther,
    howDidYouHearAboutUsOther: formData.howDidYouHearAboutUsOther,
    preferredLanguage: formData.preferredLanguage,
  };
};

// Generate tab items based on entityId - module level to prevent recreation
const generateTabItems = (entityId) => [
  {
    label: "Summary",
    to: `/admin/customer/${entityId}`,
  },
  {
    label: "Detail",
    to: `/admin/customer/${entityId}/detail`,
  },
  {
    label: "Update",
    isActive: true,
  },
  {
    label: "Event Orders",
    to: `/admin/customer/${entityId}/event-orders`,
  },
  {
    label: "Comments",
    to: `/admin/customer/${entityId}/comments`,
  },
  {
    label: "Attachments",
    to: `/admin/customer/${entityId}/attachments`,
  },
  {
    label: "More",
    to: `/admin/customer/${entityId}/more`,
    icon: EllipsisHorizontalIcon,
  },
];

function AdminCustomerUpdatePageContent() {
  const customerManager = useCustomerManager();

  // Generate form sections - these are component functions that will receive props from EntityUpdatePage
  const formSections = useMemo(
    () => [
      CustomerOrganizationSection,
      CustomerContactInfoSection,
      CustomerAddressSection,
      CustomerMetricsSection,
      CustomerSystemInfoSection,
    ],
    [],
  );

  // Entity manager with proper method names for EntityUpdatePage
  const entityManager = useMemo(
    () => ({
      getDetail: async (customerId, onUnauthorized) => {
        return await customerManager.getCustomerDetail(
          customerId,
          onUnauthorized,
        );
      },
      update: async (customerId, data, onUnauthorized) => {
        return await customerManager.updateCustomer(
          customerId,
          data,
          onUnauthorized,
        );
      },
    }),
    [customerManager],
  );

  const config = useMemo(
    () => ({
      entityName: ENTITY_NAME,
      entityType: ENTITY_TYPE,
      idParam: ID_PARAM,
      icon: UserGroupIcon,
      manager: entityManager,
      breadcrumbItems: BREADCRUMB_ITEMS,
      generateTabItems,
      formSections,
      initialFormData: INITIAL_FORM_DATA,
      validateForm,
      formatDataForSubmit,
      formatDataFromResponse,
      redirectAfterUpdate: (entityId) => `/admin/customer/${entityId}/detail`,
    }),
    [entityManager, formSections],
  );

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

function AdminCustomerUpdatePage() {
  return (
    <UIXThemeProvider>
      <AdminCustomerUpdatePageContent />
    </UIXThemeProvider>
  );
}

export default AdminCustomerUpdatePage;
