'use client';

import React, { useState, useEffect, useRef, useCallback, useMemo, Suspense } from 'react';
import type { DeletionValidationResult, IDocument } from '@alga-psa/types';
import { IContact } from '@alga-psa/types';
import type { IClient, ITag } from '@alga-psa/types';
import { findTagsByEntityId } from '@alga-psa/tags/actions';
import { useTags } from '@alga-psa/tags/context';
import { getAllUsersBasicAsync, getCurrentUserAsync } from '../../lib/usersHelpers';
import type { ISlaPolicy } from '@alga-psa/types';
import { BillingCycleType } from '@alga-psa/types';
import { useDocumentsCrossFeature } from '@alga-psa/core/context/DocumentsCrossFeatureContext';
import { validateClientName } from '@alga-psa/validation';
import ClientContactsList from '../contacts/ClientContactsList';
import { Flex, Text, Heading } from '@radix-ui/themes';
import { Switch } from '@alga-psa/ui/components/Switch';
import BillingConfiguration from './BillingConfiguration';
import { getClientById } from '@alga-psa/clients/actions';
import {
  updateClient,
  uploadClientLogo,
  deleteClientLogo,
  deleteClient,
  validateClientDeletion,
  reactivateClientContacts,
  deactivateClientContacts,
  markClientInactiveWithContacts,
  markClientActiveWithContacts,
  listClientInboundEmailDomains,
  addClientInboundEmailDomain,
  removeClientInboundEmailDomain,
  listClientNameAliases,
  addClientNameAlias,
  removeClientNameAlias,
  listInboundTicketDestinationOptions,
  startClientEntraSync,
} from '@alga-psa/clients/actions';
import { ConfirmationDialog } from '@alga-psa/ui/components/ConfirmationDialog';
import { DeleteEntityDialog } from '@alga-psa/ui';
import CustomTabs from '@alga-psa/ui/components/CustomTabs';
import { useClientCrossFeature } from '../../context/ClientCrossFeatureContext';
import { Button } from '@alga-psa/ui/components/Button';
import { PrintButton } from '@alga-psa/ui/components/PrintButton';
import { PrintableDetailHeader, type PrintableDetailField } from '@alga-psa/ui/components/PrintableDetailHeader';
import { ExternalLink, RefreshCw, Trash2 } from 'lucide-react';
import BackNav from '@alga-psa/ui/components/BackNav';
import InteractionsFeed from '../interactions/InteractionsFeed';
import { IInteraction } from '@alga-psa/types';
import { useDrawer } from "@alga-psa/ui";
import TimezonePicker from '@alga-psa/ui/components/TimezonePicker';
import { IUser } from '@shared/interfaces/user.interfaces';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import ClientLocations from './ClientLocations';
import TaxSettingsForm from './TaxSettingsForm';
import { IBoard, ITicket, ITicketCategory } from '@alga-psa/types';
import CustomSelect, { SelectOption } from '@alga-psa/ui/components/CustomSelect';
import { Card } from '@alga-psa/ui/components/Card';
import { Input } from '@alga-psa/ui/components/Input';
import { withDataAutomationId } from '@alga-psa/ui/ui-reflection/withDataAutomationId';
import { ReflectionContainer } from '@alga-psa/ui/ui-reflection/ReflectionContainer';
import { useAutomationIdAndRegister } from '@alga-psa/ui/ui-reflection/useAutomationIdAndRegister';
import { FormFieldComponent } from '@alga-psa/ui/ui-reflection/types';
import ClientContractLineDashboard from './ClientContractLineDashboard';
import { ClientNotesPanel } from './panels/ClientNotesPanel';
import { toast } from 'react-hot-toast';
import { handleError } from '@alga-psa/ui';
import EntityImageUpload from '@alga-psa/ui/components/EntityImageUpload';
import { useFeatureFlag } from '@alga-psa/ui/hooks';
import { Dialog, DialogContent } from '@alga-psa/ui/components/Dialog';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import { usePageSaveShortcut } from '@alga-psa/ui/keyboard-shortcuts';
import type { SurveyClientSatisfactionSummary } from '@alga-psa/types';
import {
  formatEntraRunStatusLabel,
  isTerminalEntraRunStatus,
  resolveEntraClientSyncStartState,
  shouldShowEntraSyncAction,
} from './clientDetailsEntraSyncAction';
import { ClientDetailsTabContent } from './ClientDetailsTabContent';
import HuduClientTab from './HuduClientTab';
import HuduClientPasswordsTab from './HuduClientPasswordsTab';
import HuduClientDocumentsSection from './HuduClientDocumentsSection';
import { useHuduClientTab } from './useHuduClientTab';

const EMPTY_CONTACTS: IContact[] = [];
const EMPTY_DOCUMENTS: IDocument[] = [];


const SwitchDetailItem: React.FC<{
  value: boolean;
  onEdit: (value: boolean) => void;
  automationId?: string;
  statusLabel: string;
  helperLabel: string;
  activeLabel: string;
  inactiveLabel: string;
}> = ({ value, onEdit, automationId, statusLabel, helperLabel, activeLabel, inactiveLabel }) => {
  // Register for UI automation with meaningful label
  const { automationIdProps } = useAutomationIdAndRegister<FormFieldComponent>({
    id: automationId,
    type: 'formField',
    fieldType: 'checkbox',
    label: statusLabel,
    value: value ? activeLabel : inactiveLabel,
    helperText: helperLabel
  });

  return (
    <div className="flex items-center justify-between py-3" {...automationIdProps}>
      <div>
        <div className="text-gray-900 font-medium">{statusLabel}</div>
        <div className="text-sm text-gray-500">{helperLabel}</div>
      </div>
      <div className="flex items-center gap-2">
        <span className="text-sm text-gray-700">
          {value ? activeLabel : inactiveLabel}
        </span>
        <Switch
          checked={value}
          onCheckedChange={onEdit}
          className="data-[state=checked]:bg-primary-500"
        />
      </div>
    </div>
  );
};

const TextDetailItem: React.FC<{
  label: string;
  value: string;
  onEdit: (value: string) => void;
  automationId?: string;
  validate?: (value: string) => string | null;
}> = ({ label, value, onEdit, automationId, validate }) => {
  const [localValue, setLocalValue] = useState(value);
  const [error, setError] = useState<string | null>(null);

  // Register for UI automation with meaningful label
  const { automationIdProps, updateMetadata } = useAutomationIdAndRegister<FormFieldComponent>({
    id: automationId,
    type: 'formField',
    fieldType: 'textField',
    label: label,
    value: localValue,
    helperText: `Input field for ${label}`
  });

  // Update metadata when localValue changes
  useEffect(() => {
    if (updateMetadata) {
      updateMetadata({
        value: localValue,
        label: label
      });
    }
  }, [localValue, updateMetadata, label]);

  const handleBlur = () => {
    // Professional SaaS validation pattern: validate on blur, not while typing
    if (validate) {
      const validationError = validate(localValue);
      setError(validationError);
    }

    // Always call onEdit to allow parent to determine if changes should be tracked
    onEdit(localValue);
  };
  
  return (
    <div className="space-y-2" {...automationIdProps}>
      <Text as="label" size="2" className="text-gray-700 font-medium">{label}</Text>
      <Input
        id={automationId ? `${automationId}-input` : undefined}
        type="text"
        value={localValue}
        onChange={(e) => {
          setLocalValue(e.target.value);
          // Clear error while typing
          if (error) {
            setError(null);
          }
        }}
        onBlur={handleBlur}
        className={`w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-2 transition-all duration-200 ${
          error
            ? 'border-red-500 focus:ring-red-500 focus:border-red-500'
            : 'border-gray-200 focus:ring-purple-500 focus:border-transparent'
        }`}
      />
      {error && (
        <Text size="1" className="text-red-600 mt-1">{error}</Text>
      )}
    </div>
  );
};

interface ClientDetailsProps {
  id?: string;
  client: IClient;
  documents?: IDocument[];
  contacts?: IContact[];
  isInDrawer?: boolean;
  quickView?: boolean;
  surveySummary?: SurveyClientSatisfactionSummary | null;
  isAlgaDeskMode?: boolean;
}

