import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HeaderComponent } from '../header/header.component';
import { AuthService } from '../auth.service';
import { LanguageService } from '../language.service';
import { TranslationService } from '../translation.service';

@Component({
  selector: 'app-user-profile',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, HeaderComponent],
  templateUrl: './user-profile.component.html',
  styleUrl: './user-profile.component.css'
})
export class UserProfileComponent implements OnInit {
  profileForm!: FormGroup;
  userNameInitial: string = '';
  userId: number | null = null;
  successMessage: string = '';
  errorMessage: string = '';
  loading: boolean = false;
  userDetail: any = null;
  uploadingProfile = false;
  uploadingCover = false;
  storyImgPath = 'https://infoways.in/funtelapi/';
  selectedLanguage: string = 'en';

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private authService: AuthService,
    public translationService: TranslationService,
    private languageService: LanguageService 
  ) {}

  @ViewChild('profileInput') profileInput!: ElementRef<HTMLInputElement>;
  @ViewChild('coverInput') coverInput!: ElementRef<HTMLInputElement>;

  ngOnInit(): void {
    this.selectedLanguage = this.languageService.getCurrentLanguage();
    
    this.languageService.currentLanguage$.subscribe(lang => {
      this.selectedLanguage = lang;
    });
    
    this.authService.initializeAuthState();
    this.userId = this.authService.getCurrentUserId();
    
    if (!this.userId) {
      this.errorMessage = 'Unable to determine user ID.';
      return;
    }

    // Initialize form
    this.initializeForm();
    this.loadUserData();
  }

  private initializeForm(): void {
    this.profileForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      email: ['', [Validators.required, Validators.email]],
      mobile: [{value: '', disabled: true}], // Mobile is readonly
      about: ['', [Validators.maxLength(500)]],
      language: ['English']
    });
  }

  loadUserData(): void {
    this.loading = true;
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });

    // Load user data from signup.php API
    this.http.get<any>(`https://infoways.in/funtelapi/signup.php?get_user=true&id=${this.userId}`, 
      { headers: headers, withCredentials: true })
      .subscribe({
        next: (res) => {
          this.loading = false;
          if (res?.status === 'success' && res?.data) {
            this.updateFormWithUserData(res.data);
            this.loadAuthorData(); // Load additional user details
          } else {
            this.errorMessage = res?.message || 'Invalid response from server';
            setTimeout(() => this.errorMessage = '', 5000);
          }
        },
        error: (err) => {
          this.loading = false;
          console.error('Error fetching profile data:', err);
          this.errorMessage = 'Could not load user information';
          setTimeout(() => this.errorMessage = '', 5000);
        }
      });
  }

  loadAuthorData(): void {
    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });
    
    this.http.get<any>('https://infoways.in/funtelapi/userinfo.php', 
      { headers: headers, withCredentials: true })
      .subscribe({
        next: (res) => {
          if (res.status === 'success') {
            this.userDetail = res.data;
            console.log('User detail loaded:', this.userDetail);
            
            // Update profile image URLs
            if (this.userDetail.profileimg) {
              this.userDetail.profileimg_url = `${this.storyImgPath}/${this.userDetail.profileimg}`;
            }
            if (this.userDetail.coverimage) {
              this.userDetail.coverimage_url = `${this.storyImgPath}/${this.userDetail.coverimage}`;
            }
          }
        },
        error: (err) => {
          console.error('Failed to fetch user info:', err);
        }
      });
  }

  private updateFormWithUserData(userData: any): void {
    console.log('Updating form with data:', userData);
    
    this.profileForm.patchValue({
      name: userData.name || '',
      email: userData.email || '',
      mobile: userData.mobile || '',
      about: userData.about || '',
      language: userData.language || 'English'
    });

    this.userNameInitial = userData.name ? userData.name.charAt(0).toUpperCase() : 'U';
    
    // Set userDetail for profile image
    this.userDetail = {
      ...userData,
      profileimg_url: userData.profileimg ? `${this.storyImgPath}/${userData.profileimg}` : null,
      coverimage_url: userData.coverimage ? `${this.storyImgPath}/${userData.coverimage}` : null
    };
  }

  t(key: string): string {
    return this.translationService.translate(key);
  }

  onSubmit() {
    if (!this.userId || this.profileForm.invalid) {
      console.log('Form invalid or user ID missing');
      this.errorMessage = 'Please fill all required fields correctly';
      setTimeout(() => this.errorMessage = '', 3000);
      return;
    }

    this.loading = true;
    this.errorMessage = '';
    this.successMessage = '';

    const payload = {
      update_profile: true,
      user_id: this.userId,
      name: this.profileForm.value.name,
      email: this.profileForm.value.email,
      about: this.profileForm.value.about,
      language: this.profileForm.value.language
      // Mobile excluded as it's readonly
    };

    const headers = new HttpHeaders({
      'content-type': 'application/json',
    });

    console.log('Submitting payload:', payload);

    this.http.post<any>('https://infoways.in/funtelapi/signup.php', payload, { 
      headers: headers,
      withCredentials: true 
    }).subscribe({
      next: (res) => {
        this.loading = false;
        console.log('Update response:', res);
        
        if (res.status === 'success') {
          this.successMessage = this.t('PROFILE_UPDATED_SUCCESSFULLY');
          window.scrollTo({ top: 0, behavior: 'smooth' });
          
          if (res.logout) {
            setTimeout(() => {
              this.authService.logout();
            }, 1500);
          } else {
            setTimeout(() => this.successMessage = '', 3000);
          }
        } else {
          this.errorMessage = res.message || this.t('UPDATE_FAILED');
          setTimeout(() => this.errorMessage = '', 5000);
        }
      },
      error: (err) => {
        this.loading = false;
        console.error('Update error:', err);
        this.errorMessage = this.t('SOMETHING_WENT_WRONG');
        setTimeout(() => this.errorMessage = '', 5000);
      }
    });
  }

  triggerProfileUpload() {
    this.profileInput?.nativeElement.click();
  }

  triggerCoverUpload() {
    this.coverInput?.nativeElement.click();
  }

  onProfileSelected(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) this.uploadImage(file, 'profileimg');
  }

  onCoverSelected(e: Event) {
    const file = (e.target as HTMLInputElement).files?.[0];
    if (file) this.uploadImage(file, 'coverimage');
  }

  private uploadImage(file: File, type: 'profileimg' | 'coverimage') {
    if (!this.userId) return;

    const fd = new FormData();
    if (type === 'profileimg') {
      this.uploadingProfile = true;
      fd.append('upload_profileimg', '1');
    } else {
      this.uploadingCover = true;
      fd.append('upload_coverimage', '1');
    }

    fd.append('user_id', String(this.userId));
    fd.append('file', file);

    this.http.post<any>(`${this.storyImgPath}/signup.php`, fd, { withCredentials: true })
      .subscribe({
        next: (res) => {
          if (type === 'profileimg') this.uploadingProfile = false;
          if (type === 'coverimage') this.uploadingCover = false;

          if (res.status === 'success') {
            if (!this.userDetail) this.userDetail = {};
            
            if (type === 'profileimg') {
              this.userDetail.profileimg = res.path || res.filename;
              this.userDetail.profileimg_url = res.url || `${this.storyImgPath}/${this.userDetail.profileimg}`;
            } else {
              this.userDetail.coverimage = res.path || res.filename;
              this.userDetail.coverimage_url = res.url || `${this.storyImgPath}/${this.userDetail.coverimage}`;
            }
            
            this.successMessage = `${type === 'profileimg' ? 'Profile' : 'Cover'} image updated successfully`;
            setTimeout(() => this.successMessage = '', 3000);
          } else {
            this.errorMessage = res.message || 'Image upload failed';
            setTimeout(() => this.errorMessage = '', 5000);
          }
        },
        error: (err) => {
          if (type === 'profileimg') this.uploadingProfile = false;
          if (type === 'coverimage') this.uploadingCover = false;
          
          this.errorMessage = 'Image upload error';
          setTimeout(() => this.errorMessage = '', 5000);
          console.error('Upload error:', err);
        }
      });
  }
}