import { CommonModule } from '@angular/common';
import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ButtonModule } from '@progress/kendo-angular-buttons';

import { CashlineApiService } from '../core/cashline-api.service';
import { CutoverI18nService } from '../core/cutover-i18n.service';
import { canAccessJourney, defaultJourneyId, isAdministratorSession, isSystemOwnerSession, journeyIdFromRoutePath, resolveJourneyRoute } from '../core/uat-access.util';
import { getDefaultJourneyStepId } from '../journeys/journey-definitions';
import { JourneyId } from '../journeys/journey.models';

@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [CommonModule, FormsModule, ButtonModule],
  template: `
    <section class="login-page" [attr.dir]="i18n.dir()">
      <div class="login-layout">
        <article class="surface-card login-card">
          <div class="surface-card__header">
            <div>
              <h2>{{ t('Sign in') }}</h2>
            </div>
          </div>
          <div class="surface-card__body">
            <form class="login-form" (ngSubmit)="signIn()">
              <label class="field-card">
                <span class="field-label">{{ t('Email or username') }}</span>
                <input
                  type="text"
                  name="username"
                  autocomplete="username"
                  [(ngModel)]="username"
                  [placeholder]="t('Enter your assigned email or username')"
                />
              </label>

              <label class="field-card">
                <span class="field-label">{{ t('Password') }}</span>
                <input
                  type="password"
                  name="password"
                  autocomplete="current-password"
                  [(ngModel)]="password"
                  [placeholder]="t('Enter your password')"
                />
              </label>

              <div class="login-actions">
                <button kendoButton type="submit" class="primary-action-btn" [disabled]="loading || !canSignIn">
                  {{ t('Sign in') }}
                </button>
              </div>
            </form>

            <div class="feedback success" *ngIf="messageText">{{ t(messageText) }}</div>
            <div class="feedback error" *ngIf="errorText">{{ t(errorText) }}</div>

            <div class="support-note demo-entry">
              <strong>{{ t('Open the full interactive demo') }}</strong>
              <p>{{ t('Launch role-based personas, move through real journeys, and use the guided walkthroughs as a practical user manual during demos, onboarding, and stakeholder reviews.') }}</p>
              <div class="login-actions">
                <button kendoButton type="button" fillMode="outline" class="secondary-action-btn" (click)="openDemoCenter()">
                  {{ t('Open demo center') }}
                </button>
              </div>
            </div>

            <div class="support-note onboarding-entry">
              <strong>{{ t('Become a Customer or Supplier') }}</strong>
              <p *ngIf="prospectType === 'supplier'">
                {{ t('The CashLine Supplier Portal is a secure self-service platform that enables suppliers to complete onboarding, manage company and compliance documents, track requests and orders, submit invoices, and follow transaction status in one place.') }}
              </p>

              <div class="lead-grid">
                <label class="field-card">
                  <span class="field-label">{{ t('I want to become') }}</span>
                  <select name="prospectType" [(ngModel)]="prospectType">
                    <option value="customer">{{ t('Customer') }}</option>
                    <option value="supplier">{{ t('Supplier') }}</option>
                  </select>
                </label>

                <label class="field-card">
                  <span class="field-label">{{ t('Company name') }}</span>
                  <input type="text" name="leadCompanyName" [(ngModel)]="leadCompanyName" />
                </label>

                <label class="field-card">
                  <span class="field-label">{{ t('Contact name') }}</span>
                  <input type="text" name="leadContactName" [(ngModel)]="leadContactName" />
                </label>

                <label class="field-card">
                  <span class="field-label">{{ t('Email') }}</span>
                  <input type="email" name="leadEmail" [(ngModel)]="leadEmail" />
                </label>

                <label class="field-card">
                  <span class="field-label">{{ t('Mobile number') }}</span>
                  <input type="text" name="leadMobileNumber" [(ngModel)]="leadMobileNumber" />
                </label>
              </div>

              <div class="login-actions">
                <button kendoButton type="button" class="primary-action-btn" [disabled]="submittingLead || !canStartLead" (click)="startLeadOnboarding()">
                  {{ t('Continue onboarding') }}
                </button>
              </div>

              <div class="feedback success" *ngIf="leadMessageText">{{ t(leadMessageText) }}</div>
              <div class="feedback error" *ngIf="leadErrorText">{{ t(leadErrorText) }}</div>
            </div>
          </div>
        </article>
      </div>
    </section>
  `,
  styles: [`
    :host {
      display: block;
    }

    .login-page {
      display: grid;
      gap: 20px;
    }

    .login-layout {
      display: grid;
      grid-template-columns: minmax(460px, 760px);
      justify-content: center;
    }

    .surface-card {
      width: 100%;
      border: 1px solid var(--card-frame);
      border-radius: var(--radius-2xl);
      background: var(--paper-strong);
      box-shadow: var(--shadow-lg);
      backdrop-filter: blur(20px);
      overflow: hidden;
    }

    .intro-card {
      background:
        linear-gradient(180deg, rgba(255,255,255,.97), rgba(245,241,233,.94)),
        linear-gradient(135deg, rgba(23,71,104,.06), rgba(183,130,54,.05));
    }

    .surface-card__header,
    .surface-card__body {
      padding: 22px;
    }

    .surface-card__header {
      border-bottom: 1px solid rgba(15, 35, 95, 0.08);
      background: linear-gradient(180deg, rgba(255,255,255,.6), rgba(255,255,255,0));
    }

    h2 {
      margin: 0;
      font-size: clamp(1.7rem, 2.4vw, 2.4rem);
      line-height: 1.08;
      letter-spacing: -0.03em;
    }

    .intro-card__copy {
      display: grid;
      gap: 10px;
    }

    .intro-card__meta {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }

    .package-grid {
      display: grid;
      gap: 10px;
      margin-top: 16px;
    }

    .intro-chip {
      display: inline-flex;
      align-items: center;
      min-height: 32px;
      padding: 7px 11px;
      border-radius: 999px;
      border: 1px solid var(--card-frame);
      background: color-mix(in srgb, var(--brand-primary) 12%, rgba(255,255,255,.86));
      color: var(--ink);
      font-size: 0.78rem;
      font-weight: 700;
      box-shadow: inset 0 1px 0 rgba(255,255,255,.45);
    }

    p,
    .support-note,
    .field-card small {
      color: var(--muted);
      line-height: 1.6;
    }

    .eyebrow,
    .meta-label {
      display: block;
      color: var(--muted);
      text-transform: uppercase;
      letter-spacing: 0.11em;
      font-size: 0.72rem;
      margin-bottom: 6px;
    }

    .intro-points {
      display: grid;
      gap: 12px;
    }

    .intro-point,
    .package-card,
    .field-card,
    .support-note,
    .feedback {
      border: 1px solid var(--card-frame);
      border-radius: var(--radius-xl);
      background: rgba(255, 255, 255, 0.84);
    }

    .intro-point,
    .package-card,
    .field-card {
      padding: 15px 16px;
      display: grid;
      gap: 5px;
    }

    .package-card strong {
      line-height: 1.35;
    }

    .package-card {
      position: relative;
      overflow: hidden;
      transition: transform 180ms ease, border-color 180ms ease, box-shadow 180ms ease, background 180ms ease;
    }

    .package-card::after {
      content: '';
      position: absolute;
      inset: 0;
      background: linear-gradient(120deg, transparent 0%, rgba(255,255,255,.28) 48%, transparent 100%);
      opacity: 0;
      transform: translateX(-20%);
      pointer-events: none;
      transition: opacity 180ms ease, transform 240ms cubic-bezier(0.22, 1, 0.36, 1);
    }

    .package-card:hover {
      transform: translateY(-1px);
      border-color: var(--card-frame-strong);
      box-shadow: 0 10px 22px rgba(20, 30, 48, 0.06);
      background: rgba(255, 255, 255, 0.94);
    }

    .package-card:hover::after {
      opacity: 1;
      transform: translateX(0);
    }

    .login-form {
      display: grid;
      gap: 14px;
    }

    .field-label {
      font-weight: 700;
      color: var(--ink);
    }

    input {
      width: 100%;
      min-height: 50px;
      border-radius: 14px;
      border: 1px solid color-mix(in srgb, var(--card-frame) 68%, var(--line-strong));
      background: rgba(255, 255, 255, 0.98);
      padding: 0 14px;
      color: var(--ink);
      font: inherit;
    }

    input:focus {
      outline: 2px solid rgba(24, 23, 22, 0.1);
      border-color: rgba(24, 23, 22, 0.2);
    }

    .login-actions {
      display: flex;
      justify-content: flex-start;
      margin-top: 6px;
    }

    .primary-action-btn {
      width: auto;
      min-width: 148px;
      min-height: 42px;
      justify-content: center;
      text-align: center;
    }

    .secondary-action-btn {
      min-width: 160px;
      min-height: 42px;
    }

    .primary-action-btn :is(.k-button-text, span) {
      width: auto;
      text-align: center;
      line-height: 1.2;
    }

    .feedback,
    .support-note {
      margin-top: 14px;
      padding: 13px 15px;
    }

    .feedback.success {
      background: rgba(15, 113, 87, 0.12);
      color: #0f7157;
    }

    .feedback.error {
      background: rgba(169, 68, 66, 0.12);
      color: #a94442;
    }

    select {
      width: 100%;
      min-height: 50px;
      border-radius: 14px;
      border: 1px solid color-mix(in srgb, var(--card-frame) 68%, var(--line-strong));
      background: rgba(255, 255, 255, 0.98);
      padding-inline-start: 14px;
      padding-inline-end: 42px;
      color: var(--ink);
      font: inherit;
    }

    .onboarding-entry {
      display: grid;
      gap: 12px;
    }

    .onboarding-entry p {
      margin: 0;
    }

    .lead-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
      gap: 12px;
    }

    :host-context([dir='rtl']) .eyebrow,
    :host-context([dir='rtl']) .meta-label {
      text-transform: none;
      letter-spacing: 0.02em;
    }

    :host-context([dir='rtl']) .surface-card__header,
    :host-context([dir='rtl']) .surface-card__body,
    :host-context([dir='rtl']) .intro-card__copy,
    :host-context([dir='rtl']) .intro-point,
    :host-context([dir='rtl']) .package-card,
    :host-context([dir='rtl']) .field-card,
    :host-context([dir='rtl']) .support-note,
    :host-context([dir='rtl']) .feedback {
      text-align: right;
    }

    :host-context([dir='rtl']) .package-card::after {
      transform: translateX(20%);
    }

    :host-context([dir='rtl']) .primary-action-btn {
      text-align: center;
    }

    @media (max-width: 720px) {
      .primary-action-btn {
        width: 100%;
      }
    }

    @media (max-width: 980px) {
      .login-layout {
        grid-template-columns: 1fr;
      }
    }

    @media (max-width: 720px) {
      .surface-card__header,
      .surface-card__body {
        padding: 18px;
      }
    }
  `]
})
export class LoginPageComponent implements OnInit {
  private readonly api = inject(CashlineApiService);
  private readonly router = inject(Router);
  private readonly route = inject(ActivatedRoute);
  protected readonly i18n = inject(CutoverI18nService);

