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';

interface UploadedComplianceDocument {
  documentType: string;
  fileName: string;
  storageReference: string;
  storageProviderCode: string;
  contentType: string;
  fileSizeBytes: number;
}

interface PrivacyGovernanceResponse {
  notices: PrivacyNoticeResponse[];
}

interface PrivacyNoticeResponse {
  subjectTypeCode: string;
  noticeCode: string;
  version: string;
  title: string;
  summary: string;
  requiresExplicitAcceptance: boolean;
}

@Component({
  selector: 'app-public-onboarding-page',
  standalone: true,
  imports: [CommonModule, FormsModule, ButtonModule],
  template: `
    <section class="public-onboarding" [attr.dir]="i18n.dir()">
      <article class="surface-card">
        <div class="surface-card__header">
          <p class="eyebrow">{{ t('Pre-login onboarding') }}</p>
          <h2>{{ t(pageTitle) }}</h2>
          <p>{{ t(pageSummary) }}</p>
        </div>
        <div class="surface-card__body form-stack">
          <div class="status-strip">
            <span class="status-pill">{{ t('Onboarding-only access') }}</span>
            <span class="status-pill">{{ t('Operations review required') }}</span>
            <span class="status-pill">{{ t('Business features locked until activation') }}</span>
          </div>

          <div class="info-banner">
            <strong>{{ t('Lead reference') }}:</strong>
            <span>{{ leadCode || t('Not captured yet') }}</span>
          </div>

          <section class="form-section">
            <h3>{{ t('Basic lead information') }}</h3>
            <div class="grid two-up">
              <label class="field-card">
                <span class="field-label">{{ t('Company name') }}</span>
                <input type="text" [(ngModel)]="companyName" name="companyName" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Contact name') }}</span>
                <input type="text" [(ngModel)]="contactName" name="contactName" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Email') }}</span>
                <input type="email" [(ngModel)]="email" name="email" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Mobile number') }}</span>
                <input type="text" [(ngModel)]="mobileNumber" name="mobileNumber" />
              </label>
            </div>
          </section>

          <section class="form-section">
            <h3>{{ t('Onboarding details') }}</h3>
            <div class="grid two-up">
              <label class="field-card">
                <span class="field-label">{{ t('Country code') }}</span>
                <input type="text" [(ngModel)]="countryCode" name="countryCode" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Address') }}</span>
                <input type="text" [(ngModel)]="addressLine1" name="addressLine1" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Tax registration number') }}</span>
                <input type="text" [(ngModel)]="taxRegistrationNumber" name="taxRegistrationNumber" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Tax branch code') }}</span>
                <input type="text" [(ngModel)]="taxBranchCode" name="taxBranchCode" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Firm national ID (Egypt)') }}</span>
                <input type="text" [(ngModel)]="firmNationalId" name="firmNationalId" />
              </label>
            </div>

            <div class="grid two-up" *ngIf="prospectType === 'supplier'; else customerFields">
              <label class="field-card">
                <span class="field-label">{{ t('Supplier category') }}</span>
                <select [(ngModel)]="supplierCategoryCode" name="supplierCategoryCode">
                  <option value="core">{{ t('Core supplier') }}</option>
                  <option value="service">{{ t('Service supplier') }}</option>
                  <option value="project">{{ t('Project supplier') }}</option>
                </select>
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Default currency') }}</span>
                <input type="text" [(ngModel)]="defaultCurrencyCode" name="defaultCurrencyCode" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Preferred payment method') }}</span>
                <input type="text" [(ngModel)]="preferredPaymentMethodCode" name="preferredPaymentMethodCode" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Payment terms days') }}</span>
                <input type="number" [(ngModel)]="paymentTermsDays" name="paymentTermsDays" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Lead time days') }}</span>
                <input type="number" [(ngModel)]="supplierLeadTimeDays" name="supplierLeadTimeDays" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Minimum order amount') }}</span>
                <input type="number" [(ngModel)]="minimumOrderAmount" name="minimumOrderAmount" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Bank name') }}</span>
                <input type="text" [(ngModel)]="bankName" name="bankName" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Bank account number') }}</span>
                <input type="text" [(ngModel)]="bankAccountNumber" name="bankAccountNumber" />
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('Bank swift code') }}</span>
                <input type="text" [(ngModel)]="bankSwiftCode" name="bankSwiftCode" />
              </label>
            </div>

            <ng-template #customerFields>
              <div class="grid two-up">
                <label class="field-card">
                  <span class="field-label">{{ t('Customer classification') }}</span>
                  <input type="text" [(ngModel)]="customerClassificationCode" name="customerClassificationCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Customer segment') }}</span>
                  <input type="text" [(ngModel)]="customerSegmentCode" name="customerSegmentCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Default currency') }}</span>
                  <input type="text" [(ngModel)]="defaultCurrencyCode" name="customerDefaultCurrencyCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Sales channel') }}</span>
                  <input type="text" [(ngModel)]="salesChannelCode" name="salesChannelCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Price tier') }}</span>
                  <input type="text" [(ngModel)]="priceTierCode" name="priceTierCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Invoice delivery method') }}</span>
                  <input type="text" [(ngModel)]="invoiceDeliveryMethodCode" name="invoiceDeliveryMethodCode" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Credit limit amount') }}</span>
                  <input type="number" [(ngModel)]="creditLimitAmount" name="creditLimitAmount" />
                </label>
                <label class="field-card">
                  <span class="field-label">{{ t('Credit terms days') }}</span>
                  <input type="number" [(ngModel)]="creditTermsDays" name="creditTermsDays" />
                </label>
              </div>
            </ng-template>
          </section>

          <section class="form-section">
            <h3>{{ t('KYC documents') }}</h3>
            <div class="grid two-up">
              <label class="field-card">
                <span class="field-label">{{ t('Document type') }}</span>
                <select [(ngModel)]="documentType" name="documentType">
                  <option [value]="supplierDocumentOptionValue">{{ t(supplierDocumentOptionLabel) }}</option>
                  <option value="tax_card">{{ t('Tax card') }}</option>
                  <option value="bank_letter">{{ t('Bank letter') }}</option>
                  <option value="billing_instruction">{{ t('Billing instruction') }}</option>
                </select>
              </label>
              <label class="field-card">
                <span class="field-label">{{ t('PDF or image file') }}</span>
                <input type="file" accept=".pdf,image/png,image/jpeg" (change)="onFileSelected($event)" />
              </label>
            </div>
            <div class="action-row">
              <button kendoButton type="button" class="workflow-action-btn" [disabled]="uploadingDocument || !selectedFile" (click)="uploadDocument()">
                {{ t('Upload document') }}
              </button>
            </div>
            <div class="feedback success" *ngIf="uploadMessage">{{ uploadMessage }}</div>
            <div class="feedback error" *ngIf="uploadError">{{ uploadError }}</div>
            <div class="document-list" *ngIf="uploadedDocuments.length > 0">
              <div class="document-card" *ngFor="let document of uploadedDocuments">
                <strong>{{ document.fileName }}</strong>
                <span>{{ document.documentType }}</span>
              </div>
            </div>
          </section>

          <label class="field-card">
            <span class="field-label">{{ t('Notes') }}</span>
            <textarea rows="4" [(ngModel)]="notes" name="notes"></textarea>
          </label>

          <label class="privacy-acceptance" *ngIf="privacyNotice">
            <input type="checkbox" [(ngModel)]="privacyAccepted" name="privacyAccepted" />
            <span>
              <strong>{{ t(privacyNotice.title) }}</strong>
              <small>{{ t(privacyNotice.summary) }}</small>
              <em>{{ t('Notice version') }} {{ privacyNotice.version }}</em>
            </span>
          </label>

          <div class="action-row">
            <button kendoButton type="button" class="workflow-action-btn" [disabled]="submitting || isPrivacyAcceptanceRequired" (click)="submit()">
              {{ t('Submit onboarding for operations review') }}
            </button>
            <button kendoButton type="button" fillMode="outline" class="secondary-action-btn" (click)="backToLogin()">
              {{ t('Back to sign in') }}
            </button>
          </div>

          <div class="feedback success" *ngIf="messageText">{{ messageText }}</div>
          <div class="feedback error" *ngIf="errorText">{{ errorText }}</div>
        </div>
      </article>
    </section>
  `,
  styles: [`
    :host { display: block; }
    .public-onboarding { display: grid; gap: 20px; }
    .surface-card { border: 1px solid var(--card-frame); border-radius: var(--radius-2xl); background: var(--paper-strong); box-shadow: var(--shadow-lg); overflow: hidden; }
    .surface-card__header, .surface-card__body { padding: 24px; }
    .surface-card__header { border-bottom: 1px solid rgba(15, 35, 95, 0.08); }
    .form-stack { display: grid; gap: 18px; }
    .status-strip { display: flex; flex-wrap: wrap; gap: 10px; }
    .status-pill { display: inline-flex; align-items: center; padding: 8px 12px; border-radius: 999px; border: 1px solid var(--card-frame); background: color-mix(in srgb, var(--brand-primary) 12%, rgba(255,255,255,0.88)); color: var(--ink); font-weight: 700; font-size: .84rem; }
    .form-section { display: grid; gap: 14px; }
    .grid { display: grid; gap: 14px; }
    .two-up { grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); }
    .field-card { display: grid; gap: 8px; border: 1px solid var(--card-frame); border-radius: var(--radius-xl); background: rgba(255,255,255,0.85); padding: 16px; }
    .field-label, h2, h3 { margin: 0; color: var(--ink); }
    .eyebrow { text-transform: uppercase; letter-spacing: .12em; font-size: .76rem; color: var(--muted); }
    input, select, textarea { width: 100%; min-height: 46px; border-radius: 12px; border: 1px solid color-mix(in srgb, var(--card-frame) 68%, var(--line-strong)); padding: 10px 12px; font: inherit; }
    textarea { min-height: 110px; }
    .action-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: flex-start; }
    .workflow-action-btn,
    .secondary-action-btn {
      width: auto;
      min-width: 180px;
      max-width: 320px;
      min-height: 36px;
      border-radius: 14px;
      justify-content: center;
    }
    .workflow-action-btn {
      background: linear-gradient(180deg, rgba(188, 113, 34, 0.9), rgba(142, 82, 25, 0.9));
      border-color: rgba(142, 82, 25, 0.42);
      box-shadow: 0 6px 16px rgba(142, 82, 25, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.12);
    }
    .secondary-action-btn {
      background: linear-gradient(180deg, rgba(246, 240, 231, 0.96), rgba(235, 228, 216, 0.96));
      border-color: rgba(160, 137, 112, 0.34);
      color: color-mix(in srgb, var(--ink) 82%, #6e5636);
      box-shadow: 0 4px 12px rgba(123, 101, 71, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.3);
    }
    .workflow-action-btn .k-button-text,
    .secondary-action-btn .k-button-text {
      width: auto;
      font-size: 0.78rem;
      line-height: 1.15;
    }
    [dir='rtl'] .workflow-action-btn .k-button-text,
    [dir='rtl'] .secondary-action-btn .k-button-text { font-size: 0.76rem; }
    .feedback { border-radius: 14px; padding: 12px 14px; }
    .feedback.success { background: rgba(15, 113, 87, 0.12); color: #0f7157; }
    .feedback.error { background: rgba(169, 68, 66, 0.12); color: #a94442; }
    .info-banner { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; border: 1px solid var(--card-frame); border-radius: 18px; background: rgba(255,255,255,0.9); padding: 12px 14px; }
    .privacy-acceptance { display: flex; gap: 12px; align-items: flex-start; border: 1px solid color-mix(in srgb, var(--brand-primary) 38%, var(--card-frame)); border-radius: 18px; background: color-mix(in srgb, var(--brand-primary) 8%, rgba(255,255,255,0.92)); padding: 14px 16px; color: var(--ink); }
    .privacy-acceptance input { width: 18px; min-height: 18px; margin-top: 3px; accent-color: var(--brand-primary); }
    .privacy-acceptance span { display: grid; gap: 4px; }
    .privacy-acceptance small { color: var(--muted); line-height: 1.45; }
    .privacy-acceptance em { color: color-mix(in srgb, var(--ink) 70%, var(--brand-primary)); font-size: 0.78rem; font-style: normal; font-weight: 700; }
    .document-list { display: grid; gap: 10px; }
    .document-card { display: grid; gap: 4px; border: 1px solid var(--card-frame); border-radius: 18px; background: rgba(255,255,255,0.84); padding: 12px 14px; }
    @media (max-width: 720px) {
      .workflow-action-btn,
      .secondary-action-btn { width: 100%; min-width: 0; max-width: none; }
    }
  `]
})
export class PublicOnboardingPageComponent implements OnInit {
  private readonly api = inject(CashlineApiService);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  protected readonly i18n = inject(CutoverI18nService);