const ClientDetails: React.FC<ClientDetailsProps> = ({
  id = 'client-details',
  client,
  documents = EMPTY_DOCUMENTS,
  contacts = EMPTY_CONTACTS,
  isInDrawer = false,
  quickView = false,
  surveySummary = null,
  isAlgaDeskMode = false,
}) => {
  const { t } = useTranslation('msp/clients');
  const { renderQuickAddTicket, getTicketFormOptions, renderSurveySummaryCard, renderClientAssets, renderClientTickets, getSlaPolicies } = useClientCrossFeature();
  const { renderDocuments } = useDocumentsCrossFeature();
  const [editedClient, setEditedClient] = useState<IClient>(client);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [isQuickAddTicketOpen, setIsQuickAddTicketOpen] = useState(false);
  const [interactions, setInteractions] = useState<IInteraction[]>([]);
  const [currentUser, setCurrentUser] = useState<IUser | null>(null);
  const [internalUsers, setInternalUsers] = useState<IUser[]>([]);
  const [isLoadingUsers, setIsLoadingUsers] = useState(false);
  const [isDocumentSelectorOpen, setIsDocumentSelectorOpen] = useState(false);
  const [isUploadingLogo, setIsUploadingLogo] = useState(false);
  const [isDeletingLogo, setIsDeletingLogo] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteValidation, setDeleteValidation] = useState<DeletionValidationResult | null>(null);
  const [isDeleteValidating, setIsDeleteValidating] = useState(false);
  const [isDeleteProcessing, setIsDeleteProcessing] = useState(false);
  const [isReactivateDialogOpen, setIsReactivateDialogOpen] = useState(false);
  const [inactiveContactsToReactivate, setInactiveContactsToReactivate] = useState<IContact[]>([]);
  const [isDeactivateDialogOpen, setIsDeactivateDialogOpen] = useState(false);
  const [activeContactsToDeactivate, setActiveContactsToDeactivate] = useState<IContact[]>([]);
  const [isEditingLogo, setIsEditingLogo] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isSyncingEntra, setIsSyncingEntra] = useState(false);
  const [entraSyncRunId, setEntraSyncRunId] = useState<string | null>(null);
  const [entraSyncStatus, setEntraSyncStatus] = useState<string | null>(null);
  const [ticketFormOptions, setTicketFormOptions] = useState<{
    statusOptions: SelectOption[];
    priorityOptions: SelectOption[];
    boardOptions: IBoard[];
    categories: ITicketCategory[];
    tags?: ITag[];
    users?: IUser[];
  } | null>(null);
  const [isLocationsDialogOpen, setIsLocationsDialogOpen] = useState(false);
  const [locationsRefreshKey, setLocationsRefreshKey] = useState(0);
  const [tags, setTags] = useState<ITag[]>([]);
  const [defaultContactOptions, setDefaultContactOptions] = useState<IContact[]>(contacts);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
  const [slaPolicies, setSlaPolicies] = useState<ISlaPolicy[]>([]);
  const [isLoadingSlaPolicies, setIsLoadingSlaPolicies] = useState(false);
  const { tags: allTags } = useTags();
  const router = useRouter();
  const memoizedRouter = useMemo(() => router, [router]);
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const drawer = useDrawer();
  const isEEAvailable = process.env.NEXT_PUBLIC_EDITION === 'enterprise';
  const entraClientSyncFlag = useFeatureFlag('entra-integration-client-sync-action', {
    defaultValue: false,
  });
  const showEntraSyncAction = shouldShowEntraSyncAction(
    isEEAvailable ? 'enterprise' : process.env.NEXT_PUBLIC_EDITION,
    entraClientSyncFlag.enabled,
    editedClient
  );
  const shouldRenderPsaOnlyClientSurfaces = !isAlgaDeskMode;
  // F070: EE + hudu-integration flag + Hudu connected + this client mapped.
  const huduClientTab = useHuduClientTab(client.client_id);

  const fetchEntraSyncRunStatus = useCallback(async (runId: string): Promise<string | null> => {
    const response = await fetch(`/api/integrations/entra/sync/runs/${encodeURIComponent(runId)}`, {
      method: 'GET',
      credentials: 'same-origin',
      cache: 'no-store',
    });
    const payload = (await response.json().catch(() => null)) as {
      success?: boolean;
      data?: { run?: { status?: string } | null };
      error?: string;
    } | null;

    if (!response.ok || !payload?.success) {
      return null;
    }

    const status = payload.data?.run?.status ? String(payload.data.run.status) : null;
    return status;
  }, []);

  useEffect(() => {
    if (!entraSyncRunId) {
      return;
    }

    let cancelled = false;

    const poll = async () => {
      try {
        const nextStatus = await fetchEntraSyncRunStatus(entraSyncRunId);
        if (!nextStatus || cancelled) {
          return;
        }

        setEntraSyncStatus(formatEntraRunStatusLabel(nextStatus));
        if (isTerminalEntraRunStatus(nextStatus)) {
          setEntraSyncRunId(null);
        }
      } catch {
        // Keep polling resilient and avoid noisy UI errors on transient failures.
      }
    };

    void poll();
    const intervalId = window.setInterval(() => {
      void poll();
    }, 5000);

    return () => {
      cancelled = true;
      window.clearInterval(intervalId);
    };
  }, [entraSyncRunId, fetchEntraSyncRunStatus]);

  const localizeClientDeleteValidation = useCallback((result: DeletionValidationResult): DeletionValidationResult => {
    const hasClientOnlyAlternative = result.alternatives.some((alternative) => alternative.action === 'deactivate_client_only');
    const dependencyLabel = (type: string, count: number, fallback: string) => {
      const dependencyKeys: Record<string, [string, string, string, string]> = {
        contact: ['clientsPage.dependency.contact', 'contact', 'clientsPage.dependency.contacts', 'contacts'],
        ticket: ['clientsPage.dependency.ticket', 'ticket', 'clientsPage.dependency.tickets', 'tickets'],
        project: ['clientsPage.dependency.project', 'project', 'clientsPage.dependency.projects', 'projects'],
        invoice: ['clientsPage.dependency.invoice', 'invoice', 'clientsPage.dependency.invoices', 'invoices'],
        document: ['clientsPage.dependency.document', 'document', 'clientsPage.dependency.documents', 'documents'],
        interaction: ['clientsPage.dependency.interaction', 'interaction', 'clientsPage.dependency.interactions', 'interactions'],
        asset: ['clientsPage.dependency.asset', 'asset', 'clientsPage.dependency.assets', 'assets'],
        usage: ['clientsPage.dependency.serviceUsageRecord', 'service usage record', 'clientsPage.dependency.serviceUsageRecords', 'service usage records'],
        bucket_usage: ['clientsPage.dependency.bucketUsageRecord', 'bucket usage record', 'clientsPage.dependency.bucketUsageRecords', 'bucket usage records'],
      };
      const keys = dependencyKeys[type];
      if (!keys) return fallback;
      const [singularKey, singularDefault, pluralKey, pluralDefault] = keys;
      return count === 1
        ? t(singularKey, { defaultValue: singularDefault })
        : t(pluralKey, { defaultValue: pluralDefault });
    };

    const message = (() => {
      if (result.code === 'DEPENDENCIES_EXIST') {
        return t('clientsPage.deleteClientUnable', { defaultValue: 'Unable to delete this client.' });
      }
      if (result.code === 'IS_DEFAULT') {
        return t('clientsPage.defaultClientDeleteError', {
          defaultValue: 'Cannot delete the default client. Please set another client as default in General Settings first.',
        });
      }
      if (result.code === 'NOT_FOUND') {
        return t('clientsPage.clientNotFound', { defaultValue: 'Client not found.' });
      }
      if (result.code === 'PERMISSION_DENIED') {
        return t('clientsPage.deletePermissionDenied', {
          defaultValue: 'Permission denied: Cannot delete clients.',
        });
      }
      return result.message;
    })();

    return {
      ...result,
      message,
      dependencies: result.dependencies.map((dependency) => ({
        ...dependency,
        label: dependencyLabel(dependency.type, dependency.count, dependency.label),
      })),
      alternatives: result.alternatives.map((alternative) => {
        if (alternative.action === 'deactivate_client_only') {
          return {
            ...alternative,
            label: t('clientDetails.clientOnly', { defaultValue: 'Client Only' }),
            description: t('clientDetails.deactivateClientOnlyDescription', {
              defaultValue: 'Deactivate the client but leave its contacts active.',
            }),
          };
        }

        if (alternative.action === 'deactivate') {
          return {
            ...alternative,
            label: hasClientOnlyAlternative
              ? t('clientDetails.clientAndContacts', { defaultValue: 'Client & Contacts' })
              : t('clientsPage.markAsInactive', { defaultValue: 'Mark as Inactive' }),
            description: t('clientDetails.deactivateClientDescription', {
              defaultValue: 'Deactivates the record without deleting its data.',
            }),
          };
        }

        return alternative;
      }),
    };
  }, [t]);


  const runDeleteValidation = useCallback(async () => {
    setIsDeleteValidating(true);
    try {
      const result = await validateClientDeletion(editedClient.client_id);
      setDeleteValidation(localizeClientDeleteValidation(result));
    } catch (error: any) {
      console.error('Failed to validate client deletion:', error);
      setDeleteValidation({
        canDelete: false,
        code: 'VALIDATION_FAILED',
        message: t('clientDetails.deleteValidationError', {
          defaultValue: 'Failed to validate deletion. Please try again.',
        }),
        dependencies: [],
        alternatives: []
      });
    } finally {
      setIsDeleteValidating(false);
    }
  }, [editedClient.client_id, localizeClientDeleteValidation, t]);

  const handleDeleteClient = () => {
    setIsDeleteDialogOpen(true);
    void runDeleteValidation();
  };

  const confirmDelete = async () => {
    setIsDeleteProcessing(true);
    try {
      const result = await deleteClient(editedClient.client_id);

      if (!result.success) {
        setDeleteValidation(localizeClientDeleteValidation(result));
        return;
      }

      resetDeleteState();
      toast.success(t('clientDetails.deleteSuccess', {
        defaultValue: 'Client has been deleted successfully.',
      }));

      if (isInDrawer) {
        drawer.closeDrawer();
      } else {
        router.push('/msp/clients');
      }
    } catch (error: any) {
      console.error('Failed to delete client:', error);
      toast.error(error.message || t('clientDetails.deleteError'));
    } finally {
      setIsDeleteProcessing(false);
    }
  };

  const handleDeleteAlternativeAction = async (action: string) => {
    setIsDeleteProcessing(true);
    try {
      if (action === 'deactivate') {
        await handleMarkClientInactiveAll();
      } else if (action === 'deactivate_client_only') {
        await handleMarkClientInactiveOnly();
      }
    } finally {
      setIsDeleteProcessing(false);
    }
  };

  // Handler for deactivating client from the delete dialog (deactivates all contacts)
  const handleMarkClientInactiveAll = async () => {
    try {
      // Use atomic action to deactivate client AND all contacts
      const result = await markClientInactiveWithContacts(editedClient.client_id, true);

      if (!result.success) {
        handleError(new Error(result.message || 'Failed to mark client as inactive'));
        resetDeleteState();
        return;
      }

      // Update local state immediately
      setEditedClient(prev => ({ ...prev, is_inactive: true }));

      if (result.contactsDeactivated > 0) {
        toast.success(t('clientDetails.deactivateWithContactsSuccess', {
          defaultValue: 'Client and {{count}} contacts have been deactivated successfully.',
          count: result.contactsDeactivated,
        }));
      } else {
        toast.success(t('clientDetails.inactiveSuccess', {
          defaultValue: 'Client has been marked as inactive successfully.',
        }));
      }

      // Close dialog first, then refresh in background
      resetDeleteState();
      router.refresh();
    } catch (error: any) {
      handleError(error, 'An error occurred while marking the client as inactive. Please try again.');
      resetDeleteState();
    }
  };

  // Handler for deactivating client from the delete dialog (client only)
  const handleMarkClientInactiveOnly = async () => {
    try {
      // Use atomic action to deactivate client only
      const result = await markClientInactiveWithContacts(editedClient.client_id, false);

      if (!result.success) {
        handleError(new Error(result.message || 'Failed to mark client as inactive'));
        resetDeleteState();
        return;
      }

      // Update local state immediately
      setEditedClient(prev => ({ ...prev, is_inactive: true }));
      toast.success(t('clientDetails.inactiveSuccess', {
        defaultValue: 'Client has been marked as inactive successfully.',
      }));

      // Close dialog first, then refresh in background
      resetDeleteState();
      router.refresh();
    } catch (error: any) {
      handleError(error, 'An error occurred while marking the client as inactive. Please try again.');
      resetDeleteState();
    }
  };

  // Handler for the direct "Mark as Inactive" button (not from delete dialog)
  const handleDirectMarkInactive = async () => {
    try {
      // Fetch active contacts for this client
      const { getContactsByClient } = await import('@alga-psa/clients/actions');
      const activeContacts = await getContactsByClient(editedClient.client_id, 'active');

      if (activeContacts.length > 0) {
        setActiveContactsToDeactivate(activeContacts);
        setIsDeactivateDialogOpen(true);
      } else {
        // No contacts to warn about, use atomic action to deactivate the client
        const result = await markClientInactiveWithContacts(editedClient.client_id, false);

        if (!result.success) {
          handleError(new Error(result.message || 'Failed to mark client as inactive'));
          return;
        }

        // Update local state immediately
        setEditedClient(prev => ({ ...prev, is_inactive: true }));
        toast.success(t('clientDetails.inactiveSuccess', {
          defaultValue: 'Client has been marked as inactive successfully.',
        }));
        router.refresh();
      }
    } catch (error: any) {
      handleError(error, 'An error occurred while marking the client as inactive. Please try again.');
    }
  };

  // Handler for the direct "Reactivate" button
  const handleDirectReactivate = async () => {
    try {
      // Fetch inactive contacts for this client
      const { getContactsByClient } = await import('@alga-psa/clients/actions');
      const inactiveContacts = await getContactsByClient(editedClient.client_id, 'inactive');

      if (inactiveContacts.length > 0) {
        setInactiveContactsToReactivate(inactiveContacts);
        setIsReactivateDialogOpen(true);
      } else {
        // No contacts to ask about, use atomic action to reactivate the client
        const result = await markClientActiveWithContacts(editedClient.client_id, false);

        if (!result.success) {
          handleError(new Error(result.message || 'Failed to reactivate client'));
          return;
        }

        // Update local state immediately
        setEditedClient(prev => ({ ...prev, is_inactive: false }));
        toast.success(t('clientDetails.reactivateSuccess', {
          defaultValue: 'Client has been reactivated successfully.',
        }));
        router.refresh();
      }
    } catch (error: any) {
      handleError(error, 'An error occurred while reactivating the client. Please try again.');
    }
  };

  const handleReactivateClient = async (reactivateContacts: boolean) => {
    try {
      // Use atomic server action to reactivate client and optionally contacts in a single transaction
      const result = await markClientActiveWithContacts(editedClient.client_id, reactivateContacts);

      if (!result.success) {
        handleError(new Error(result.message || 'Failed to reactivate client'));
        setIsReactivateDialogOpen(false);
        return;
      }

      // Update local state immediately
      setEditedClient(prev => ({ ...prev, is_inactive: false }));
      setHasUnsavedChanges(false);

      if (reactivateContacts && result.contactsReactivated > 0) {
        toast.success(t('clientDetails.reactivateWithContactsSuccess', {
          defaultValue: 'Client and {{count}} contacts have been reactivated successfully.',
          count: result.contactsReactivated,
        }));
      } else {
        toast.success(t('clientDetails.reactivateSuccess', {
          defaultValue: 'Client has been reactivated successfully.',
        }));
      }

      setIsReactivateDialogOpen(false);
      router.refresh();
    } catch (error: any) {
      handleError(error, 'An error occurred while reactivating the client. Please try again.');
    }
  };

  const handleCancelReactivation = () => {
    setIsReactivateDialogOpen(false);
    // Keep the client inactive - no changes
  };

  const handleDeactivateClient = async (deactivateContacts: boolean) => {
    try {
      // Use atomic server action to deactivate client and optionally contacts in a single transaction
      const result = await markClientInactiveWithContacts(editedClient.client_id, deactivateContacts);

      if (!result.success) {
        handleError(new Error(result.message || 'Failed to deactivate client'));
        setIsDeactivateDialogOpen(false);
        return;
      }

      // Update local state immediately
      setEditedClient(prev => ({ ...prev, is_inactive: true }));
      setHasUnsavedChanges(false);

      if (deactivateContacts && result.contactsDeactivated > 0) {
        toast.success(t('clientDetails.deactivateWithContactsSuccess', {
          defaultValue: 'Client and {{count}} contacts have been deactivated successfully.',
          count: result.contactsDeactivated,
        }));
      } else {
        toast.success(t('clientDetails.inactiveSuccess', {
          defaultValue: 'Client has been marked as inactive successfully.',
        }));
      }

      setIsDeactivateDialogOpen(false);
      router.refresh();
    } catch (error: any) {
      handleError(error, 'An error occurred while deactivating the client. Please try again.');
    }
  };

  const handleCancelDeactivation = () => {
    setIsDeactivateDialogOpen(false);
    // Keep the client active - no changes
  };

  const resetDeleteState = () => {
    setIsDeleteDialogOpen(false);
    setDeleteValidation(null);
  };

  // 1. Implement refreshClientData function
  const refreshClientData = useCallback(async () => {
    if (!client?.client_id) return;

    try {
      const latestClientData = await getClientById(client.client_id);
      if (latestClientData) {
        setEditedClient({
          ...latestClientData,
          client_type: latestClientData.client_type || 'company'
        });
        setHasUnsavedChanges(false);
      }
    } catch (error) {
      console.error('Error refreshing client data:', error);
      toast.error(t('clientDetails.refreshError', {
        defaultValue: 'Could not fetch latest client data.',
      }));
    }
  }, [client?.client_id]);

  // Combined Initial Load Logic
  useEffect(() => {
    setEditedClient({
      ...client,
      client_type: client.client_type || 'company'
    });
    setHasUnsavedChanges(false);
  }, [client]);

  // Fetch current user once on mount
  useEffect(() => {
    const fetchUser = async () => {
      try {
        const user = await getCurrentUserAsync();
        if (user) {
          setCurrentUser(prev => (prev?.user_id === user.user_id ? prev : user));
        }
      } catch (error) {
        console.error('Error fetching current user:', error);
      }
    };
    fetchUser();
  }, []);

  // Fetch MSP users once or when needed
  useEffect(() => {
    const fetchAllUsers = async () => {
      if (internalUsers.length > 0) return;
      setIsLoadingUsers(true);
      try {
        const users = await getAllUsersBasicAsync();
        setInternalUsers(users);
      } catch (error) {
        console.error("Error fetching MSP users:", error);
      } finally {
        setIsLoadingUsers(false);
      }
    };
    fetchAllUsers();
  }, [internalUsers.length]);

  // Separate useEffect for ticket form options
  useEffect(() => {
    const fetchTicketFormOptions = async () => {
      if (!currentUser) return;
      try {
        const options = await getTicketFormOptions();
        setTicketFormOptions({
          statusOptions: options.statusOptions,
          priorityOptions: options.priorityOptions,
          boardOptions: options.boardOptions,
          categories: options.categories,
          tags: options.tags,
          users: options.users
        });
      } catch (error) {
        console.error('Error fetching ticket form options:', error);
      }
    };

    fetchTicketFormOptions();
  }, [currentUser?.user_id]);

  // Fetch tags when component mounts
  useEffect(() => {
    const fetchTags = async () => {
      try {
        const clientTags = await findTagsByEntityId(client.client_id, 'client');
        setTags(clientTags);
      } catch (error) {
        console.error('Error fetching tags:', error);
      }
    };
    fetchTags();
  }, [client.client_id]);

  // Fetch SLA policies
  useEffect(() => {
    const fetchSlaPolicies = async () => {
      if (slaPolicies.length > 0) return;
      setIsLoadingSlaPolicies(true);
      try {
        const policies = await getSlaPolicies();
        setSlaPolicies(policies);
      } catch (error) {
        console.error('Error fetching SLA policies:', error);
      } finally {
        setIsLoadingSlaPolicies(false);
      }
    };
    fetchSlaPolicies();
  }, [slaPolicies.length]);

  const handleFieldChange = async (field: string, value: string | boolean | null) => {
    // Check if client is being deactivated (is_inactive changing from false to true)
    if (field === 'is_inactive' && editedClient.is_inactive === false && value === true) {
      // Fetch active contacts for this client
      const { getContactsByClient } = await import('@alga-psa/clients/actions');
      const activeContacts = await getContactsByClient(editedClient.client_id, 'active');

      if (activeContacts.length > 0) {
        setActiveContactsToDeactivate(activeContacts);
        setIsDeactivateDialogOpen(true);
        return; // Don't update the field yet, wait for user confirmation
      }
    }

    // Check if client is being reactivated (is_inactive changing from true to false)
    if (field === 'is_inactive' && editedClient.is_inactive === true && value === false) {
      // Fetch inactive contacts for this client
      const { getContactsByClient } = await import('@alga-psa/clients/actions');
      const inactiveContacts = await getContactsByClient(editedClient.client_id, 'inactive');

      if (inactiveContacts.length > 0) {
        setInactiveContactsToReactivate(inactiveContacts);
        setIsReactivateDialogOpen(true);
        return; // Don't update the field yet, wait for user confirmation
      }
    }

    setEditedClient(prevClient => {
      // Create a deep copy of the previous client
      const updatedClient = JSON.parse(JSON.stringify(prevClient)) as IClient;

      if (field.startsWith('properties.') && field !== 'properties.account_manager_id') {
        const propertyField = field.split('.')[1];

        // Ensure properties object exists
        if (!updatedClient.properties) {
          updatedClient.properties = {};
        }

        // Update the specific property using type assertion
        (updatedClient.properties as any)[propertyField] = value;

        // Sync url with properties.website when website is updated
        if (propertyField === 'website' && typeof value === 'string') {
          updatedClient.url = value;
        }
      } else if (field === 'url') {
        // Update the URL field
        updatedClient.url = value as string;

        // Sync properties.website with url
        if (!updatedClient.properties) {
          updatedClient.properties = {};
        }

        // Use type assertion to set the website property
        (updatedClient.properties as any).website = value as string;
      } else {
        // For all other fields, use type assertion to update directly
        (updatedClient as any)[field] = value;
      }

      return updatedClient;
    });
    
    // Check if the updated client matches the original client
    setHasUnsavedChanges(() => {
      // Create a temporary copy to compare
      const tempClient = JSON.parse(JSON.stringify(editedClient)) as IClient;
      
      // Apply the change to temp client for comparison
      if (field.startsWith('properties.') && field !== 'properties.account_manager_id') {
        const propertyField = field.split('.')[1];
        if (!tempClient.properties) {
          tempClient.properties = {};
        }
        (tempClient.properties as any)[propertyField] = value;
        if (propertyField === 'website' && typeof value === 'string') {
          tempClient.url = value;
        }
      } else if (field === 'url') {
        tempClient.url = value as string;
        if (!tempClient.properties) {
          tempClient.properties = {};
        }
        (tempClient.properties as any).website = value as string;
      } else {
        (tempClient as any)[field] = value;
      }
      
      // Compare with original client to determine if there are unsaved changes
      return JSON.stringify(tempClient) !== JSON.stringify(client);
    });
  };

  const editedClientRef = useRef(editedClient);
  editedClientRef.current = editedClient;
  const isSavingRef = useRef(isSaving);
  isSavingRef.current = isSaving;

  const handleSave = useCallback(async () => {
    if (isSavingRef.current) return;
    setHasAttemptedSubmit(true);

    // Professional PSA validation pattern: Check required fields
    const requiredFields = {
      client_name: editedClientRef.current.client_name?.trim() || ''
    };

    // Clear previous errors and validate required fields
    const newErrors: Record<string, string> = {};
    let hasValidationErrors = false;

    Object.entries(requiredFields).forEach(([field, value]) => {
      if (field === 'client_name') {
        const error = validateClientName(value);
        if (error) {
          newErrors[field] = error;
          hasValidationErrors = true;
        }
      }
    });

    setFieldErrors(newErrors);

    if (hasValidationErrors) {
      setIsSaving(false);
      return;
    }

    setIsSaving(true);
    try {
      // Prepare data for update, removing computed fields
      const {
        account_manager_full_name,
        ...restOfEditedClient
      } = editedClientRef.current;
      const dataToUpdate: Partial<Omit<IClient, 'account_manager_full_name'>> = {
        ...restOfEditedClient,
        properties: restOfEditedClient.properties ? { ...restOfEditedClient.properties } : {},
        account_manager_id: editedClientRef.current.account_manager_id === '' ? null : editedClientRef.current.account_manager_id,
      };
      const updatedClientResult = await updateClient(client.client_id, dataToUpdate);
      // Assuming updateClient returns the full updated client object matching IClient
      const updatedClient = updatedClientResult as IClient; // Cast if necessary, or adjust based on actual return type
      setEditedClient(updatedClient);
      setHasUnsavedChanges(false);
      setHasAttemptedSubmit(false);
      toast.success(t('clientDetails.saveSuccess', {
        defaultValue: 'Client details saved successfully.',
      }));
    } catch (error) {
      console.error('Error saving client:', error);
      toast.error(t('clientDetails.saveError', {
        defaultValue: 'Failed to save client details. Please try again.',
      }));
    } finally {
      setIsSaving(false);
    }
  }, [client.client_id]);

  usePageSaveShortcut(handleSave, { enabled: hasUnsavedChanges && !isSaving });

  const handleSyncEntraNow = async () => {
    if (isSyncingEntra) return;

    setIsSyncingEntra(true);
    try {
      const result = await startClientEntraSync({
        clientId: editedClient.client_id,
      });

      if ('error' in result) {
        toast.error(result.error || t('clientDetails.entraSyncError', {
          defaultValue: 'Failed to start Entra sync.',
        }));
        return;
      }

      if (!result.success) {
        toast.error(t('clientDetails.entraSyncError', {
          defaultValue: 'Failed to start Entra sync.',
        }));
        return;
      }

      // The status endpoint looks up by entra_sync_runs.run_id or workflow_id.
      // Prefer workflowId because the upstream `runId` here is Temporal's
      // firstExecutionRunId, which has no row in entra_sync_runs — polling it
      // would never reach a terminal state.
      const syncState = resolveEntraClientSyncStartState(result.data?.workflowId || result.data?.runId);
      if (syncState.shouldPoll && syncState.runId) {
        setEntraSyncRunId(syncState.runId);
        setEntraSyncStatus(syncState.statusMessage);
        toast.success(t('clientDetails.entraSyncStarted', { runId: syncState.runId }));
      } else {
        setEntraSyncStatus(syncState.statusMessage);
        toast.success(syncState.statusMessage);
      }
    } catch (error: unknown) {
      const message = error instanceof Error
        ? error.message
        : t('clientDetails.entraSyncError', { defaultValue: 'Failed to start Entra sync.' });
      toast.error(message);
    } finally {
      setIsSyncingEntra(false);
    }
  };

  const handleBillingConfigSave = useCallback(async (updatedBillingConfig: Partial<IClient>) => {
    try {
      const updatedClient = await updateClient(client.client_id, updatedBillingConfig);
      setEditedClient(prevClient => {
        const newClient = { ...prevClient };
        Object.keys(updatedBillingConfig).forEach(key => {
          (newClient as any)[key] = (updatedClient as any)[key];
        });
        return newClient;
      });
    } catch (error) {
      console.error('Error updating client:', error);
    }
  }, [client.client_id]);

  const handleTicketAdded = (ticket: ITicket) => {
    setIsQuickAddTicketOpen(false);
  };

  const handleInteractionAdded = (newInteraction: IInteraction) => {
    setInteractions(prevInteractions => {
      const updatedInteractions = [newInteraction, ...prevInteractions];
      return updatedInteractions.filter((interaction, index, self) =>
        index === self.findIndex((t) => t.interaction_id === interaction.interaction_id)
      );
    });
  };

  const handleTagsChange = useCallback((updatedTags: ITag[]) => {
    setTags(updatedTags);
  }, []);

  const handleTabChange = useCallback(async (tabValue: string) => {
    const params = new URLSearchParams(searchParams?.toString() || '');
    params.set('tab', tabValue);
    memoizedRouter.push(`${pathname}?${params.toString()}`);
  }, [pathname, memoizedRouter, searchParams]);

  const clientActiveContacts = useMemo(() => {
    return (defaultContactOptions ?? []).filter((c) => !c?.is_inactive);
  }, [defaultContactOptions]);

  useEffect(() => {
    setDefaultContactOptions(contacts);
  }, [contacts]);

  const handleDefaultContactChange = useCallback((contactId: string) => {
    const selected = contactId ? clientActiveContacts.find((c) => c.contact_name_id === contactId) : undefined;
    const selectedName = contactId ? (selected?.full_name ?? '') : '';

    setEditedClient((prevClient) => {
      const updatedClient = JSON.parse(JSON.stringify(prevClient)) as IClient;
      if (!updatedClient.properties) {
        updatedClient.properties = {};
      }
      (updatedClient.properties as any).primary_contact_id = contactId;
      (updatedClient.properties as any).primary_contact_name = selectedName;
      return updatedClient;
    });

    setHasUnsavedChanges(() => {
      const tempClient = JSON.parse(JSON.stringify(editedClient)) as IClient;
      if (!tempClient.properties) {
        tempClient.properties = {};
      }
      (tempClient.properties as any).primary_contact_id = contactId;
      (tempClient.properties as any).primary_contact_name = selectedName;
      return JSON.stringify(tempClient) !== JSON.stringify(client);
    });
  }, [clientActiveContacts, editedClient, client]);

  const [inboundEmailDomains, setInboundEmailDomains] = useState<Array<{ id: string; domain: string }>>([]);
  const [inboundDomainDraft, setInboundDomainDraft] = useState('');
  const [isInboundDomainBusy, setIsInboundDomainBusy] = useState(false);
  const [inboundDestinationOptions, setInboundDestinationOptions] = useState<SelectOption[]>([]);
  const [isInboundDestinationOptionsLoading, setIsInboundDestinationOptionsLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const rows = await listClientInboundEmailDomains(editedClient.client_id);
        if (cancelled) return;
        setInboundEmailDomains((rows ?? []).map((r: any) => ({ id: r.id, domain: r.domain })));
      } catch (error) {
        // Non-blocking; if this fails we don't want to prevent other client edits.
        console.error('Failed to load inbound email domains:', error);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [editedClient.client_id]);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setIsInboundDestinationOptionsLoading(true);
      try {
        const rows = await listInboundTicketDestinationOptions();
        if (cancelled) return;
        const options = (rows ?? []).map((row: any) => ({
          value: row.id,
          label: row.is_active
            ? `${row.display_name} (${row.short_name})`
            : `${row.display_name} (${row.short_name}) [inactive]`,
        })) as SelectOption[];
        setInboundDestinationOptions(options);
      } catch (error) {
        if (cancelled) return;
        console.error('Failed to load inbound ticket destination options:', error);
        setInboundDestinationOptions([]);
      } finally {
        if (!cancelled) {
          setIsInboundDestinationOptionsLoading(false);
        }
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const normalizeInboundDomain = useCallback((raw: string) => {
    const trimmed = (raw ?? '').trim().toLowerCase();
    return trimmed.startsWith('@') ? trimmed.slice(1) : trimmed;
  }, []);

  const handleAddInboundDomain = useCallback(async () => {
    const domain = normalizeInboundDomain(inboundDomainDraft);
    if (!domain) return;
    setIsInboundDomainBusy(true);
    try {
      const created = await addClientInboundEmailDomain(editedClient.client_id, domain);
      setInboundEmailDomains((prev) => {
        const next = [...prev, { id: (created as any).id, domain: (created as any).domain }].filter(
          (d, idx, arr) => idx === arr.findIndex((x) => x.id === d.id)
        );
        next.sort((a, b) => a.domain.localeCompare(b.domain));
        return next;
      });
      setInboundDomainDraft('');
      toast.success(t('clientDetails.inboundDomainAdded'));
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('clientDetails.inboundDomainAddFailed'));
    } finally {
      setIsInboundDomainBusy(false);
    }
  }, [addClientInboundEmailDomain, editedClient.client_id, inboundDomainDraft, normalizeInboundDomain]);

  const handleRemoveInboundDomain = useCallback(async (domainId: string) => {
    if (!domainId) return;
    setIsInboundDomainBusy(true);
    try {
      await removeClientInboundEmailDomain(editedClient.client_id, domainId);
      setInboundEmailDomains((prev) => prev.filter((d) => d.id !== domainId));
      toast.success(t('clientDetails.inboundDomainRemoved'));
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('clientDetails.inboundDomainRemoveFailed'));
    } finally {
      setIsInboundDomainBusy(false);
    }
  }, [editedClient.client_id]);

  const [clientNameAliases, setClientNameAliases] = useState<Array<{ id: string; alias: string }>>([]);
  const [aliasDraft, setAliasDraft] = useState('');
  const [isAliasBusy, setIsAliasBusy] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const rows = await listClientNameAliases(editedClient.client_id);
        if (cancelled) return;
        setClientNameAliases((rows ?? []).map((r: any) => ({ id: r.id, alias: r.alias })));
      } catch (error) {
        // Non-blocking; if this fails we don't want to prevent other client edits.
        console.error('Failed to load client name aliases:', error);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [editedClient.client_id]);

  const handleAddClientNameAlias = useCallback(async () => {
    const alias = aliasDraft.replace(/\s+/g, ' ').trim();
    if (!alias) return;
    setIsAliasBusy(true);
    try {
      const created = await addClientNameAlias(editedClient.client_id, alias);
      setClientNameAliases((prev) => {
        const next = [...prev, { id: (created as any).id, alias: (created as any).alias }].filter(
          (a, idx, arr) => idx === arr.findIndex((x) => x.id === a.id)
        );
        next.sort((a, b) => a.alias.localeCompare(b.alias));
        return next;
      });
      setAliasDraft('');
      toast.success(t('clientDetails.nameAliasAdded', { defaultValue: 'Alias added' }));
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('clientDetails.nameAliasAddFailed', { defaultValue: 'Failed to add alias' }));
    } finally {
      setIsAliasBusy(false);
    }
  }, [aliasDraft, editedClient.client_id]);

  const handleRemoveClientNameAlias = useCallback(async (aliasId: string) => {
    if (!aliasId) return;
    setIsAliasBusy(true);
    try {
      await removeClientNameAlias(editedClient.client_id, aliasId);
      setClientNameAliases((prev) => prev.filter((a) => a.id !== aliasId));
      toast.success(t('clientDetails.nameAliasRemoved', { defaultValue: 'Alias removed' }));
    } catch (error) {
      toast.error(error instanceof Error ? error.message : t('clientDetails.nameAliasRemoveFailed', { defaultValue: 'Failed to remove alias' }));
    } finally {
      setIsAliasBusy(false);
    }
  }, [editedClient.client_id]);

  const baseTabContent = useMemo(() => [
    {
      id: 'details',
      label: t('clientDetails.details', { defaultValue: 'Details' }),
      content: (
        <ClientDetailsTabContent
          id={id}
          editedClient={editedClient}
          tags={tags}
          internalUsers={internalUsers}
          isLoadingUsers={isLoadingUsers}
          clientActiveContacts={clientActiveContacts}
          setDefaultContactOptions={setDefaultContactOptions}
          fieldErrors={fieldErrors}
          hasAttemptedSubmit={hasAttemptedSubmit}
          slaPolicies={slaPolicies}
          isLoadingSlaPolicies={isLoadingSlaPolicies}
          isInDrawer={isInDrawer}
          locationsRefreshKey={locationsRefreshKey}
          surveySummary={surveySummary}
          isAlgaDeskMode={isAlgaDeskMode}
          inboundDestinationOptions={inboundDestinationOptions}
          isInboundDestinationOptionsLoading={isInboundDestinationOptionsLoading}
          inboundEmailDomains={inboundEmailDomains}
          inboundDomainDraft={inboundDomainDraft}
          setInboundDomainDraft={setInboundDomainDraft}
          isInboundDomainBusy={isInboundDomainBusy}
          normalizeInboundDomain={normalizeInboundDomain}
          clientNameAliases={clientNameAliases}
          aliasDraft={aliasDraft}
          setAliasDraft={setAliasDraft}
          isAliasBusy={isAliasBusy}
          isSaving={isSaving}
          t={t}
          onFieldChange={handleFieldChange}
          onDefaultContactChange={handleDefaultContactChange}
          onAddInboundDomain={handleAddInboundDomain}
          onRemoveInboundDomain={handleRemoveInboundDomain}
          onAddClientNameAlias={handleAddClientNameAlias}
          onRemoveClientNameAlias={handleRemoveClientNameAlias}
          onTagsChange={handleTagsChange}
          onManageLocations={() => setIsLocationsDialogOpen(true)}
          onSave={handleSave}
          onAddTicket={() => setIsQuickAddTicketOpen(true)}
          renderSurveySummaryCard={renderSurveySummaryCard}
        />
      )
    },
    {
      id: 'tickets',
      label: t('clientDetails.tickets', { defaultValue: 'Tickets' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          {ticketFormOptions ? (
            renderClientTickets({
              clientId: client.client_id,
              clientName: client.client_name,
              initialBoards: ticketFormOptions.boardOptions,
              initialStatuses: ticketFormOptions.statusOptions,
              initialPriorities: ticketFormOptions.priorityOptions,
              initialCategories: ticketFormOptions.categories,
              initialTags: ticketFormOptions.tags || [],
              initialUsers: ticketFormOptions.users || [],
            })
          ) : (
            <div className="flex justify-center items-center h-32">
              <span>{t('clientDetails.loadingTicketFilters', { defaultValue: 'Loading ticket filters...' })}</span>
            </div>
          )}
        </div>
      )
    },
    {
      id: 'assets',
      label: t('clientDetails.assets', { defaultValue: 'Assets' }),
      content: shouldRenderPsaOnlyClientSurfaces ? renderClientAssets({ clientId: client.client_id }) : null,
    },
    {
      id: 'billing',
      label: t('clientDetails.billing', { defaultValue: 'Billing' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <BillingConfiguration
            client={editedClient}
            onSave={handleBillingConfigSave}
            contacts={contacts}
          />
        </div>
      )
    },
    {
      id: 'billing-dashboard',
      label: t('clientDetails.billingDashboard', { defaultValue: 'Billing Dashboard' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <ClientContractLineDashboard clientId={client.client_id} />
        </div>
      )
    },
    {
      id: 'contacts',
      label: t('clientDetails.contacts', { defaultValue: 'Contacts' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <ClientContactsList
            clientId={client.client_id}
            clients={[client]}
          />
        </div>
      )
    },
    {
      id: 'documents',
      label: t('clientDetails.documents', { defaultValue: 'Documents' }),
      content: (
        shouldRenderPsaOnlyClientSurfaces ? (
          <div className="bg-white p-6 rounded-lg shadow-sm">
            {currentUser ? renderDocuments({
                id: `${id}-documents`,
                documents,
                gridColumns: 3,
                userId: currentUser.user_id,
                entityId: client.client_id,
                entityType: 'client',
                onDocumentCreated: async () => {
                  memoizedRouter.refresh();
                },
            }) : (
              <div>{t('common.states.loading', { defaultValue: 'Loading...' })}</div>
            )}
            {huduClientTab.visible && (
              <HuduClientDocumentsSection clientId={client.client_id} />
            )}
          </div>
        ) : null
      )
    },
    {
      id: 'tax-settings',
      label: t('clientDetails.taxSettings', { defaultValue: 'Tax Settings' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <Suspense fallback={<div>{t('clientDetails.loadingTaxSettings', { defaultValue: 'Loading tax settings...' })}</div>}>
            <TaxSettingsForm clientId={client.client_id} />
          </Suspense>
        </div>
      )
    },
    {
      id: 'additional-info',
      label: t('clientDetails.additionalInfo', { defaultValue: 'Additional Info' }),
      content: (
        <div className="space-y-6 bg-white p-6 rounded-lg shadow-sm">
          <div className="grid grid-cols-2 gap-4">
            <TextDetailItem
              label="Tax ID"
              value={editedClient.properties?.tax_id ?? ""}
              onEdit={(value) => handleFieldChange('properties.tax_id', value)}
              automationId="tax-id-field"
            />
            <TextDetailItem
              label={t('clientDetails.paymentTerms', { defaultValue: 'Payment Terms' })}
              value={editedClient.properties?.payment_terms ?? ""}
              onEdit={(value) => handleFieldChange('properties.payment_terms', value)}
              automationId="payment-terms-field"
            />
            <TextDetailItem
              label={t('clientDetails.parentClient', { defaultValue: 'Parent Client' })}
              value={editedClient.properties?.parent_client_name ?? ""}
              onEdit={(value) => handleFieldChange('properties.parent_client_name', value)}
              automationId="parent-client-field"
            />
            <FieldContainer
              label={t('clientDetails.timezone', { defaultValue: 'Timezone' })}
              fieldType="select"
              value={editedClient.timezone || ''}
              helperText={t('clientDetails.timezoneHelper', {
                defaultValue: 'Select the timezone for this client',
              })}
              automationId="timezone-field"
            >
              <Text as="label" size="2" className="text-gray-700 font-medium">
                {t('clientDetails.timezone', { defaultValue: 'Timezone' })}
              </Text>
              <TimezonePicker
                value={editedClient.timezone ?? ""}
                onValueChange={(value) => handleFieldChange('timezone', value)}
              />
            </FieldContainer>
            <TextDetailItem
              label={t('clientDetails.lastContactDate', { defaultValue: 'Last Contact Date' })}
              value={editedClient.properties?.last_contact_date ?? ""}
              onEdit={(value) => handleFieldChange('properties.last_contact_date', value)}
              automationId="last-contact-date-field"
            />
          </div>
          
          <Flex gap="4" justify="end" align="center">
            {hasAttemptedSubmit && Object.keys(fieldErrors).some(key => fieldErrors[key]) && (
              <Text size="2" className="text-red-600 mr-2" role="alert">
                {t('clientDetails.requiredFields', { defaultValue: 'Please fill in all required fields' })}
              </Text>
            )}
            <Button
              id="save-additional-info-btn"
              onClick={handleSave}
              disabled={isSaving}
              className="bg-[rgb(var(--color-primary-500))] text-white hover:bg-[rgb(var(--color-primary-600))] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSaving
                ? t('common.actions.saving', { defaultValue: 'Saving...' })
                : t('clientDetails.saveChanges', { defaultValue: 'Save Changes' })}
            </Button>
          </Flex>
        </div>
      )
    },
    {
      id: 'notes',
      label: t('clientDetails.notes', { defaultValue: 'Notes' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <ClientNotesPanel
            clientId={editedClient.client_id}
            legacyNotes={editedClient.notes}
          />
        </div>
      )
    },
    {
      id: 'interactions',
      label: t('clientDetails.interactions', { defaultValue: 'Interactions' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <InteractionsFeed
            entityId={client.client_id}
            entityType="client"
            interactions={interactions}
            setInteractions={setInteractions}
          />
        </div>
      )
    },
    // EE-only Hudu tabs: registered only when EE + flag + connected + mapped (F070/F080).
    ...(huduClientTab.visible ? [{
      id: 'hudu',
      label: t('clientDetails.huduTab', { defaultValue: 'Hudu' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <HuduClientTab clientId={client.client_id} />
        </div>
      )
    }, {
      id: 'hudu-passwords',
      label: t('clientDetails.huduPasswordsTab', { defaultValue: 'Passwords' }),
      content: (
        <div className="bg-white p-6 rounded-lg shadow-sm">
          <HuduClientPasswordsTab clientId={client.client_id} />
        </div>
      )
    }] : [])
  ], [
    editedClient,
    internalUsers,
    isLoadingUsers,
    clientActiveContacts,
    setDefaultContactOptions,
    slaPolicies,
    isLoadingSlaPolicies,
    t,
    id,
    tags,
    handleTagsChange,
    isInDrawer,
    locationsRefreshKey,
    surveySummary,
    hasAttemptedSubmit,
    fieldErrors,
    handleSave,
    isSaving,
    setIsQuickAddTicketOpen,
    isAlgaDeskMode,
    ticketFormOptions,
    client.client_id,
    client.client_name,
    handleBillingConfigSave,
    contacts,
    handleDefaultContactChange,
    inboundDestinationOptions,
    isInboundDestinationOptionsLoading,
    inboundEmailDomains,
    inboundDomainDraft,
    setInboundDomainDraft,
    isInboundDomainBusy,
    handleAddInboundDomain,
    handleRemoveInboundDomain,
    normalizeInboundDomain,
    clientNameAliases,
    aliasDraft,
    setAliasDraft,
    isAliasBusy,
    handleAddClientNameAlias,
    handleRemoveClientNameAlias,
    renderSurveySummaryCard,
    currentUser,
    documents,
    memoizedRouter,
    interactions,
    huduClientTab.visible
  ]);

  const tabContent = useMemo(() => {
    if (!isAlgaDeskMode) {
      return baseTabContent;
    }

    const excludedTabs = new Set([
      'assets',
      'billing',
      'billing-dashboard',
      'documents',
      'tax-settings',
      'projects',
      'service-catalog',
      'services',
    ]);
    return baseTabContent.filter((tab) => !excludedTabs.has(tab.id));
  }, [baseTabContent, isAlgaDeskMode]);

  return (
    <ReflectionContainer id={id} label={t('clientDetails.title', { defaultValue: 'Client Details' })}>
      <div className="flex items-center space-x-5 mb-4 pt-2">
        {!quickView && (
          <BackNav href="/msp/clients">
            {isInDrawer
              ? t('common.actions.back', { defaultValue: 'Back' })
              : t('clientDetails.backToClients', { defaultValue: 'Back to Clients' })}
          </BackNav>
        )}
        
        {/* Logo Display and Edit Container */}
        <div className="flex items-center space-x-3">
          <EntityImageUpload
            entityType="client"
            entityId={editedClient.client_id}
            entityName={editedClient.client_name}
            imageUrl={editedClient.logoUrl ?? null}
            uploadAction={uploadClientLogo}
            deleteAction={deleteClientLogo}
            onImageChange={async (newLogoUrl) => {
              setEditedClient(prev => {
                if (!prev) return prev;
                return {
                  ...prev,
                  logoUrl: newLogoUrl
                };
              });
              
              // If logo was deleted (newLogoUrl is null), refresh client data to ensure consistency
              if (newLogoUrl === null) {
                await refreshClientData();
              }
            }}
            size="md"
          />
        </div>

        <div className="flex-1 flex items-center justify-between">
          <Heading size="6" tabIndex={quickView ? 0 : undefined} autoFocus={quickView}>
            {editedClient.client_name}
          </Heading>
          
          {isInDrawer && (
            <Button
              id={`${id}-open-in-new-tab-button`}
              onClick={() => window.open(`/msp/clients/${editedClient.client_id}`, '_blank')}
              variant="soft"
              size="sm"
              className="flex items-center ml-4 mr-2"
            >
              <ExternalLink className="h-4 w-4 mr-2" />
              {t('clientDetails.openInNewTab', { defaultValue: 'Open in new tab' })}
            </Button>
          )}

          <div className="flex items-center gap-2 mr-8" data-print-hide>
            {showEntraSyncAction && (
              <div className="flex flex-col items-end gap-1">
                <Button
                  id={`${id}-sync-entra-now-button`}
                  onClick={handleSyncEntraNow}
                  variant="outline"
                  size="sm"
                  className="flex items-center"
                  disabled={isSyncingEntra}
                >
                  {isSyncingEntra ? (
                    <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <RefreshCw className="h-4 w-4 mr-2" />
                  )}
                  {t('clientDetails.syncEntraNow', { defaultValue: 'Sync Entra Now' })}
                </Button>
                {entraSyncStatus ? (
                  <p
                    className="text-xs text-muted-foreground"
                    id={`${id}-sync-entra-status`}
                    title={entraSyncRunId || undefined}
                  >
                    {entraSyncStatus}
                  </p>
                ) : null}
              </div>
            )}
            <PrintButton
              id={`${id}-print-button`}
              variant="outline"
              size="sm"
            />
            <Button
              id={`${id}-delete-client-button`}
              onClick={handleDeleteClient}
              variant="destructive"
              size="sm"
              className="flex items-center"
            >
              <Trash2 className="h-4 w-4 mr-2" />
              {t('common.actions.delete', { defaultValue: 'Delete' })}
            </Button>
          </div>
        </div>
      </div>

      {/* Content Area */}
      <div data-print-region data-print-title={editedClient.client_name}>
        <div className="app-print-section">
          <PrintableDetailHeader
            title={editedClient.client_name}
            subtitle={[
              editedClient.client_type
                ? t(`clientsPage.clientTypes.${editedClient.client_type}`, {
                    defaultValue: editedClient.client_type,
                  })
                : undefined,
              editedClient.url,
            ].filter(Boolean).join(' — ')}
            fields={[
              {
                label: t('clientDetails.fields.accountManager', { defaultValue: 'Account Manager' }),
                value: editedClient.account_manager_full_name,
              },
              {
                label: t('clientDetails.fields.url', { defaultValue: 'URL' }),
                value: editedClient.url,
              },
              {
                label: t('clientDetails.fields.status', { defaultValue: 'Status' }),
                value: editedClient.is_inactive
                  ? t('common.states.inactive', { defaultValue: 'Inactive' })
                  : t('common.states.active', { defaultValue: 'Active' }),
              },
            ] satisfies PrintableDetailField[]}
          />
        </div>
        <CustomTabs
          tabs={quickView ? [tabContent[0]] : tabContent}
          // In quick view we only render the Details tab. Force default to details
          // to avoid a mismatch with the current page's ?tab= query (e.g. "Tickets").
          defaultTab={quickView ? 'details' : searchParams?.get('tab')?.toLowerCase() || 'details'}
          onTabChange={handleTabChange}
        />

        {renderQuickAddTicket({
          id: `${id}-quick-add-ticket`,
          open: isQuickAddTicketOpen,
          onOpenChange: setIsQuickAddTicketOpen,
          onTicketAdded: handleTicketAdded,
          prefilledClient: {
            id: editedClient.client_id,
            name: editedClient.client_name,
          },
        })}

        <Dialog
          isOpen={isLocationsDialogOpen}
          onClose={() => {
            setIsLocationsDialogOpen(false);
            setLocationsRefreshKey(prev => prev + 1);
          }}
          title={t('clientDetails.manageLocations', { defaultValue: 'Manage Locations' })}
        >
          <DialogContent className="max-w-4xl">
            <ClientLocations
              clientId={editedClient.client_id}
              isEditing={true}
            />
          </DialogContent>
        </Dialog>

        {/* Delete Confirmation Dialog */}
        <DeleteEntityDialog
          id="delete-client-dialog"
          isOpen={isDeleteDialogOpen}
          onClose={resetDeleteState}
          onConfirmDelete={confirmDelete}
          onAlternativeAction={handleDeleteAlternativeAction}
          entityName={editedClient.client_name}
          validationResult={deleteValidation}
          isValidating={isDeleteValidating}
          isDeleting={isDeleteProcessing}
        />

        {/* Deactivate Confirmation Dialog */}
        <ConfirmationDialog
          id="deactivate-client-dialog"
          isOpen={isDeactivateDialogOpen}
          onClose={handleCancelDeactivation}
          onConfirm={() => handleDeactivateClient(true)}
          title={t('clientDetails.deactivateClient', { defaultValue: 'Deactivate Client' })}
          message={
            <div className="space-y-3">
              <p>
                {t('clientDetails.deactivatePrompt', {
                  defaultValue: 'This client has {{count}} active contact(s). Would you like to deactivate them as well?',
                  count: activeContactsToDeactivate.length,
                })}
              </p>
              {activeContactsToDeactivate.length > 0 && (
                <div className="mt-3">
                  <p className="text-sm font-medium text-gray-700 mb-2">
                    {t('clientDetails.activeContacts', { defaultValue: 'Active contacts:' })}
                  </p>
                  <ul className="list-disc list-inside space-y-1 text-sm text-gray-600 max-h-40 overflow-y-auto">
                    {activeContactsToDeactivate.map((contact) => (
                      <li key={contact.contact_name_id}>
                        {contact.full_name}
                        {contact.email && ` (${contact.email})`}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
              <p className="text-sm text-gray-500 mt-2">
                {t('clientDetails.deactivatePortalWarning', {
                  defaultValue: 'Deactivated users will not be able to log into the client portal.',
                })}
              </p>
            </div>
          }
          confirmLabel={t('clientDetails.clientAndContacts', { defaultValue: 'Client & Contacts' })}
          cancelLabel={t('common.actions.cancel', { defaultValue: 'Cancel' })}
          onCancel={() => handleDeactivateClient(false)}
          thirdButtonLabel={t('clientDetails.clientOnly', { defaultValue: 'Client Only' })}
          isConfirming={false}
        />

        {/* Reactivate Confirmation Dialog */}
        <ConfirmationDialog
          id="reactivate-client-dialog"
          isOpen={isReactivateDialogOpen}
          onClose={handleCancelReactivation}
          onConfirm={() => handleReactivateClient(true)}
          title={t('clientDetails.reactivateClient', { defaultValue: 'Reactivate Client' })}
          message={
            <div className="space-y-3">
              <p>
                {t('clientDetails.reactivatePrompt', {
                  defaultValue: 'This client has {{count}} inactive contact(s). Would you like to reactivate them as well?',
                  count: inactiveContactsToReactivate.length,
                })}
              </p>
              {inactiveContactsToReactivate.length > 0 && (
                <div className="mt-3">
                  <p className="text-sm font-medium text-gray-700 mb-2">
                    {t('clientDetails.inactiveContacts', { defaultValue: 'Inactive contacts:' })}
                  </p>
                  <ul className="list-disc list-inside space-y-1 text-sm text-gray-600 max-h-40 overflow-y-auto">
                    {inactiveContactsToReactivate.map((contact) => (
                      <li key={contact.contact_name_id}>
                        {contact.full_name}
                        {contact.email && ` (${contact.email})`}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          }
          confirmLabel={t('clientDetails.clientAndContacts', { defaultValue: 'Client & Contacts' })}
          cancelLabel={t('common.actions.cancel', { defaultValue: 'Cancel' })}
          onCancel={() => handleReactivateClient(false)}
          thirdButtonLabel={t('clientDetails.clientOnly', { defaultValue: 'Client Only' })}
          isConfirming={false}
        />
      </div>
    </ReflectionContainer>
  );
};

const FieldContainer: React.FC<{
  label: string;
  fieldType: 'select' | 'textField';
  value: string;
  helperText: string;
  automationId?: string;
  children: React.ReactNode;
}> = ({ label, fieldType, value, helperText, automationId, children }) => {
  const { automationIdProps } = useAutomationIdAndRegister<FormFieldComponent>({
    type: 'formField',
    fieldType,
    label,
    value,
    helperText
  }, true, automationId);

  return (
    <div className="space-y-2" {...automationIdProps}>
      {children}
    </div>
  );
};

export default ClientDetails;
