// File: src/pages/Admin/Customer/Update/CustomerFormSections.jsx
// Form section components for Customer Update Page

import React from "react";
import {
  BuildingOfficeIcon,
  UserIcon,
  MapPinIcon,
  ChartPieIcon,
  ComputerDesktopIcon,
} from "@heroicons/react/24/outline";
import {
  Input,
  Select,
  Checkbox,
  DateInput,
  FormSection,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  OrganizationSelect,
  DivisionSelect,
  TagsMultiSelect,
  HowHearAboutUsSelect,
} from "../../../../components/business/selects";
import {
  COMMERCIAL_CUSTOMER_TYPE_OF_ID,
  CLIENT_PHONE_TYPE_WORK,
} from "../../../../constants/Customer";

// Option configurations
const CLIENT_ORGANIZATION_TYPE_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Unknown" },
  { value: 2, label: "Private" },
  { value: 3, label: "Non-profit" },
  { value: 4, label: "Government" },
];

const CLIENT_PHONE_TYPE_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Mobile" },
  { value: 2, label: "Work" },
  { value: 3, label: "Home" },
];

const GENDER_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Other" },
  { value: 2, label: "Male" },
  { value: 3, label: "Female" },
  { value: 4, label: "Transgender" },
  { value: 5, label: "Non-Binary" },
  { value: 6, label: "Two Spirit" },
  { value: 7, label: "Prefer not to say" },
  { value: 8, label: "Do not know" },
];

const REGION_OPTIONS = [
  { value: "AB", label: "Alberta" },
  { value: "BC", label: "British Columbia" },
  { value: "MB", label: "Manitoba" },
  { value: "NB", label: "New Brunswick" },
  { value: "NL", label: "Newfoundland and Labrador" },
  { value: "NT", label: "Northwest Territories" },
  { value: "NS", label: "Nova Scotia" },
  { value: "NU", label: "Nunavut" },
  { value: "ON", label: "Ontario" },
  { value: "PE", label: "Prince Edward Island" },
  { value: "QC", label: "Quebec" },
  { value: "SK", label: "Saskatchewan" },
  { value: "YT", label: "Yukon" },
];

const LANGUAGE_OPTIONS = [
  { value: "English", label: "English" },
  { value: "French", label: "French" },
];

// Calculate max birth date once at module level (today's date)
const MAX_BIRTH_DATE = new Date().toISOString().split("T")[0];

// Organization Section
export const CustomerOrganizationSection = ({ formData, errors, onChange, onUnauthorized }) => (
  <FormSection>
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
      <OrganizationSelect
        value={formData.organizationId}
        onChange={(value) => onChange("organizationId", value)}
        error={errors.organizationId}
        required={false}
        label="Organization"
        onUnauthorized={onUnauthorized}
      />

      <DivisionSelect
        value={formData.divisionId}
        onChange={(value) => onChange("divisionId", value)}
        organizationId={formData.organizationId}
        error={errors.divisionId}
        required={false}
        label="Division"
        onUnauthorized={onUnauthorized}
      />
    </div>
  </FormSection>
);

