import { Component, OnInit, inject } from '@angular/core'
import { CommonModule } from '@angular/common'
import { FormsModule } from '@angular/forms'
import { Notifier } from '@app/core'
import { EventRegistrationService } from '../event-details/+register-event/register-event.service'
import { ActionDropdownComponent, DropdownAction } from '@app/shared/shared-main/buttons/action-dropdown.component'
import { ButtonComponent } from '@app/shared/shared-main/buttons/button.component'

interface EventRegistrationDisplay {
  id: number
  eventId: number
  eventName: string
  eventStartTime?: string
  eventEndTime?: string
  firstName: string
  lastName: string
  email: string
  phone: string
  companyName: string
  jobTitle: string
  country: string
  createdAt: string
  eventThumbnail?: string
}

@Component({
  selector: 'app-event-registrations',
  templateUrl: './event-userList.component.html',
  styleUrls: ['./event-userList.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ActionDropdownComponent,
    ButtonComponent
  ]
})
export class EventUsersListComponent implements OnInit {
  private registrationApi = inject(EventRegistrationService)
  private notifier = inject(Notifier)

  registrations: EventRegistrationDisplay[] = []
  loading = false
  searchQuery = ''

  ngOnInit () {
    this.loadRegistrations()
  }

  deleteActions: DropdownAction<EventRegistrationDisplay>[] = [
    {
      label: 'Delete',
      iconName: 'delete',
      handler: user => this.deleteRegistration(user)
    }
  ]

  loadRegistrations () {
    this.loading = true

    this.registrationApi.getAllRegistrations()
      .subscribe({
        next: (response: any) => {
          this.registrations = (response.data || []).map((item: any) => {
            return {
              id: item.id,
              eventId: item.event?.id,
              eventName: item.event?.title || 'N/A',
              eventStartTime: item.event?.startTime,
              eventEndTime: item.event?.endTime,
              firstName: item.firstName,
              lastName: item.lastName,
              email: item.email,
              phone: item.phone,
              companyName: item.companyName,
              jobTitle: item.jobTitle,
              country: item.country,
              createdAt: item.createdAt,
              eventThumbnail: item.event?.thumbnailFilename
                ? '/lazy-static/event-thumbnails/' + item.event.thumbnailFilename
                : ''
            }
          })

          this.loading = false
        },
        error: err => {
          console.error('Error loading registrations:', err)
          this.notifier.error('Failed to load registrations')
          this.loading = false
        }
      })
  }

  deleteRegistration(user: EventRegistrationDisplay) {
    if (!confirm(`Delete ${user.firstName} ${user.lastName}?`)) return

    this.registrationApi
      .deleteRegistration(user.eventId, user.id)
      .subscribe({
        next: () => {
          this.notifier.success('Deleted successfully')

          // remove from UI
          this.registrations = this.registrations.filter(r => r.id !== user.id)
        },
        error: err => {
          console.error(err)
          this.notifier.error('Delete failed')
        }
      })
  }

  get filteredUsers () {
    const query = this.searchQuery.trim().toLowerCase()

    if (!query) return this.registrations

    return this.registrations.filter(user =>
      user.eventName.toLowerCase().includes(query) ||
      user.firstName.toLowerCase().includes(query) ||
      user.lastName.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query) ||
      user.phone.toLowerCase().includes(query) ||
      user.companyName.toLowerCase().includes(query) ||
      user.jobTitle.toLowerCase().includes(query) ||
      user.country.toLowerCase().includes(query)
    )
  }

  exportRegistrations () {
    const rows = this.filteredUsers

    if (rows.length === 0) {
      this.notifier.error('No registrations to export')
      return
    }

    const workbook = this.buildExcelHtml(rows)
    const blob = new Blob([ '\ufeff', workbook ], { type: 'application/vnd.ms-excel;charset=utf-8;' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    const date = new Date().toISOString().slice(0, 10)

    link.href = url
    link.download = `event-registrations-${date}.xls`
    link.click()

    URL.revokeObjectURL(url)
  }

  private buildExcelHtml (rows: EventRegistrationDisplay[]) {
    const headers = [
      'Event ID',
      'Event Name',
      'Event Start Time',
      'Event End Time',
      'First Name',
      'Last Name',
      'Email',
      'Phone',
      'Company Name',
      'Job Title',
      'Country',
      'Registered At'
    ]

    const tableRows = rows.map(row => [
      row.eventId,
      row.eventName,
      this.formatDate(row.eventStartTime),
      this.formatDate(row.eventEndTime),
      row.firstName,
      row.lastName,
      row.email,
      row.phone,
      row.companyName,
      row.jobTitle,
      row.country,
      this.formatDate(row.createdAt)
    ])

    const headerHtml = headers.map(header => `<th>${this.escapeHtml(header)}</th>`).join('')
    const bodyHtml = tableRows.map(cells => {
      return `<tr>${cells.map(cell => `<td>${this.escapeHtml(cell)}</td>`).join('')}</tr>`
    }).join('')

    return `<!DOCTYPE html>
<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
  <head>
    <meta charset="UTF-8">
    <meta name="ProgId" content="Excel.Sheet">
    <meta name="Generator" content="PeerTube">
  </head>
  <body>
    <table>
      <thead>
        <tr>${headerHtml}</tr>
      </thead>
      <tbody>
        ${bodyHtml}
      </tbody>
    </table>
  </body>
</html>`
  }

  private formatDate (value?: string) {
    if (!value) return ''

    return new Date(value).toLocaleString()
  }

  private escapeHtml (value: unknown) {
    return String(value ?? '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
  }
}