  protected username = '';
  protected password = '';
  protected loading = false;
  protected messageText = '';
  protected errorText = '';
  protected prospectType: 'customer' | 'supplier' = 'customer';
  protected leadCompanyName = '';
  protected leadContactName = '';
  protected leadEmail = '';
  protected leadMobileNumber = '';
  protected leadMessageText = '';
  protected leadErrorText = '';
  protected submittingLead = false;
  private returnUrl = '';

  async ngOnInit(): Promise<void> {
    this.returnUrl = this.route.snapshot.queryParamMap.get('returnUrl') ?? '';
    const session = this.api.currentSession;
    if (session) {
      if (isAdministratorSession(session) || isSystemOwnerSession(session)) {
        await this.router.navigateByUrl('/internal/user-administration');
        return;
      }

      const requestedJourneyId = journeyIdFromRoutePath(this.returnUrl);
      if (requestedJourneyId && !canAccessJourney(session, requestedJourneyId)) {
        await this.router.navigateByUrl(this.resolvePostLoginTarget(defaultJourneyId(session)));
        return;
      }

      await this.router.navigateByUrl(this.resolvePostLoginTarget(requestedJourneyId ?? defaultJourneyId(session)));
    }
  }

  protected get canSignIn(): boolean {
    return this.username.trim().length > 0 && this.password.length > 0;
  }

