// src/app/components/contact/contact.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { lastValueFrom } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { OverlayService } from '../services/overlay.service';


interface ErrorResponse {
  message: Array<{
    field: string;
    message: string;
  }>;
  error: string;
  statusCode: number;
}

@Component({
  selector: 'app-contact',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <section id="contact" class="py-20" data-aos="fade-up">
      <div class="container mx-auto px-6">
        <h2 class="text-3xl font-bold text-center">Get in Touch</h2>
        <p class="mt-4 text-center text-gray-600">We're here to help you with all your IT needs.</p>
        <div class="mt-12 max-w-lg mx-auto">
          <form (ngSubmit)="onSubmit()" class="bg-white p-8 rounded-lg shadow" data-aos="fade-up">
            <p class="text-sm text-gray-500 mb-4">Fields marked with <span class="text-red-600">*</span> are required</p>
            <div class="mb-4 relative">
              <label class="block text-gray-700 flex items-center">
                Name <span class="text-red-600 ml-1">*</span>
                <span *ngIf="errors.name" class="ml-2 text-red-600 cursor-pointer" 
                      [title]="errors.name" 
                      data-tooltip-target="tooltip-name">
                  &#8505;
                </span>
              </label>
              <input 
                type="text" 
                name="name"
                [(ngModel)]="formData.name"
                class="w-full mt-2 p-3 border rounded" 
                placeholder="Your Name" 
                required>
            </div>
            <div class="mb-4 relative">
              <label class="block text-gray-700 flex items-center">
                Email <span class="text-red-600 ml-1">*</span>
                <span *ngIf="errors.email" class="ml-2 text-red-600 cursor-pointer" 
                      [title]="errors.email" 
                      data-tooltip-target="tooltip-email">
                  &#8505;
                </span>
              </label>
              <input 
                type="email" 
                name="email"
                [(ngModel)]="formData.email"
                class="w-full mt-2 p-3 border rounded" 
                placeholder="Your Email" 
                required>
            </div>
            <div class="mb-4 relative">
              <label class="block text-gray-700 flex items-center">
                Phone <span class="text-gray-400 text-sm ml-1">(optional)</span>
                <span *ngIf="errors.phone" class="ml-2 text-red-600 cursor-pointer" 
                      [title]="errors.phone" 
                      data-tooltip-target="tooltip-phone">
                  &#8505;
                </span>
              </label>
              <input 
                type="tel" 
                name="phone"
                [(ngModel)]="formData.phone"
                class="w-full mt-2 p-3 border rounded" 
                placeholder="Your Phone Number">
            </div>
            <div class="mb-4 relative">
              <label class="block text-gray-700 flex items-center">
                Company <span class="text-gray-400 text-sm ml-1">(optional)</span>
                <span *ngIf="errors.company" class="ml-2 text-red-600 cursor-pointer" 
                      [title]="errors.company" 
                      data-tooltip-target="tooltip-company">
                  &#8505;
                </span>
              </label>
              <input 
                type="text" 
                name="company"
                [(ngModel)]="formData.company"
                class="w-full mt-2 p-3 border rounded" 
                placeholder="Your Company Name">
            </div>
            <div class="mb-4 relative">
              <label class="block text-gray-700 flex items-center">
                Message <span class="text-red-600 ml-1">*</span>
                <span *ngIf="errors.message" class="ml-2 text-red-600 cursor-pointer" 
                      [title]="errors.message" 
                      data-tooltip-target="tooltip-message">
                  &#8505;
                </span>
              </label>
              <textarea 
                name="message"
                [(ngModel)]="formData.message"
                class="w-full mt-2 p-3 border rounded" 
                rows="5" 
                placeholder="Your Message" 
                required></textarea>
            </div>
            <button 
              type="submit" 
              class="w-full bg-blue-600 text-white p-3 rounded hover:bg-blue-700">
              Send Message
            </button>
          </form>
        </div>
      </div>
    </section>
  `,
})
export class ContactComponent {
  private hostname = window.location.hostname;
  private apiBaseUrl = '';//`http://${this.hostname}:3000`;
  formData = {
    name: '',
    email: '',
    phone: '',
    company: '',
    message: '',
  };
  // Update the errors type to include the new fields
  errors: { name?: string, email?: string, phone?: string, company?: string, message?: string } = {};

  constructor(private http: HttpClient, private overlayService: OverlayService) {}

  async onSubmit() {
    this.errors = {}; // Reset errors
    this.overlayService.showLoading();
    try {
      await lastValueFrom(this.http.post(`${this.apiBaseUrl}/api`, this.formData));
      this.overlayService.showSuccess();
      this.formData = { name: '', email: '', phone: '', company: '', message: '' }; // Reset form
    } catch (error) {
      if (error instanceof HttpErrorResponse && error.status === 400) {
        const errorResponse = error.error as ErrorResponse;
        errorResponse.message.forEach((err) => {
          this.errors[err.field] = err.message;
        });
      } else {
        // General error handling
        console.error('An unexpected error occurred:', error);
      }
    } finally {
      this.overlayService.hideLoading();
    }
  }
}