import { inject, effect, Signal, DestroyRef } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { TabService } from '@isa/core/tabs';
import { PageTitleInput } from './title-management.types';
import { TitleRegistryService } from './title-registry.service';
import { TITLE_PREFIX } from './title-prefix';

/**
 * Reactive helper function for managing dynamic page titles and subtitles in components.
 * Uses Angular signals and effects to automatically update the document title
 * and tab name/subtitle whenever the provided signal changes.
 *
 * This is ideal for pages where the title depends on component state, such as:
 * - Search pages with query terms
 * - Detail pages with item names
 * - Wizard flows with step names
 * - Filter pages with applied filters
 * - Status indicators with changing subtitles
 *
 * @param titleSubtitleSignal - A signal containing optional title and subtitle
 *
 * @example
 * ```typescript
 * // Basic usage with static title
 * import { Component, signal } from '@angular/core';
 * import { usePageTitle } from '@isa/common/title-management';
 *
 * @Component({
 *   selector: 'app-dashboard',
 *   template: `<h1>Dashboard</h1>`
 * })
 * export class DashboardComponent {
 *   pageTitle = signal({ title: 'Dashboard' });
 *
 *   constructor() {
 *     usePageTitle(this.pageTitle);
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Dynamic title with search term
 * import { Component, signal, computed } from '@angular/core';
 * import { usePageTitle } from '@isa/common/title-management';
 *
 * @Component({
 *   selector: 'app-article-search',
 *   template: `<input [(ngModel)]="searchTerm" />`
 * })
 * export class ArticleSearchComponent {
 *   searchTerm = signal('');
 *
 *   pageTitle = computed(() => {
 *     const term = this.searchTerm();
 *     return {
 *       title: term ? `Artikelsuche - "${term}"` : 'Artikelsuche'
 *     };
 *   });
 *
 *   constructor() {
 *     usePageTitle(this.pageTitle);
 *     // Title updates automatically when searchTerm changes!
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Title with subtitle
 * import { Component, signal, computed } from '@angular/core';
 * import { usePageTitle } from '@isa/common/title-management';
 *
 * @Component({
 *   selector: 'app-order-details',
 *   template: `<h1>Order Details</h1>`
 * })
 * export class OrderDetailsComponent {
 *   orderId = signal('12345');
 *   orderStatus = signal<'pending' | 'processing' | 'complete'>('pending');
 *
 *   statusLabels = {
 *     pending: 'Awaiting Payment',
 *     processing: 'In Progress',
 *     complete: 'Completed'
 *   };
 *
 *   pageTitle = computed(() => ({
 *     title: `Order ${this.orderId()}`,
 *     subtitle: this.statusLabels[this.orderStatus()]
 *   }));
 *
 *   constructor() {
 *     usePageTitle(this.pageTitle);
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Skip title when undefined (e.g., data not loaded yet)
 * import { Component, signal, computed } from '@angular/core';
 * import { usePageTitle } from '@isa/common/title-management';
 *
 * @Component({
 *   selector: 'app-product-details',
 *   template: `<h1>{{ productName() || 'Loading...' }}</h1>`
 * })
 * export class ProductDetailsComponent {
 *   productName = signal<string | null>(null);
 *
 *   pageTitle = computed(() => {
 *     const name = this.productName();
 *     return {
 *       title: name ? `Product - ${name}` : undefined
 *     };
 *   });
 *
 *   constructor() {
 *     usePageTitle(this.pageTitle);
 *     // Title only updates when productName is not null
 *   }
 * }
 * ```
 *
 * @example
 * ```typescript
 * // Nested components - child component's title automatically takes precedence
 * // Parent component (route: /dashboard)
 * export class DashboardComponent {
 *   pageTitle = signal({ title: 'Dashboard' });
 *   constructor() {
 *     usePageTitle(this.pageTitle); // "ISA - Dashboard"
 *   }
 * }
 *
 * // Child component (route: /dashboard/settings)
 * export class SettingsComponent {
 *   pageTitle = signal({ title: 'Settings' });
 *   constructor() {
 *     usePageTitle(this.pageTitle); // "ISA - Settings" (wins!)
 *   }
 * }
 * // When SettingsComponent is destroyed → "ISA - Dashboard" (automatically restored)
 * ```
 */
export function usePageTitle(
  titleSubtitleSignal: Signal<PageTitleInput>
): void {
  const title = inject(Title);
  const titlePrefix = inject(TITLE_PREFIX);
  const tabService = inject(TabService);
  const registry = inject(TitleRegistryService);
  const destroyRef = inject(DestroyRef);

  // Create the updater function that will be called by the registry
  const updateTitle = () => {
    const { title: pageTitle, subtitle } = titleSubtitleSignal();

    // Update document title if title is defined
    if (pageTitle !== undefined) {
      const fullTitle = `${titlePrefix} - ${pageTitle}`;
      title.setTitle(fullTitle);
    }

    // Update tab if activeTabId exists
    const activeTabId = tabService.activatedTabId();
    if (activeTabId !== null) {
      // Build patch object conditionally based on what's defined
      const patch: { name?: string; subtitle?: string } = {};

      if (pageTitle !== undefined) {
        patch.name = pageTitle;
      }

      if (subtitle !== undefined) {
        patch.subtitle = subtitle;
      }

      // Only patch if we have something to update
      if (Object.keys(patch).length > 0) {
        tabService.patchTab(activeTabId, patch);
      }
    }
  };

  // Register with the registry (this will execute updateTitle immediately)
  const registrationId = registry.register(updateTitle);

  // Automatically unregister when component is destroyed
  destroyRef.onDestroy(() => {
    registry.unregister(registrationId);
  });

  // React to signal changes, but only update if this is the active registration
  effect(() => {
    // Access the signal to track it as a dependency
    titleSubtitleSignal();

    // Only update if this component is the active one
    registry.updateIfActive(registrationId, updateTitle);
  });
}
