// File Path: monorepo/web/frontend/src/pages/Admin/Customer/Detail/FullPage.jsx

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UserIcon,
  InformationCircleIcon,
  ChevronLeftIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  PhoneIcon,
  EnvelopeIcon,
  MapPinIcon,
  CalendarIcon,
  ShieldExclamationIcon,
  PencilSquareIcon,
  HomeIcon,
  NoSymbolIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import {
  useCustomerManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  DetailFullView,
  InfoCard,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_ORGANIZATION_TYPE_LABELS,
  CUSTOMER_STATUS,
} from "../../../../constants/Customer";
import { formatDateTime } from "../../../../services/Helpers/DateFormatter";
import {
  HowHearAboutUsDisplay,
  TagsDisplay,
} from "../../../../components/business/displays";

// Helper function to get customer display name
const getCustomerDisplayName = (customer) => {
  if (!customer) return "Customer";
  if (customer.name) return customer.name;
  if (customer.organizationName) return customer.organizationName;
  const fullName =
    `${customer.firstName || ""} ${customer.lastName || ""}`.trim();
  return fullName || "Customer";
};

// Create status badge component
const createStatusBadge = (customer) => {
  if (!customer) return null;
  if (customer.isBanned) {
    return (
      <Badge variant="error" size="sm">
        <ShieldExclamationIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
        Banned
      </Badge>
    );
  }
  if (customer.status === CUSTOMER_STATUS.ACTIVE) {
    return (
      <Badge variant="primary" size="sm">
        <CheckCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
        Active
      </Badge>
    );
  }
  return (
    <Badge variant="secondary" size="sm">
      <ArchiveBoxIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
      Archived
    </Badge>
  );
};

// Static breadcrumb configuration
const BREADCRUMB_ITEMS = [
  {
    label: "Dashboard",
    to: "/admin/dashboard",
    icon: HomeIcon,
  },
  {
    label: "Customers",
    to: "/admin/customers",
    icon: UserIcon,
  },
  {
    label: "Full Details",
    icon: InformationCircleIcon,
    isActive: true,
  },
];

// Static alerts configuration
const ALERTS = {
  archived: {
    message: "This customer is archived",
    icon: ArchiveBoxIcon,
  },
  banned: {
    message: "This customer is banned",
    icon: NoSymbolIcon,
  },
};