  protected prospectType: 'supplier' | 'customer' = 'supplier';
  protected leadCode = '';
  protected companyName = '';
  protected contactName = '';
  protected email = '';
  protected mobileNumber = '';
  protected countryCode = 'EG';
  protected addressLine1 = '';
  protected taxRegistrationNumber = '';
  protected taxBranchCode = '';
  protected firmNationalId = '';
  protected notes = '';

  protected supplierCategoryCode = 'core';
  protected defaultCurrencyCode = 'EGP';
  protected preferredPaymentMethodCode = 'BANK_TRANSFER';
  protected paymentTermsDays = 30;
  protected supplierLeadTimeDays = 14;
  protected minimumOrderAmount: number | null = null;
  protected bankName = '';
  protected bankAccountNumber = '';
  protected bankSwiftCode = '';

  protected customerClassificationCode = 'COMPANY';
  protected customerSegmentCode = 'STANDARD';
  protected salesChannelCode = 'DIRECT';
  protected priceTierCode = 'STANDARD';
  protected invoiceDeliveryMethodCode = 'EMAIL';
  protected creditLimitAmount: number | null = null;
  protected creditTermsDays: number | null = null;

  protected documentType = 'commercial_register';
  protected selectedFile: File | null = null;
  protected uploadedDocuments: UploadedComplianceDocument[] = [];
  protected uploadMessage = '';
  protected uploadError = '';
  protected messageText = '';
  protected errorText = '';
  protected submitting = false;
  protected uploadingDocument = false;
  protected privacyNotice: PrivacyNoticeResponse | null = null;
  protected privacyAccepted = false;