// Contact Information Section
export const CustomerContactInfoSection = ({ formData, errors, onChange }) => (
  <FormSection>
    {/* Organization fields for commercial customers */}
    {formData.type === COMMERCIAL_CUSTOMER_TYPE_OF_ID && (
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
        <Input
          label="Organization Name"
          value={formData.organizationName}
          onChange={(value) => onChange("organizationName", value)}
          error={errors.organizationName}
          required
        />

        <Select
          label="Organization Type"
          value={formData.organizationType}
          onChange={(value) => onChange("organizationType", parseInt(value))}
          options={CLIENT_ORGANIZATION_TYPE_OPTIONS}
          error={errors.organizationType}
        />
      </div>
    )}

    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
      <Input
        label="First Name"
        value={formData.firstName}
        onChange={(value) => onChange("firstName", value)}
        error={errors.firstName}
        required
      />

      <Input
        label="Last Name"
        value={formData.lastName}
        onChange={(value) => onChange("lastName", value)}
        error={errors.lastName}
        required
      />
    </div>

    <div className="mb-4 sm:mb-6">
      <Input
        label="Email"
        type="email"
        value={formData.email}
        onChange={(value) => onChange("email", value)}
        error={errors.email}
        helperText="Optional - a temporary email will be generated if not provided"
      />
    </div>

    <div className="mb-4 sm:mb-6">
      <Checkbox
        label="I agree to receive electronic email"
        checked={formData.isOkToEmail}
        onChange={() => onChange("isOkToEmail", !formData.isOkToEmail)}
      />
    </div>

    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
      <Input
        label="Phone"
        type="tel"
        value={formData.phone}
        onChange={(value) => onChange("phone", value)}
        error={errors.phone}
        required
      />

      <Select
        label="Phone Type"
        value={formData.phoneType}
        onChange={(value) => onChange("phoneType", parseInt(value))}
        options={CLIENT_PHONE_TYPE_OPTIONS}
        error={errors.phoneType}
      />
    </div>

    {formData.phoneType == CLIENT_PHONE_TYPE_WORK && (
      <div className="mb-4 sm:mb-6">
        <Input
          label="Phone Extension"
          value={formData.phoneExtension}
          onChange={(value) => onChange("phoneExtension", value)}
          error={errors.phoneExtension}
        />
      </div>
    )}

    <div className="mb-4 sm:mb-6">
      <Checkbox
        label="I agree to receive texts to my phone"
        checked={formData.isOkToText}
        onChange={() => onChange("isOkToText", !formData.isOkToText)}
      />
    </div>

    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
      <Input
        label="Other Phone (Optional)"
        type="tel"
        value={formData.otherPhone}
        onChange={(value) => onChange("otherPhone", value)}
        error={errors.otherPhone}
      />

      <Select
        label="Other Phone Type"
        value={formData.otherPhoneType}
        onChange={(value) => onChange("otherPhoneType", parseInt(value))}
        options={CLIENT_PHONE_TYPE_OPTIONS}
        error={errors.otherPhoneType}
      />
    </div>

    {formData.otherPhoneType == CLIENT_PHONE_TYPE_WORK && (
      <div className="mb-4 sm:mb-6">
        <Input
          label="Other Phone Extension"
          value={formData.otherPhoneExtension}
          onChange={(value) => onChange("otherPhoneExtension", value)}
          error={errors.otherPhoneExtension}
        />
      </div>
    )}
  </FormSection>
);