function AdminCustomerDetailFullPage() {
  const { cid } = useParams();
  const navigate = useNavigate();
  const customerManager = useCustomerManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [customer, setCustomer] = useState(null);

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

  // Fetch customer detail
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const fetchCustomerDetail = async () => {
      if (!cid) {
        setErrors({ general: "Customer ID is required" });
        setFetching(false);
        return;
      }

      try {
        setFetching(true);
        setErrors({});

        const response = await customerManager.getCustomerDetail(
          cid,
          onUnauthorized,
        );
        setCustomer(response);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Failed to fetch customer detail:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
      }
    };

    fetchCustomerDetail();
  }, [cid, customerManager, authManager, navigate, onUnauthorized]);

  const handleBackToCustomers = useCallback(() => {
    navigate("/admin/customers");
  }, [navigate]);

  const handleEditCustomer = useCallback(() => {
    navigate(`/admin/customer/${cid}/edit`);
  }, [navigate, cid]);

  const headerConfig = useMemo(
    () => ({
      title: "Customer - Full Details",
      icon: UserIcon,
      loadingText: "Loading customer details...",
      notFoundTitle: "Customer Not Found",
      notFoundMessage:
        "The customer you're looking for doesn't exist or you don't have permission to view it.",
      notFoundAction: {
        label: "Back to Customers",
        icon: ChevronLeftIcon,
        onClick: handleBackToCustomers,
      },
    }),
    [handleBackToCustomers],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: handleBackToCustomers,
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: handleEditCustomer,
        icon: PencilSquareIcon,
        label: "Edit",
      },
    ],
    [handleBackToCustomers, handleEditCustomer],
  );

  const tabs = useMemo(
    () => [
      {
        label: "Summary",
        to: `/admin/customer/${cid}`,
      },
      {
        label: "Detail",
        isActive: true,
      },
      {
        label: "Event Orders",
        to: `/admin/customer/${cid}/event-orders`,
      },
      {
        label: "Comments",
        to: `/admin/customer/${cid}/comments`,
      },
      {
        label: "Attachments",
        to: `/admin/customer/${cid}/attachments`,
      },
      {
        label: "More",
        to: `/admin/customer/${cid}/more`,
        icon: EllipsisHorizontalIcon,
      },
    ],
    [cid],
  );

  const mainInfoCard = useMemo(
    () => ({
      title: "Customer Information",
      icon: UserIcon,
      primarySections: [
        {
          component: (
            <div className="space-y-4">
              <div>
                <h3
                  className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}
                >
                  {getCustomerDisplayName(customer)}
                </h3>
                <div
                  className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")}`}
                >
                  {createStatusBadge(customer)}
                </div>
              </div>

              {customer?.email && (
                <div
                  className={`flex items-center ${getThemeClasses("text-primary")}`}
                >
                  <EnvelopeIcon className="w-4 h-4 mr-2" />
                  <a
                    href={`mailto:${customer.email}`}
                    className={`${getThemeClasses("link")}`}
                  >
                    {customer.email}
                  </a>
                </div>
              )}

              {customer?.phone && (
                <div
                  className={`flex items-center ${getThemeClasses("text-primary")}`}
                >
                  <PhoneIcon className="w-4 h-4 mr-2" />
                  <a
                    href={`tel:${customer.phone}`}
                    className={`${getThemeClasses("link")}`}
                  >
                    {customer.phone}
                    {customer.phoneExtension &&
                      ` ext. ${customer.phoneExtension}`}
                  </a>
                </div>
              )}

              {customer?.otherPhone && (
                <div
                  className={`flex items-center ${getThemeClasses("text-primary")}`}
                >
                  <PhoneIcon className="w-4 h-4 mr-2" />
                  <span>Other: </span>
                  <a
                    href={`tel:${customer.otherPhone}`}
                    className={`${getThemeClasses("link")} ml-1`}
                  >
                    {customer.otherPhone}
                    {customer.otherPhoneExtension &&
                      ` ext. ${customer.otherPhoneExtension}`}
                  </a>
                </div>
              )}
            </div>
          ),
        },
      ],
      secondarySections: [
        {
          component: (
            <div className="space-y-4">
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Type
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                >
                  {CUSTOMER_TYPE_LABELS[customer?.type] ||
                    customer?.type ||
                    "Not specified"}
                </p>
              </div>

              {customer?.organizationName && (
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                  >
                    Organization
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                  >
                    {customer.organizationName}
                  </p>
                </div>
              )}

              {customer?.organizationType && (
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                  >
                    Organization Type
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                  >
                    {CUSTOMER_ORGANIZATION_TYPE_LABELS[
                      customer.organizationType
                    ] || customer.organizationType}
                  </p>
                </div>
              )}

              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Created
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1 flex items-center`}
                >
                  <CalendarIcon className="w-4 h-4 mr-1" />
                  {formatDateTime(customer?.createdAt)}
                </p>
              </div>
            </div>
          ),
        },
      ],
    }),
    [customer],
  ); // eslint-disable-line react-hooks/exhaustive-deps -- getThemeClasses intentionally excluded to prevent infinite loop

  const contentSections = useMemo(
    () => [
      {
        type: "infoCard",
        title: "Address Information",
        icon: MapPinIcon,
        primarySections: [
          {
            component: customer && (
              <div className="space-y-3">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                  >
                    Street Address
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                  >
                    {customer.addressLine1 || "Not provided"}
                  </p>
                  {customer.addressLine2 && (
                    <p
                      className={`text-base ${getThemeClasses("text-primary")}`}
                    >
                      {customer.addressLine2}
                    </p>
                  )}
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      City
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                    >
                      {customer.city || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      Province/State
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                    >
                      {customer.region || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                    >
                      Postal Code
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                    >
                      {customer.postalCode || "Not provided"}
                    </p>
                  </div>
                </div>

                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                  >
                    Country
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                  >
                    {customer.country || "Not provided"}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Additional Information",
        icon: InformationCircleIcon,
        primarySections: [
          {
            component: customer && (
              <div className="space-y-4">
                <HowHearAboutUsDisplay
                  value={customer.howHearAboutUsId}
                  onUnauthorized={onUnauthorized}
                />

                <TagsDisplay
                  values={customer.tags?.map((tag) => tag.id) || []}
                  onUnauthorized={onUnauthorized}
                />
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ],
    [customer, onUnauthorized],
  ); // eslint-disable-line react-hooks/exhaustive-deps -- getThemeClasses intentionally excluded to prevent infinite loop

  const handleErrorClose = useCallback(() => {
    setErrors({});
  }, []);

  const errorMessage = useMemo(() => {
    if (
      errors &&
      typeof errors === "object" &&
      Object.keys(errors).length > 0
    ) {
      return Object.entries(errors)
        .map(
          ([key, value]) =>
            `${key}: ${Array.isArray(value) ? value.join(", ") : value}`,
        )
        .join("; ");
    }
    return null;
  }, [errors]);

  return (
    <DetailFullView
      entityData={customer}
      breadcrumbItems={BREADCRUMB_ITEMS}
      headerConfig={headerConfig}
      mainInfoCard={mainInfoCard}
      contentSections={contentSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={ALERTS}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching}
      error={errorMessage}
      onErrorClose={handleErrorClose}
    />
  );
}

export default AdminCustomerDetailFullPage;