  async ngOnInit(): Promise<void> {
    const prospectType = this.route.snapshot.paramMap.get('prospectType');
    this.prospectType = prospectType === 'customer' ? 'customer' : 'supplier';
    this.documentType = this.prospectType === 'supplier' ? 'commercial_register' : 'vat_certificate';
    await this.loadPrivacyNotice();

    const leadCode = this.route.snapshot.queryParamMap.get('leadCode');
    if (!leadCode) {
      return;
    }

    this.leadCode = leadCode;
    try {
      const lead = await this.api.get(`/api/v1/public/onboarding/leads/${encodeURIComponent(leadCode)}`, false) as {
        companyName?: string | null;
        contactName?: string | null;
        email?: string | null;
        mobileNumber?: string | null;
      };
      this.companyName = lead.companyName ?? '';
      this.contactName = lead.contactName ?? '';
      this.email = lead.email ?? '';
      this.mobileNumber = lead.mobileNumber ?? '';
    } catch {
      this.errorText = 'The lead reference could not be loaded. You can still complete onboarding manually.';
    }
  }

  protected get pageTitle(): string {
    return this.prospectType === 'supplier'
      ? 'Become a Supplier'
      : 'Become a Customer';
  }

  protected get pageSummary(): string {
    return this.prospectType === 'supplier'
      ? 'Complete only the onboarding package. Operational and transactional features stay locked until Operations approves and activates your account.'
      : 'Complete only the onboarding package. Operational and transactional features stay locked until Operations approves and activates your account.';
  }