// Address Section
export const CustomerAddressSection = ({ formData, errors, onChange }) => {
  const { getThemeClasses } = useUIXTheme();

  return (
    <FormSection title="Address" icon={MapPinIcon}>
      <div className="mb-4 sm:mb-6">
        <Checkbox
          label="Has billing address different than mailing address"
          checked={formData.hasShippingAddress}
          onChange={() => onChange("hasShippingAddress", !formData.hasShippingAddress)}
        />
      </div>

      <div className={`grid ${formData.hasShippingAddress ? "grid-cols-1 lg:grid-cols-2" : "grid-cols-1"} gap-6 sm:gap-8`}>
        {/* Mailing Address */}
        <div>
          {formData.hasShippingAddress && (
            <h4 className={`text-sm sm:text-base font-medium ${getThemeClasses('text-primary')} mb-3 sm:mb-4`}>
              Mailing Address
            </h4>
          )}

          <div className="space-y-3 sm:space-y-4">
            <Input
              label="Country"
              value={formData.country}
              onChange={(value) => onChange("country", value)}
              error={errors.country}
              required
            />

            <Select
              label="Province/Territory"
              value={formData.region}
              onChange={(value) => onChange("region", value)}
              options={REGION_OPTIONS}
              error={errors.region}
              required
              placeholder="Select province/territory"
            />

            <Input
              label="City"
              value={formData.city}
              onChange={(value) => onChange("city", value)}
              error={errors.city}
              required
            />

            <Input
              label="Address Line 1"
              value={formData.addressLine1}
              onChange={(value) => onChange("addressLine1", value)}
              error={errors.addressLine1}
              required
            />

            <Input
              label="Address Line 2 (Optional)"
              value={formData.addressLine2}
              onChange={(value) => onChange("addressLine2", value)}
              error={errors.addressLine2}
            />

            <Input
              label="Postal Code"
              value={formData.postalCode}
              onChange={(value) => onChange("postalCode", value)}
              error={errors.postalCode}
              required
            />
          </div>
        </div>

        {/* Billing Address */}
        {formData.hasShippingAddress && (
          <div>
            <h4 className={`text-sm sm:text-base font-medium ${getThemeClasses('text-primary')} mb-3 sm:mb-4`}>
              Billing Address
            </h4>

            <div className="space-y-3 sm:space-y-4">
              <Input
                label="Name"
                value={formData.shippingName}
                onChange={(value) => onChange("shippingName", value)}
                placeholder="The name to contact for this shipping address"
                error={errors.shippingName}
                required
              />

              <Input
                label="Phone"
                type="tel"
                value={formData.shippingPhone}
                onChange={(value) => onChange("shippingPhone", value)}
                placeholder="The contact phone number for this shipping address"
                error={errors.shippingPhone}
                required
              />

              <Input
                label="Country"
                value={formData.shippingCountry}
                onChange={(value) => onChange("shippingCountry", value)}
                error={errors.shippingCountry}
                required
              />

              <Select
                label="Province/Territory"
                value={formData.shippingRegion}
                onChange={(value) => onChange("shippingRegion", value)}
                options={REGION_OPTIONS}
                error={errors.shippingRegion}
                required
                placeholder="Select province/territory"
              />

              <Input
                label="City"
                value={formData.shippingCity}
                onChange={(value) => onChange("shippingCity", value)}
                error={errors.shippingCity}
                required
              />

              <Input
                label="Address Line 1"
                value={formData.shippingAddressLine1}
                onChange={(value) => onChange("shippingAddressLine1", value)}
                error={errors.shippingAddressLine1}
                required
              />

              <Input
                label="Address Line 2 (Optional)"
                value={formData.shippingAddressLine2}
                onChange={(value) => onChange("shippingAddressLine2", value)}
                error={errors.shippingAddressLine2}
              />

              <Input
                label="Postal Code"
                value={formData.shippingPostalCode}
                onChange={(value) => onChange("shippingPostalCode", value)}
                error={errors.shippingPostalCode}
                required
              />
            </div>
          </div>
        )}
      </div>
    </FormSection>
  );
};

// Metrics Section
export const CustomerMetricsSection = ({ formData, errors, onChange, onUnauthorized }) => (
  <FormSection title="Metrics" icon={ChartPieIcon}>
    <div className="space-y-4 sm:space-y-6">
      <TagsMultiSelect
        value={formData.tags}
        onChange={(value) => onChange("tags", value)}
        error={errors.tags}
        required={false}
        label="Tags (Optional)"
        helperText="Select tags to categorize this customer"
        onUnauthorized={onUnauthorized}
      />

      <HowHearAboutUsSelect
        value={formData.howDidYouHearAboutUsID}
        onChange={(value) => onChange("howDidYouHearAboutUsID", value)}
        onOtherDetected={(isOther) => {
          onChange("isHowDidYouHearAboutUsOther", isOther);
          if (!isOther) {
            onChange("howDidYouHearAboutUsOther", "");
          }
        }}
        error={errors.howDidYouHearAboutUsID}
        required={true}
        helperText="Tell us how you discovered our organization"
        onUnauthorized={onUnauthorized}
      />

      {formData.isHowDidYouHearAboutUsOther && (
        <Input
          label="How did you hear about us? (Other)"
          value={formData.howDidYouHearAboutUsOther}
          onChange={(value) => onChange("howDidYouHearAboutUsOther", value)}
          error={errors.howDidYouHearAboutUsOther}
          required
        />
      )}

      <DateInput
        label="Join Date"
        value={formData.joinDate}
        onChange={(value) => onChange("joinDate", value)}
        error={errors.joinDate}
        helperText="This indicates when the user joined the workery"
        disabled={false}
        required={true}
      />
    </div>
  </FormSection>
);

// System Information Section
export const CustomerSystemInfoSection = ({ formData, errors, onChange }) => (
  <FormSection title="System Information" icon={ComputerDesktopIcon}>
    <div className="max-w-xl">
      <Select
        label="Preferred Language"
        value={formData.preferredLanguage}
        onChange={(value) => onChange("preferredLanguage", value)}
        options={LANGUAGE_OPTIONS}
        error={errors.preferredLanguage}
      />
    </div>
  </FormSection>
);
