import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { AuthService } from '../../../core/services/auth.service';
import { InputSanitizer } from '../../../core/utils/input-sanitizer';

interface DemoAccount {
  role: string;
  email: string;
  password: string;
  description: string;
  icon: string;
}

@Component({
  selector: 'app-email-login',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    RouterModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatSnackBarModule,
  ],
  template: `
    <div class="login-form">
      <!-- Header -->
      <div class="form-header">
        <div class="header-glow"></div>
        <h1 class="form-title">Sign In</h1>
        <p class="form-subtitle">Enter your credentials to continue</p>
      </div>

      <!-- Login Form -->
      <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
        <div class="form-field">
          <label class="field-label">Email</label>
          <div class="input-wrapper">
            <mat-icon class="input-icon">email</mat-icon>
            <input
              type="email"
              formControlName="email"
              placeholder="Enter your email"
              class="form-input"
            />
          </div>
          <span class="field-error" *ngIf="loginForm.get('email')?.touched && loginForm.get('email')?.hasError('required')">
            Email is required
          </span>
          <span class="field-error" *ngIf="loginForm.get('email')?.touched && loginForm.get('email')?.hasError('email')">
            Please enter a valid email
          </span>
        </div>

        <div class="form-field">
          <label class="field-label">Password</label>
          <div class="input-wrapper">
            <mat-icon class="input-icon">lock</mat-icon>
            <input
              [type]="hidePassword ? 'password' : 'text'"
              formControlName="password"
              placeholder="Enter your password"
              class="form-input"
            />
            <button type="button" class="toggle-password" (click)="hidePassword = !hidePassword">
              <mat-icon>{{ hidePassword ? 'visibility_off' : 'visibility' }}</mat-icon>
            </button>
          </div>
          <span class="field-error" *ngIf="loginForm.get('password')?.touched && loginForm.get('password')?.hasError('required')">
            Password is required
          </span>
        </div>

        <button type="submit" class="submit-btn" [disabled]="loginForm.invalid || loading">
          <mat-spinner *ngIf="loading" diameter="20"></mat-spinner>
          <span *ngIf="!loading">Sign In</span>
        </button>
      </form>

      <!-- Demo Credentials Toggle -->
      <button class="demo-toggle" (click)="showDemo = !showDemo">
        <mat-icon>{{ showDemo ? 'expand_less' : 'science' }}</mat-icon>
        <span>{{ showDemo ? 'Hide Demo Accounts' : 'View Demo Accounts' }}</span>
      </button>

      <!-- Collapsible Demo Panel -->
      <div class="demo-panel" [class.expanded]="showDemo">
        <div class="demo-panel-content">
          <div
            *ngFor="let account of demoAccounts"
            class="demo-account"
            (click)="fillDemoCredentials(account)"
            [class.selected]="selectedDemo === account.email"
          >
            <mat-icon [style.color]="getRoleColor(account.role)">{{ account.icon }}</mat-icon>
            <div class="account-info">
              <span class="account-role">{{ account.role }}</span>
              <span class="account-email">{{ account.email }}</span>
            </div>
          </div>
          <div class="password-hint">
            <mat-icon>vpn_key</mat-icon>
            <span>Password: <code>Role&#64;123</code></span>
          </div>
        </div>
      </div>

      <!-- Back Link -->
      <a [routerLink]="['/auth']" class="back-link">
        <mat-icon>arrow_back</mat-icon>
        <span>Other login options</span>
      </a>
    </div>
  `,
  styles: [
    `
      // =============================================================================
      // EMAIL LOGIN - Dark Glass-Morphism Theme
      // =============================================================================

      .login-form {
        position: relative;
      }

      // =============================================================================
      // HEADER
      // =============================================================================
      .form-header {
        text-align: center;
        margin-bottom: 32px;
        position: relative;
      }

      .header-glow {
        position: absolute;
        top: -40px;
        left: 50%;
        transform: translateX(-50%);
        width: 200px;
        height: 100px;
        background: radial-gradient(ellipse, rgba(99, 102, 241, 0.2) 0%, transparent 70%);
        pointer-events: none;
      }

      .form-title {
        font-size: 28px;
        font-weight: 700;
        background: linear-gradient(135deg, #FFFFFF 0%, #c7d2fe 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin: 0 0 8px;
      }

      .form-subtitle {
        font-size: 14px;
        color: rgba(255, 255, 255, 0.5);
        margin: 0;
      }

      // =============================================================================
      // FORM FIELDS
      // =============================================================================
      .form-field {
        margin-bottom: 20px;
      }

      .field-label {
        display: block;
        font-size: 13px;
        font-weight: 500;
        color: rgba(255, 255, 255, 0.7);
        margin-bottom: 8px;
      }

      .input-wrapper {
        position: relative;
        display: flex;
        align-items: center;
      }

      .input-icon {
        position: absolute;
        left: 14px;
        color: rgba(255, 255, 255, 0.4);
        font-size: 20px;
        width: 20px;
        height: 20px;
        pointer-events: none;
      }

      .form-input {
        width: 100%;
        padding: 14px 14px 14px 46px;
        background: rgba(255, 255, 255, 0.05);
        border: 1px solid rgba(255, 255, 255, 0.1);
        border-radius: 12px;
        font-size: 15px;
        color: rgba(255, 255, 255, 0.95);
        transition: all 0.2s ease;
        outline: none;

        &::placeholder {
          color: rgba(255, 255, 255, 0.35);
        }

        &:focus {
          background: rgba(255, 255, 255, 0.08);
          border-color: rgba(99, 102, 241, 0.5);
          box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
        }

        &:hover:not(:focus) {
          border-color: rgba(255, 255, 255, 0.2);
        }
      }

      .toggle-password {
        position: absolute;
        right: 8px;
        background: transparent;
        border: none;
        cursor: pointer;
        padding: 8px;
        color: rgba(255, 255, 255, 0.4);
        transition: color 0.2s ease;

        mat-icon {
          font-size: 20px;
          width: 20px;
          height: 20px;
        }

        &:hover {
          color: rgba(255, 255, 255, 0.7);
        }
      }

      .field-error {
        display: block;
        font-size: 12px;
        color: #f87171;
        margin-top: 6px;
        padding-left: 4px;
      }

      // =============================================================================
      // SUBMIT BUTTON
      // =============================================================================
      .submit-btn {
        width: 100%;
        padding: 14px;
        background: linear-gradient(135deg, #6366F1 0%, #818cf8 100%);
        border: none;
        border-radius: 12px;
        font-size: 15px;
        font-weight: 600;
        color: white;
        cursor: pointer;
        transition: all 0.25s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 24px;

        &:hover:not(:disabled) {
          background: linear-gradient(135deg, #4F46E5 0%, #6366F1 100%);
          transform: translateY(-1px);
          box-shadow: 0 8px 20px rgba(99, 102, 241, 0.3);
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        mat-spinner {
          ::ng-deep circle {
            stroke: white;
          }
        }
      }

      // =============================================================================
      // DEMO TOGGLE & PANEL
      // =============================================================================
      .demo-toggle {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        width: 100%;
        padding: 12px;
        background: transparent;
        border: 1px dashed rgba(255, 255, 255, 0.15);
        border-radius: 12px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 500;
        color: rgba(255, 255, 255, 0.5);
        transition: all 0.2s ease;

        mat-icon {
          font-size: 18px;
          width: 18px;
          height: 18px;
        }

        &:hover {
          background: rgba(255, 255, 255, 0.03);
          border-color: rgba(99, 102, 241, 0.3);
          color: rgba(255, 255, 255, 0.7);
        }
      }

      .demo-panel {
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.35s cubic-bezier(0.4, 0, 0.2, 1);

        &.expanded {
          max-height: 350px;
        }
      }

      .demo-panel-content {
        padding-top: 16px;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .demo-account {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 14px;
        background: rgba(255, 255, 255, 0.03);
        border: 1px solid rgba(255, 255, 255, 0.08);
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s ease;

        mat-icon {
          font-size: 24px;
          width: 24px;
          height: 24px;
        }

        &:hover {
          background: rgba(255, 255, 255, 0.06);
          border-color: rgba(99, 102, 241, 0.3);
        }

        &.selected {
          background: rgba(99, 102, 241, 0.15);
          border-color: rgba(99, 102, 241, 0.4);
        }
      }

      .account-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 2px;
      }

      .account-role {
        font-size: 14px;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.9);
      }

      .account-email {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.5);
        font-family: 'SF Mono', monospace;
      }

      .password-hint {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 14px;
        background: rgba(16, 185, 129, 0.1);
        border: 1px solid rgba(16, 185, 129, 0.2);
        border-radius: 10px;
        margin-top: 4px;

        mat-icon {
          font-size: 16px;
          width: 16px;
          height: 16px;
          color: #34d399;
        }

        span {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.7);
        }

        code {
          background: rgba(0, 0, 0, 0.3);
          padding: 2px 6px;
          border-radius: 4px;
          font-family: 'SF Mono', monospace;
          color: #34d399;
        }
      }

      // =============================================================================
      // BACK LINK
      // =============================================================================
      .back-link {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        margin-top: 24px;
        color: rgba(255, 255, 255, 0.4);
        text-decoration: none;
        font-size: 13px;
        transition: color 0.2s ease;

        mat-icon {
          font-size: 18px;
          width: 18px;
          height: 18px;
        }

        &:hover {
          color: #818cf8;
        }
      }
    `,
  ],
})
export class EmailLoginComponent {
  loginForm: FormGroup;
  loading = false;
  hidePassword = true;
  showDemo = false;
  selectedDemo: string | null = null;