  protected get supplierDocumentOptionValue(): string {
    return this.prospectType === 'supplier' ? 'commercial_register' : 'vat_certificate';
  }

  protected get supplierDocumentOptionLabel(): string {
    return this.prospectType === 'supplier' ? 'Commercial register' : 'VAT certificate';
  }

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

  protected get isPrivacyAcceptanceRequired(): boolean {
    return this.privacyNotice?.requiresExplicitAcceptance === true && !this.privacyAccepted;
  }

  protected onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement | null;
    this.selectedFile = input?.files?.[0] ?? null;
    this.uploadMessage = '';
    this.uploadError = '';
  }

  protected async uploadDocument(): Promise<void> {
    if (!this.selectedFile) {
      this.uploadError = 'Choose a PDF, JPG, or PNG file first.';
      return;
    }

    this.uploadingDocument = true;
    this.uploadMessage = '';
    this.uploadError = '';

    try {
      const formData = new FormData();
      formData.set('subjectTypeCode', this.prospectType.toUpperCase());
      formData.set('documentType', this.documentType);
      formData.set('file', this.selectedFile);

      const upload = await this.api.postForm('/api/v1/public/onboarding/compliance-documents/upload', formData, false) as UploadedComplianceDocument;
      this.uploadedDocuments = [...this.uploadedDocuments, upload];
      this.uploadMessage = `${upload.fileName} uploaded for onboarding review.`;
      this.selectedFile = null;
    } catch (error) {
      this.uploadError = error instanceof Error ? error.message : 'Unable to upload the onboarding document.';
    } finally {
      this.uploadingDocument = false;
    }
  }

  protected async submit(): Promise<void> {
    if (this.isPrivacyAcceptanceRequired) {
      this.errorText = 'Accept the privacy notice before submitting onboarding.';
      return;
    }

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

    try {
      if (this.prospectType === 'supplier') {
        await this.api.post('/api/v1/public/onboarding/suppliers', {
          leadCode: this.leadCode || null,
          partyName: this.companyName,
          countryCode: this.countryCode,
          firmNationalId: this.firmNationalId || null,
          taxRegistrationNumber: this.taxRegistrationNumber || null,
          taxBranchCode: this.taxBranchCode || null,
          email: this.email || null,
          mobileNumber: this.mobileNumber || null,
          addressLine1: this.addressLine1 || null,
          supplierCategoryCode: this.supplierCategoryCode,
          defaultCurrencyCode: this.defaultCurrencyCode,
          preferredPaymentMethodCode: this.preferredPaymentMethodCode,
          paymentTermsDays: Number(this.paymentTermsDays ?? 0),
          leadTimeDays: Number(this.supplierLeadTimeDays ?? 0),
          minimumOrderAmount: this.minimumOrderAmount,
          bankName: this.bankName,
          bankAccountNumber: this.bankAccountNumber,
          bankSwiftCode: this.bankSwiftCode || null,
          notes: this.notes || null,
          privacyNoticeCode: this.privacyNotice?.noticeCode ?? null,
          privacyNoticeVersion: this.privacyNotice?.version ?? null,
          privacyAccepted: this.privacyAccepted,
          complianceDocuments: this.uploadedDocuments.map((document) => ({
            documentType: document.documentType,
            fileName: document.fileName,
            storageReference: document.storageReference,
            contentType: document.contentType,
            fileSizeBytes: document.fileSizeBytes
          }))
        }, false);
      } else {
        await this.api.post('/api/v1/public/onboarding/customers', {
          leadCode: this.leadCode || null,
          partyName: this.companyName,
          countryCode: this.countryCode,
          firmNationalId: this.firmNationalId || null,
          taxRegistrationNumber: this.taxRegistrationNumber || null,
          taxBranchCode: this.taxBranchCode || null,
          email: this.email || null,
          mobileNumber: this.mobileNumber || null,
          addressLine1: this.addressLine1 || null,
          creditLimitAmount: this.creditLimitAmount,
          creditTermsDays: this.creditTermsDays,
          isCreditHoldEnabled: false,
          creditHoldReason: null,
          customerClassificationCode: this.resolveCustomerClassificationCode(),
          customerSegmentCode: this.customerSegmentCode,
          defaultCurrencyCode: this.defaultCurrencyCode,
          salesChannelCode: this.salesChannelCode,
          priceTierCode: this.priceTierCode,
          invoiceDeliveryMethodCode: this.invoiceDeliveryMethodCode,
          notes: this.notes || null,
          privacyNoticeCode: this.privacyNotice?.noticeCode ?? null,
          privacyNoticeVersion: this.privacyNotice?.version ?? null,
          privacyAccepted: this.privacyAccepted,
          complianceDocuments: this.uploadedDocuments.map((document) => ({
            documentType: document.documentType,
            fileName: document.fileName,
            storageReference: document.storageReference,
            contentType: document.contentType,
            fileSizeBytes: document.fileSizeBytes
          }))
        }, false);
      }

      this.messageText = 'Your onboarding package was submitted for Operations review. Business features remain locked until activation is completed.';
    } catch (error) {
      this.errorText = error instanceof Error ? error.message : 'Unable to submit the onboarding package.';
    } finally {
      this.submitting = false;
    }
  }

  protected async backToLogin(): Promise<void> {
    await this.router.navigate(['/login']);
  }

  private resolveCustomerClassificationCode(): string {
    const candidate = this.customerClassificationCode.trim().toUpperCase();
    return ['GOVERNMENT', 'COMPANY', 'INSTITUTIONAL'].includes(candidate)
      ? candidate
      : 'COMPANY';
  }

  private async loadPrivacyNotice(): Promise<void> {
    try {
      const governance = await this.api.get(
        `/api/v1/public/privacy/governance?subjectTypeCode=${this.prospectType.toUpperCase()}`,
        false
      ) as PrivacyGovernanceResponse;
      this.privacyNotice = governance.notices[0] ?? null;
    } catch {
      this.privacyNotice = null;
    }
  }
}