  protected get canStartLead(): boolean {
    return this.leadEmail.trim().length > 0 || this.leadMobileNumber.trim().length > 0;
  }

  protected get shellTitle(): string {
    return this.isLocalhostWorkspace()
      ? 'CashLine ERP Localhost'
      : 'CashLine ERP UAT';
  }

  protected get introEyebrow(): string {
    return this.isLocalhostWorkspace()
      ? 'Local business workspace'
      : 'Formal UAT Release';
  }

  protected get introSummary(): string {
    return this.isLocalhostWorkspace()
      ? 'Governed frontend packages separate internal users, suppliers, and customers into focused business workspaces.'
      : 'A live-like role-based entry point for governed supplier, customer, and internal frontend packages during formal user acceptance testing.';
  }

  protected get testingPosture(): string {
    return this.isLocalhostWorkspace()
      ? 'Use your assigned business account to enter the focused frontend package enabled for your role.'
      : 'Use the credentials assigned by UAT coordination for your specific business role.';
  }

  protected get signInPrompt(): string {
    return this.isLocalhostWorkspace()
      ? 'Enter your assigned email or username and password to access the business workspace.'
      : 'Enter your assigned UAT email or username and password to access the system.';
  }

  protected get accessNote(): string {
    return this.isLocalhostWorkspace()
      ? 'If your role requires additional approval or verification, continue with the credentials provided by CashLine Operations.'
      : 'If your role requires additional approval or verification, continue with the credentials provided by the UAT coordinator.';
  }

