import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router, RouterModule } from '@angular/router';
import { RegistrationService } from '../../../services/registration.service';

@Component({
  selector: 'app-patient-register',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterModule],
  templateUrl: './patient-register.component.html',
  styleUrl: './patient-register.component.scss'
})
export class PatientRegisterComponent {
  formData = {
    email: '',
    password: '',
    confirmPassword: '',
    firstName: '',
    lastName: '',
    phoneNumber: '',
    emergencyContactName: '',
    emergencyContactPhone: '',
    bloodType: '',
    allergies: ''
  };

  loading = false;
  error: string | null = null;
  success = false;
  showPassword = false;
  showConfirmPassword = false;
  passwordStrength = 0;
  passwordStrengthText = '';
  validationErrors: { [key: string]: string } = {};

  bloodTypes = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];

  constructor(
    private registrationService: RegistrationService,
    private router: Router
  ) {}

  checkPasswordStrength(password: string): { strength: number; text: string } {
    if (!password) {
      return { strength: 0, text: '' };
    }
    let strength = 0;
    if (password.length >= 8) strength++;
    if (password.length >= 12) strength++;
    if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;

    const texts = ['', 'Weak', 'Fair', 'Good', 'Strong', 'Very Strong'];
    return { strength, text: texts[strength] || '' };
  }

  onPasswordChange() {
    const result = this.checkPasswordStrength(this.formData.password);
    this.passwordStrength = result.strength;
    this.passwordStrengthText = result.text;
    this.validationErrors = {};
  }

  validateField(field: string, value: any): string {
    switch (field) {
      case 'email':
        if (!value) return 'Email is required';
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) return 'Please enter a valid email address';
        return '';
      case 'password':
        if (!value) return 'Password is required';
        if (value.length < 8) return 'Password must be at least 8 characters';
        if (value.length > 20) return 'Password must not exceed 20 characters';
        return '';
      case 'confirmPassword':
        if (!value) return 'Please confirm your password';
        if (value !== this.formData.password) return 'Passwords do not match';
        return '';
      case 'firstName':
      case 'lastName':
        if (!value) return 'This field is required';
        if (value.length < 2) return 'Must be at least 2 characters';
        if (value.length > 50) return 'Must not exceed 50 characters';
        return '';
      case 'phoneNumber':
        if (!value) return 'Phone number is required';
        const phoneRegex = /^\+?[1-9][0-9]\d{1,14}$/;
        if (!phoneRegex.test(value)) return 'Please enter a valid phone number';
        return '';
      case 'emergencyContactPhone':
        if (value && this.formData.emergencyContactName) {
          const phoneRegex = /^\+?[1-9][0-9]\d{1,14}$/;
          if (!phoneRegex.test(value)) return 'Please enter a valid phone number';
        }
        return '';
      default:
        return '';
    }
  }

  validateAll(): boolean {
    this.validationErrors = {};
    let isValid = true;

    const fields: (keyof typeof this.formData)[] = [
      'email', 'password', 'confirmPassword', 'firstName', 'lastName', 'phoneNumber'
    ];

    fields.forEach(field => {
      const error = this.validateField(field, this.formData[field]);
      if (error) {
        this.validationErrors[field] = error;
        isValid = false;
      }
    });

    // Validate emergency contact phone if emergency contact name is provided
    if (this.formData.emergencyContactName) {
      const error = this.validateField('emergencyContactPhone', this.formData.emergencyContactPhone);
      if (error) {
        this.validationErrors['emergencyContactPhone'] = error;
        isValid = false;
      }
    }

    return isValid;
  }

  async submit() {
    this.error = null;
    this.validationErrors = {};

    if (!this.validateAll()) {
      this.error = 'Please fix the errors in the form';
      return;
    }

    this.loading = true;
    try {
      const allergiesArray = this.formData.allergies
        ? this.formData.allergies.split(',').map(a => a.trim()).filter(a => a.length > 0)
        : undefined;

      await this.registrationService.registerPatient({
        user: {
          email: this.formData.email,
          password: {
            password: this.formData.password,
            confirmPassword: this.formData.confirmPassword
          },
          firstName: this.formData.firstName,
          lastName: this.formData.lastName,
          phoneNumber: this.formData.phoneNumber
        },
        emergencyContactName: this.formData.emergencyContactName || undefined,
        emergencyContactPhone: this.formData.emergencyContactPhone || undefined,
        bloodType: this.formData.bloodType || undefined,
        allergies: allergiesArray
      });

      this.success = true;
      setTimeout(() => {
        this.router.navigateByUrl('/login');
      }, 2000);
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.message || 'Registration failed. Please try again.';
    } finally {
      this.loading = false;
    }
  }

  togglePasswordVisibility() {
    this.showPassword = !this.showPassword;
  }

  toggleConfirmPasswordVisibility() {
    this.showConfirmPassword = !this.showConfirmPassword;
  }

  getFieldError(field: string): string {
    return this.validationErrors[field] || '';
  }

  hasFieldError(field: string): boolean {
    return !!this.validationErrors[field];
  }
}