  demoAccounts: DemoAccount[] = [
    {
      role: 'Admin',
      email: 'admin@goa.gov.in',
      password: 'Admin@123',
      description: 'System administrator',
      icon: 'admin_panel_settings',
    },
    {
      role: 'Fire Dept',
      email: 'fire@goa.gov.in',
      password: 'Fire@123',
      description: 'Fire safety officer',
      icon: 'local_fire_department',
    },
    {
      role: 'Tourism',
      email: 'tourism@goa.gov.in',
      password: 'Tourism@123',
      description: 'Tourism reviewer',
      icon: 'luggage',
    },
    {
      role: 'Citizen',
      email: 'rajesh.naik@example.com',
      password: 'Citizen@123',
      description: 'Citizen applicant',
      icon: 'person',
    },
  ];

  constructor(
    private fb: FormBuilder,
    private authService: AuthService,
    private router: Router,
    private snackBar: MatSnackBar
  ) {
    this.loginForm = this.fb.group({
      email: ['', [Validators.required, Validators.email, Validators.maxLength(254)]],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(128)]],
    });
  }

  fillDemoCredentials(account: DemoAccount): void {
    this.selectedDemo = account.email;
    this.loginForm.patchValue({
      email: account.email,
      password: account.password,
    });
  }

  getRoleColor(role: string): string {
    const colors: { [key: string]: string } = {
      Admin: '#f87171',
      'Fire Dept': '#fb923c',
      Tourism: '#60a5fa',
      Citizen: '#a78bfa',
    };
    return colors[role] || '#818cf8';
  }

  async onSubmit(): Promise<void> {
    if (this.loginForm.invalid) {
      return;
    }

    this.loading = true;
    const email = InputSanitizer.sanitizeEmail(this.loginForm.value.email || '');
    const password = this.loginForm.value.password || '';

    try {
      await this.authService.login(email, password);
      this.snackBar.open('Login successful!', 'Close', {
        duration: 3000,
        panelClass: ['success-snackbar'],
      });

      // All users go to dashboard after login
      this.router.navigate(['/dashboard']);
    } catch (error: any) {
      this.snackBar.open(
        error?.error?.message || 'Invalid email or password',
        'Close',
        {
          duration: 5000,
          panelClass: ['error-snackbar'],
        }
      );
    } finally {
      this.loading = false;
    }
  }
}
