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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UserIcon,
  InformationCircleIcon,
  ChevronLeftIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  PencilSquareIcon,
  ShieldExclamationIcon,
  HomeIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import {
  useCustomerManager,
  useAuthManager,
} from "../../../../services/Services";
import { TagsDisplay } from "../../../../components/business/displays";
import {
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_ORGANIZATION_TYPE_LABELS,
  CUSTOMER_STATUS,
} from "../../../../constants/Customer";
import {
  DetailLiteView,
  Badge,
  ContactLink,
  AddressDisplay,
  Button,
  useUIXTheme,
} from "../../../../components/UIX";

function AdminCustomerDetailLitePage() {
  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({});

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

  // Fetch customer detail - memoized
  const fetchCustomerDetail = useCallback(
    async (customerId) => {
      try {
        setFetching(true);
        setErrors({});

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

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

    if (cid) {
      fetchCustomerDetail(cid);
    }
  }, [cid, authManager, navigate, fetchCustomerDetail]);

  // Extract IDs from array of objects - memoized
  const extractIds = useMemo(
    () => (items) => {
      if (!items || !Array.isArray(items)) return [];
      return items.map((item) => item.id || item.value).filter(Boolean);
    },
    [],
  );

  // Helper function to get customer display name - memoized
  const getCustomerDisplayName = useCallback((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 - memoized
  const createStatusBadge = useCallback((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>
    );
  }, []);

  // Configure DetailLiteView props - memoized (MUST be before any conditional returns)
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Customers",
        to: "/admin/customers",
        icon: UserIcon,
      },
      {
        label: "Detail",
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [],
  );

  const headerConfig = useMemo(
    () => ({
      title: "Customer - Summary",
      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: () => navigate("/admin/customers"),
      },
    }),
    [navigate],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: () => navigate("/admin/customers"),
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: () => navigate(`/admin/customer/${cid}/edit`),
        icon: PencilSquareIcon,
        label: "Edit",
      },
    ],
    [navigate, cid],
  );

  const tabs = useMemo(
    () => [
      {
        label: "Summary",
        isActive: true,
      },
      {
        label: "Detail",
        to: `/admin/customer/${cid}/detail`,
      },
      {
        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 fieldSections = useMemo(
    () => [
      // Primary column sections
      {
        column: "primary",
        className: "mb-3 sm:mb-4 lg:mb-5",
        component: (
          <div>
            <h3
              className={`text-base sm:text-lg md:text-xl lg:text-2xl font-semibold ${getThemeClasses("text-primary")} flex items-center justify-center xl:justify-start`}
            >
              <span className="break-words">
                {getCustomerDisplayName(customer)}
              </span>
            </h3>
            <div
              className={`mt-2 text-sm lg:text-base ${getThemeClasses("text-secondary")} text-center xl:text-left`}
            >
              {createStatusBadge(customer)}
            </div>
            {customer?.tags && customer.tags.length > 0 && (
              <div className="mt-3">
                <TagsDisplay
                  values={extractIds(customer?.tags)}
                  label="Tags"
                  onUnauthorized={onUnauthorized}
                />
              </div>
            )}
          </div>
        ),
      },
      {
        column: "primary",
        className: "mb-3 sm:mb-4 lg:mb-5",
        component: (
          <AddressDisplay
            addressData={customer}
            size="md"
            showIcon={true}
            showMapsLink={true}
          />
        ),
      },
      {
        column: "primary",
        className: "space-y-2 sm:space-y-3",
        component: (
          <div className="space-y-2 sm:space-y-3">
            <ContactLink
              type="email"
              value={customer?.email}
              size="md"
              fallbackText="No email provided"
            />
            <ContactLink
              type="phone"
              value={customer?.phone}
              extension={customer?.phoneExtension}
              size="md"
              fallbackText="No phone provided"
            />
            {customer?.otherPhone && (
              <ContactLink
                type="phone"
                value={customer?.otherPhone}
                extension={customer?.otherPhoneExtension}
                size="md"
                label="Other Phone"
              />
            )}
          </div>
        ),
      },
      // Secondary column sections
      {
        column: "secondary",
        className: "mb-4 sm:mb-5",
        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 !== undefined &&
              customer.organizationType !== null &&
              customer.organizationType !== 0 && (
                <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>
              )}

            {customer.description && (
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text-secondary")}`}
                >
                  Description
                </label>
                <p
                  className={`text-base ${getThemeClasses("text-primary")} mt-1`}
                >
                  {customer.description}
                </p>
              </div>
            )}
          </div>
        ),
      },
      {
        column: "secondary",
        className: "mb-4 sm:mb-5",
        component: (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div
              className={`${getThemeClasses("stat-card-bg")} rounded-lg p-4 text-center`}
            >
              <div
                className={`text-2xl font-semibold ${getThemeClasses("stat-primary")}`}
              >
                {customer.orderCount || 0}
              </div>
              <div className={`text-sm ${getThemeClasses("text-muted")} mt-1`}>
                Total Orders
              </div>
            </div>

            <div
              className={`${getThemeClasses("stat-card-bg")} rounded-lg p-4 text-center`}
            >
              <div
                className={`text-2xl font-semibold ${getThemeClasses("stat-success")}`}
              >
                {customer.activeOrderCount || 0}
              </div>
              <div className={`text-sm ${getThemeClasses("text-muted")} mt-1`}>
                Active Orders
              </div>
            </div>

            <div
              className={`${getThemeClasses("stat-card-bg")} rounded-lg p-4 text-center`}
            >
              <div
                className={`text-2xl font-semibold ${getThemeClasses("stat-info")}`}
              >
                {customer.comments?.length || 0}
              </div>
              <div className={`text-sm ${getThemeClasses("text-muted")} mt-1`}>
                Comments
              </div>
            </div>
          </div>
        ),
      },
    ],
    [
      customer,
      getCustomerDisplayName,
      createStatusBadge,
      navigate,
      cid,
      getThemeClasses,
      extractIds,
      onUnauthorized,
    ],
  );

  const alerts = useMemo(
    () => ({
      archived: {
        message: "This customer is archived",
        icon: ArchiveBoxIcon,
      },
      banned: {
        message: "This customer is banned",
        icon: ShieldExclamationIcon,
      },
    }),
    [],
  );

  // Early returns AFTER all hooks to comply with rules of hooks
  if (!authManager.isAuthenticated()) {
    return (
      <DetailLiteView
        isLoading={true}
        headerConfig={{
          loadingText: "Checking authentication...",
        }}
      />
    );
  }

  if (isFetching && !customer.id) {
    return (
      <DetailLiteView
        isLoading={isFetching}
        headerConfig={{
          loadingText: "Loading customer summary...",
        }}
      />
    );
  }

  return (
    <DetailLiteView
      entityData={customer}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching}
      error={
        errors && typeof errors === "object" && Object.keys(errors).length > 0
          ? Object.entries(errors)
              .map(
                ([key, value]) =>
                  `${key}: ${Array.isArray(value) ? value.join(", ") : value}`,
              )
              .join("; ")
          : null
      }
      onErrorClose={() => setErrors({})}
    />
  );
}

export default AdminCustomerDetailLitePage;
