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 { MatCardModule } from '@angular/material/card';
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 { MatDividerModule } from '@angular/material/divider';
import { AuthService } from '../../../core/services/auth.service';

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

@Component({
  selector: 'app-email-login',
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    RouterModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatSnackBarModule,
    MatDividerModule,
  ],
  template: `
    <div class="email-login-container">
      <mat-card class="login-card">
        <mat-card-header>
          <mat-card-title>
            <mat-icon class="logo-icon">verified_user</mat-icon>
            <h2>Goa GEL Platform</h2>
          </mat-card-title>
          <p class="subtitle">Government e-License Platform</p>
        </mat-card-header>

        <mat-card-content>
          <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Email</mat-label>
              <input matInput type="email" formControlName="email" placeholder="Enter your email" />
              <mat-icon matPrefix>email</mat-icon>
              <mat-error *ngIf="loginForm.get('email')?.hasError('required')">
                Email is required
              </mat-error>
              <mat-error *ngIf="loginForm.get('email')?.hasError('email')">
                Please enter a valid email
              </mat-error>
            </mat-form-field>

            <mat-form-field appearance="outline" class="full-width">
              <mat-label>Password</mat-label>
              <input
                matInput
                [type]="hidePassword ? 'password' : 'text'"
                formControlName="password"
                placeholder="Enter your password"
              />
              <mat-icon matPrefix>lock</mat-icon>
              <button
                mat-icon-button
                matSuffix
                type="button"
                (click)="hidePassword = !hidePassword"
              >
                <mat-icon>{{ hidePassword ? 'visibility_off' : 'visibility' }}</mat-icon>
              </button>
              <mat-error *ngIf="loginForm.get('password')?.hasError('required')">
                Password is required
              </mat-error>
            </mat-form-field>

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

          <mat-divider class="divider"></mat-divider>

          <div class="demo-accounts">
            <h3 class="demo-title">
              <mat-icon>info</mat-icon>
              Demo Accounts
            </h3>
            <p class="demo-subtitle">Click any account to auto-fill credentials</p>

            <div class="demo-grid">
              <div
                *ngFor="let account of demoAccounts"
                class="demo-card"
                (click)="fillDemoCredentials(account)"
                [class.selected]="selectedDemo === account.email"
              >
                <mat-icon [style.color]="getRoleColor(account.role)">{{ account.icon }}</mat-icon>
                <div class="demo-info">
                  <strong>{{ account.role }}</strong>
                  <span class="demo-email">{{ account.email }}</span>
                  <span class="demo-description">{{ account.description }}</span>
                </div>
              </div>
            </div>

            <div class="credentials-note">
              <mat-icon>security</mat-icon>
              <span>All demo accounts use the same password format: <code>Role@123</code></span>
            </div>
          </div>
        </mat-card-content>
      </mat-card>
    </div>
  `,
  styles: [
    `
      .email-login-container {
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        padding: 20px;
      }

      .login-card {
        width: 100%;
        max-width: 600px;
      }

      mat-card-header {
        display: block;
        text-align: center;
        margin-bottom: 24px;

        mat-card-title {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 8px;
        }

        .logo-icon {
          font-size: 48px;
          width: 48px;
          height: 48px;
          color: #1976d2;
        }

        h2 {
          margin: 0;
          font-size: 1.75rem;
          font-weight: 500;
          color: #1976d2;
        }
      }

      .subtitle {
        text-align: center;
        color: rgba(0, 0, 0, 0.54);
        margin: 8px 0 0;
        font-size: 0.875rem;
      }

      .full-width {
        width: 100%;
        margin-bottom: 16px;
      }

      .login-button {
        height: 48px;
        font-size: 16px;
        margin-top: 8px;

        mat-spinner {
          display: inline-block;
          margin-right: 8px;
        }
      }

      .divider {
        margin: 32px 0 24px;
      }

      .demo-accounts {
        margin-top: 24px;
      }

      .demo-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 8px;
        font-size: 1.125rem;
        font-weight: 500;
        color: #1976d2;

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

      .demo-subtitle {
        color: rgba(0, 0, 0, 0.54);
        font-size: 0.875rem;
        margin: 0 0 16px;
      }

      .demo-grid {
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .demo-card {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          border-color: #1976d2;
          background-color: #f5f5f5;
        }

        &.selected {
          border-color: #1976d2;
          background-color: #e3f2fd;
        }

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

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

        strong {
          font-size: 0.875rem;
          color: #333;
        }

        .demo-email {
          font-size: 0.75rem;
          color: #666;
          font-family: monospace;
        }

        .demo-description {
          font-size: 0.75rem;
          color: rgba(0, 0, 0, 0.54);
        }
      }

      .credentials-note {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-top: 16px;
        padding: 12px;
        background-color: #fff3e0;
        border-radius: 8px;
        font-size: 0.875rem;
        color: #e65100;

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

        code {
          background-color: rgba(0, 0, 0, 0.1);
          padding: 2px 6px;
          border-radius: 4px;
          font-family: monospace;
        }
      }
    `,
  ],
})
export class EmailLoginComponent {
  loginForm: FormGroup;
  loading = false;
  hidePassword = true;
  selectedDemo: string | null = null;

  demoAccounts: DemoAccount[] = [
    {
      role: 'Admin',
      email: 'admin@goa.gov.in',
      password: 'Admin@123',
      description: 'System administrator with full access',
      icon: 'admin_panel_settings',
    },
    {
      role: 'Fire Department',
      email: 'fire@goa.gov.in',
      password: 'Fire@123',
      description: 'Fire safety inspection officer',
      icon: 'local_fire_department',
    },
    {
      role: 'Tourism',
      email: 'tourism@goa.gov.in',
      password: 'Tourism@123',
      description: 'Tourism license reviewer',
      icon: 'luggage',
    },
    {
      role: 'Municipality',
      email: 'municipality@goa.gov.in',
      password: 'Municipality@123',
      description: 'Municipal building permit officer',
      icon: 'location_city',
    },
    {
      role: 'Citizen',
      email: 'citizen@example.com',
      password: 'Citizen@123',
      description: 'Citizen applying for licenses',
      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]],
      password: ['', [Validators.required]],
    });
  }

  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: '#d32f2f',
      'Fire Department': '#f57c00',
      Tourism: '#1976d2',
      Municipality: '#388e3c',
      Citizen: '#7b1fa2',
    };
    return colors[role] || '#666';
  }

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

    this.loading = true;
    const { email, password } = this.loginForm.value;

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

      // Navigate based on user role
      const user = this.authService.currentUser();
      if (user?.role === 'ADMIN' || user?.type === 'ADMIN') {
        this.router.navigate(['/admin']);
      } else if (user?.role === 'DEPARTMENT' || user?.type === 'DEPARTMENT') {
        this.router.navigate(['/dashboard']);
      } else {
        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;
    }
  }
}
