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

import React from "react";
import {
  ChartBarIcon,
  BuildingOffice2Icon,
  InformationCircleIcon,
  PencilSquareIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import { useDivisionManager } from "../../../../services/Services";
import { EntityUpdatePage } from "../../../../components/UIX";
import {
  DivisionBasicInfoSection,
  DivisionContactInfoSection,
  DivisionAddressSection,
  DivisionAdditionalInfoSection,
} from "../../../../components/UIX/EntityUpdatePage/examples/DivisionFormSections";
import {
  DIVISION_STATUS,
  DEFAULT_VALUES,
} from "../../../../constants/Division";
import { formatDateForInput } from "../../../../constants/Date";

/**
 * Admin Division Update Page
 * Uses the reusable EntityUpdatePage component
 */
function AdminDivisionUpdatePage() {
  const divisionManager = useDivisionManager();

  // Configuration object for the EntityUpdatePage
  const config = {
    // Basic entity information
    entityName: "Division",
    entityType: "division",
    idParam: "id", // URL parameter name for division ID

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

    // Manager with CRUD operations
    manager: {
      getDetail: (id, onUnauthorized) => divisionManager.getDivisionDetail(id, onUnauthorized),
      update: (id, data, onUnauthorized) => divisionManager.updateDivision(id, data, onUnauthorized),
    },

    // Initial form data structure
    initialFormData: {
      divisionName: "",
      divisionShortName: "",
      divisionType: "",
      organizationId: "",
      organizationName: "",
      country: DEFAULT_VALUES.COUNTRY,
      region: DEFAULT_VALUES.REGION,
      city: "",
      addressLine1: "",
      addressLine2: "",
      postalCode: "",
      hasShippingAddress: false,
      shippingName: "",
      shippingPhone: "",
      shippingCountry: "",
      shippingRegion: "",
      shippingCity: "",
      shippingAddressLine1: "",
      shippingAddressLine2: "",
      shippingPostalCode: "",
      joinDate: "",
      additionalComment: "",
      tags: [],
      status: DIVISION_STATUS.ACTIVE,
      contacts: [{
        firstName: "",
        lastName: "",
        title: "",
        email: "",
        isOkToEmail: false,
        phone: "",
        phoneType: 0,
        phoneExtension: "",
        otherPhone: "",
        otherPhoneType: 0,
        otherPhoneExtension: "",
      }],
    },

    // Form sections to render
    formSections: [
      DivisionBasicInfoSection,
      DivisionContactInfoSection,
      DivisionAddressSection,
      DivisionAdditionalInfoSection,
    ],

    // Custom form validation
    validateForm: (formData) => {
      const newErrors = {};

      if (!formData.divisionName.trim()) {
        newErrors.divisionName = "Division name is required";
      }
      if (!formData.divisionType) {
        newErrors.divisionType = "Division type is required";
      }

      // Validate contacts
      const contacts = formData.contacts || [];
      contacts.forEach((contact, index) => {
        if (!contact.firstName.trim()) {
          newErrors[`contacts[${index}].firstName`] = "First name is required";
        }
        if (!contact.lastName.trim()) {
          newErrors[`contacts[${index}].lastName`] = "Last name is required";
        }
        if (!contact.email.trim()) {
          newErrors[`contacts[${index}].email`] = "Email is required";
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email)) {
          newErrors[`contacts[${index}].email`] = "Invalid email format";
        }
      });

      // Validate address
      if (!formData.country) {
        newErrors.country = "Country is required";
      }
      if (!formData.region) {
        newErrors.region = "Region 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";
      }

      // Validate shipping address if enabled
      if (formData.hasShippingAddress) {
        if (!formData.shippingCountry) {
          newErrors.shippingCountry = "Shipping country is required";
        }
        if (!formData.shippingRegion) {
          newErrors.shippingRegion = "Shipping region 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";
        }
      }

      // Validate join date
      if (!formData.joinDate) {
        newErrors.joinDate = "Join date is required";
      }

      return newErrors;
    },

    // Format data from API response to form data
    formatDataFromResponse: (response) => {
      // Map division type from backend number to frontend string
      const typeMapping = {
        1: "educational",
        2: "corporate",
        3: "non-profit",
        4: "government",
      };
      const divisionType = response.divisionType ? typeMapping[response.divisionType] || "" : "";

      // 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
      }

      return {
        divisionName: response.divisionName || "",
        divisionShortName: response.divisionShortName || "",
        divisionType: divisionType,
        organizationId: response.organizationId || "",
        organizationName: response.organizationName || "",
        country: response.country || DEFAULT_VALUES.COUNTRY,
        region: response.region || DEFAULT_VALUES.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 || "",
        joinDate: formatDateForInput(response.joinDate) || "",
        additionalComment: response.additionalComment || "",
        tags: tags,
        status: response.status || DIVISION_STATUS.ACTIVE,
        contacts: response.contacts && Array.isArray(response.contacts) && response.contacts.length > 0
          ? response.contacts
          : [{
              firstName: "",
              lastName: "",
              title: "",
              email: "",
              isOkToEmail: false,
              phone: "",
              phoneType: 0,
              phoneExtension: "",
              otherPhone: "",
              otherPhoneType: 0,
              otherPhoneExtension: "",
            }],
      };
    },

    // Format form data for API submission
    formatDataForSubmit: (formData, entityId) => {
      // Map division type from frontend string to backend number
      const typeReverseMapping = {
        "educational": 1,
        "corporate": 2,
        "non-profit": 3,
        "government": 4,
      };
      const divisionType = formData.divisionType ? typeReverseMapping[formData.divisionType] || 0 : 0;

      return {
        ...formData,
        id: entityId,
        divisionType: divisionType,
        contacts: formData.contacts || [],
      };
    },

    // Custom breadcrumb items (optional - will use defaults if not provided)
    breadcrumbItems: [
      {
        label: 'Dashboard',
        to: '/admin/dashboard',
        icon: ChartBarIcon,
        hideOnMobile: false,
        mobileLabel: 'Dash'
      },
      {
        label: 'Divisions',
        to: '/admin/divisions',
        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/division/{id}`
      },
      {
        label: "Detail",
        to: `/admin/division/{id}/detail`
      },
      {
        label: "Orders",
        to: `/admin/division/{id}/orders`
      },
      {
        label: "Update",
        isActive: true
      },
      {
        label: "Comments",
        to: `/admin/division/{id}/comments`
      },
      {
        label: "Attachments",
        to: `/admin/division/{id}/attachments`
      },
      {
        label: "More",
        to: `/admin/division/{id}/more`,
        icon: EllipsisHorizontalIcon
      }
    ],
  };

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

export default AdminDivisionUpdatePage;