  protected t(value: string): string {
    return this.i18n.text(value);
  }

  protected async signIn(): Promise<void> {
    if (!this.canSignIn) {
      return;
    }

    this.loading = true;
    this.messageText = '';
    this.errorText = '';

    try {
      const session = await this.api.authenticate(this.username.trim(), this.password, 'WEB_PORTAL');
      this.messageText = `Signed in as ${session.displayName}.`;
      if (isAdministratorSession(session) || isSystemOwnerSession(session)) {
        await this.router.navigateByUrl('/internal/user-administration');
        return;
      }

      const requestedJourneyId = journeyIdFromRoutePath(this.returnUrl);
      const targetJourneyId = requestedJourneyId && canAccessJourney(session, requestedJourneyId)
        ? requestedJourneyId
        : defaultJourneyId(session);
      await this.router.navigateByUrl(this.resolvePostLoginTarget(targetJourneyId));
    } catch (error) {
      this.errorText = error instanceof Error ? error.message : 'Unable to sign in to the current environment.';
    } finally {
      this.loading = false;
    }
  }

  protected async startLeadOnboarding(): Promise<void> {
    if (!this.canStartLead) {
      return;
    }

    this.submittingLead = true;
    this.leadMessageText = '';
    this.leadErrorText = '';

    try {
      const lead = await this.api.post('/api/v1/public/onboarding/leads', {
        prospectTypeCode: this.prospectType.toUpperCase(),
        companyName: this.leadCompanyName || null,
        contactName: this.leadContactName || null,
        email: this.leadEmail || null,
        mobileNumber: this.leadMobileNumber || null,
        notes: null
      }, false) as { leadCode: string };

      this.leadMessageText = 'Lead captured. Continuing to onboarding.';
      await this.router.navigate(['/become', this.prospectType], {
        queryParams: { leadCode: lead.leadCode }
      });
    } catch (error) {
      this.leadErrorText = error instanceof Error ? error.message : 'Unable to start onboarding right now.';
    } finally {
      this.submittingLead = false;
    }
  }

  protected async openDemoCenter(): Promise<void> {
    await this.router.navigate(['/demo-center']);
  }

  private isLocalhostWorkspace(): boolean {
    if (typeof window === 'undefined') {
      return false;
    }

    const desktopConfig = (window as Window & {
      cashlineDesktopConfig?: { environmentLabel?: string; apiBaseUrl?: string; shellUrl?: string };
    }).cashlineDesktopConfig;

    const environmentLabel = desktopConfig?.environmentLabel?.toLowerCase() ?? '';
    const apiBaseUrl = desktopConfig?.apiBaseUrl?.toLowerCase() ?? '';
    const shellUrl = desktopConfig?.shellUrl?.toLowerCase() ?? '';
    const currentOrigin = window.location.origin.toLowerCase();

    return environmentLabel.includes('localhost')
      || apiBaseUrl.includes('localhost:5080')
      || shellUrl.includes('localhost:5080')
      || currentOrigin.includes('localhost:5080');
  }

  private resolvePostLoginTarget(fallbackJourneyId: string): string {
    const requestedJourneyId = journeyIdFromRoutePath(this.returnUrl);
    if (this.returnUrl.startsWith('/') && requestedJourneyId && requestedJourneyId === fallbackJourneyId) {
      return this.returnUrl;
    }

    const defaultStepId = getDefaultJourneyStepId(fallbackJourneyId as JourneyId);
    return `${resolveJourneyRoute(fallbackJourneyId as JourneyId)}?step=${encodeURIComponent(defaultStepId)}`;
  }
}
