/**
 * @copyright 2026 NHCarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { Component, OnInit, inject, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { SuggestionService } from '../../services/suggestion.service';
import { AuthService } from '../../services/auth.service';
import { PaginationComponent } from '../shared/pagination.component';
import { GameFormComponent } from '../shared/game-form.component';
import { BookFormComponent } from '../shared/book-form.component';
import { MusicFormComponent } from '../shared/music-form.component';
import { ShowFormComponent } from '../shared/show-form.component';
import { MangaFormComponent } from '../shared/manga-form.component';
import { ArtFormComponent } from '../shared/art-form.component';
import { Suggestion, SuggestionStatus, SuggestionEntity, CreateGameDto, UpdateGameDto, GameStatus, CreateBookDto, UpdateBookDto, BookStatus, CreateMusicDto, UpdateMusicDto, MusicStatus, MusicType, CreateShowDto, UpdateShowDto, ShowStatus, ShowType, CreateMangaDto, UpdateMangaDto, MangaStatus, CreateArtDto, UpdateArtDto } from '@library/shared-types';

@Component({
  selector: 'app-admin-suggestions',
  standalone: true,
  imports: [CommonModule, FormsModule, PaginationComponent, GameFormComponent, BookFormComponent, MusicFormComponent, ShowFormComponent, MangaFormComponent, ArtFormComponent],
  template: `
    <div class="container">
      <div class="header-section">
        <h2>Manage Suggestions</h2>
        <p class="subtitle">Review and respond to community suggestions</p>
      </div>

      @if (!authService.isAdmin()) {
        <div class="not-authorized">
          <p>You don't have permission to view this page.</p>
        </div>
      } @else if (loading()) {
        <div class="loading">Loading suggestions...</div>
      } @else {
        <div class="filters">
          <button
            (click)="setFilter('all')"
            [class.active]="statusFilter() === 'all'"
            class="filter-btn"
          >
            All ({{ suggestions().length }})
          </button>
          <button
            (click)="setFilter(SuggestionStatus.unreviewed)"
            [class.active]="statusFilter() === SuggestionStatus.unreviewed"
            class="filter-btn pending"
          >
            Pending ({{ unreviewedCount() }})
          </button>
          <button
            (click)="setFilter(SuggestionStatus.accepted)"
            [class.active]="statusFilter() === SuggestionStatus.accepted"
            class="filter-btn accepted"
          >
            Accepted ({{ acceptedCount() }})
          </button>
          <button
            (click)="setFilter(SuggestionStatus.declined)"
            [class.active]="statusFilter() === SuggestionStatus.declined"
            class="filter-btn declined"
          >
            Declined ({{ declinedCount() }})
          </button>
        </div>

        @if (filteredSuggestions().length === 0) {
          <div class="empty-state">
            <p>No suggestions found.</p>
          </div>
        } @else {
          <app-pagination
            [currentPage]="currentPage()"
            [pageSize]="pageSize()"
            [totalItems]="totalFilteredSuggestions()"
            (pageChange)="onPageChange($event)"
            (pageSizeChange)="onPageSizeChange($event)"
          ></app-pagination>

          <div class="suggestions-list">
            @for (suggestion of paginatedSuggestions(); track suggestion.id) {
              <div class="suggestion-card" [class]="'status-' + suggestion.status.toLowerCase()">
                <div class="suggestion-header">
                  <div class="badges">
                    <span class="entity-badge" [class]="'entity-' + suggestion.entityType.toLowerCase()">
                      {{ getEntityIcon(suggestion.entityType) }} {{ suggestion.entityType }}
                    </span>
                    <span class="status-badge" [class]="'status-' + suggestion.status.toLowerCase()">
                      {{ getStatusLabel(suggestion.status) }}
                    </span>
                  </div>
                  <span class="user-info">
                    @if (suggestion.user.avatar) {
                      <img [src]="suggestion.user.avatar" [alt]="suggestion.user.username" class="user-avatar">
                    }
                    {{ suggestion.user.username }}
                  </span>
                </div>

                <h3 class="suggestion-title">{{ suggestion.title }}</h3>

                <div class="suggestion-details">
                  @if (suggestion.gameData) {
                    @if (suggestion.gameData.platform) {
                      <p><strong>Platform:</strong> {{ suggestion.gameData.platform }}</p>
                    }
                    @if (suggestion.gameData.notes) {
                      <p><strong>Notes:</strong> {{ suggestion.gameData.notes }}</p>
                    }
                    @if (suggestion.gameData.coverImage) {
                      <img [src]="suggestion.gameData.coverImage" alt="Cover" class="suggestion-image">
                    }
                  }
                  @if (suggestion.bookData) {
                    @if (suggestion.bookData.author) {
                      <p><strong>Author:</strong> {{ suggestion.bookData.author }}</p>
                    }
                    @if (suggestion.bookData.isbn) {
                      <p><strong>ISBN:</strong> {{ suggestion.bookData.isbn }}</p>
                    }
                    @if (suggestion.bookData.notes) {
                      <p><strong>Notes:</strong> {{ suggestion.bookData.notes }}</p>
                    }
                    @if (suggestion.bookData.coverImage) {
                      <img [src]="suggestion.bookData.coverImage" alt="Cover" class="suggestion-image">
                    }
                  }
                  @if (suggestion.musicData) {
                    @if (suggestion.musicData.artist) {
                      <p><strong>Artist:</strong> {{ suggestion.musicData.artist }}</p>
                    }
                    @if (suggestion.musicData.type) {
                      <p><strong>Type:</strong> {{ suggestion.musicData.type }}</p>
                    }
                    @if (suggestion.musicData.notes) {
                      <p><strong>Notes:</strong> {{ suggestion.musicData.notes }}</p>
                    }
                    @if (suggestion.musicData.coverArt) {
                      <img [src]="suggestion.musicData.coverArt" alt="Cover" class="suggestion-image">
                    }
                  }
                  @if (suggestion.artData) {
                    @if (suggestion.artData.artist) {
                      <p><strong>Artist:</strong> {{ suggestion.artData.artist }}</p>
                    }
                    @if (suggestion.artData.description) {
                      <p><strong>Description:</strong> {{ suggestion.artData.description }}</p>
                    }
                    @if (suggestion.artData.imageUrl) {
                      <img [src]="suggestion.artData.imageUrl" alt="Artwork" class="suggestion-image">
                    }
                  }
                  @if (suggestion.showData) {
                    @if (suggestion.showData.type) {
                      <p><strong>Type:</strong> {{ suggestion.showData.type }}</p>
                    }
                    @if (suggestion.showData.notes) {
                      <p><strong>Notes:</strong> {{ suggestion.showData.notes }}</p>
                    }
                    @if (suggestion.showData.coverImage) {
                      <img [src]="suggestion.showData.coverImage" alt="Cover" class="suggestion-image">
                    }
                  }
                  @if (suggestion.mangaData) {
                    @if (suggestion.mangaData.author) {
                      <p><strong>Author:</strong> {{ suggestion.mangaData.author }}</p>
                    }
                    @if (suggestion.mangaData.notes) {
                      <p><strong>Notes:</strong> {{ suggestion.mangaData.notes }}</p>
                    }
                    @if (suggestion.mangaData.coverImage) {
                      <img [src]="suggestion.mangaData.coverImage" alt="Cover" class="suggestion-image">
                    }
                  }
                </div>

                @if (suggestion.status === SuggestionStatus.declined && suggestion.declineReason) {
                  <div class="decline-reason">
                    <strong>Decline reason:</strong> {{ suggestion.declineReason }}
                  </div>
                }

                <div class="suggestion-footer">
                  <span class="date">Suggested on {{ formatDate(suggestion.createdAt) }}</span>

                  @if (suggestion.status === SuggestionStatus.unreviewed) {
                    <div class="actions">
                      <button (click)="acceptSuggestion(suggestion)" class="btn btn-accept">
                        Accept
                      </button>
                      <button (click)="openDeclineModal(suggestion)" class="btn btn-decline">
                        Decline
                      </button>
                    </div>
                  }
                </div>
              </div>
            }
          </div>

          <app-pagination
            [currentPage]="currentPage()"
            [pageSize]="pageSize()"
            [totalItems]="totalFilteredSuggestions()"
            (pageChange)="onPageChange($event)"
            (pageSizeChange)="onPageSizeChange($event)"
          ></app-pagination>
        }
      }

      @if (showDeclineModal()) {
        <div class="modal-overlay" (click)="closeDeclineModal()" (keyup.escape)="closeDeclineModal()" tabindex="0" role="button">
          <div class="modal" (click)="$event.stopPropagation()" (keyup)="$event.stopPropagation()" tabindex="-1">
            <h3>Decline Suggestion</h3>
            <p>Are you sure you want to decline "{{ decliningsuggestion()?.title }}"?</p>
            <div class="form-group">
              <label for="decline-reason">Reason (optional):</label>
              <textarea
                id="decline-reason"
                [(ngModel)]="declineReason"
                name="declineReason"
                rows="3"
                placeholder="Let the user know why you're declining this suggestion..."
              ></textarea>
            </div>
            <div class="modal-actions">
              <button (click)="confirmDecline()" class="btn btn-decline">Decline</button>
              <button (click)="closeDeclineModal()" class="btn btn-secondary">Cancel</button>
            </div>
          </div>
        </div>
      }

      @if (showEditModal()) {
        <div class="modal-overlay" (click)="closeEditModal()" (keyup.escape)="closeEditModal()" tabindex="0" role="button">
          <div class="modal edit-modal" (click)="$event.stopPropagation()" (keyup)="$event.stopPropagation()" tabindex="-1">
            @if (editingSuggestion()) {
              @if (editingSuggestion()!.entityType === SuggestionEntity.game) {
                <h3>Review & Edit Game Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-game-form
                  mode="add"
                  [initialData]="getGameInitialData(editingSuggestion()!)"
                  (formSubmit)="saveGameFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-game-form>
              } @else if (editingSuggestion()!.entityType === SuggestionEntity.book) {
                <h3>Review & Edit Book Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-book-form
                  mode="add"
                  [initialData]="getBookInitialData(editingSuggestion()!)"
                  (formSubmit)="saveBookFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-book-form>
              } @else if (editingSuggestion()!.entityType === SuggestionEntity.music) {
                <h3>Review & Edit Music Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-music-form
                  mode="add"
                  [initialData]="getMusicInitialData(editingSuggestion()!)"
                  (formSubmit)="saveMusicFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-music-form>
              } @else if (editingSuggestion()!.entityType === SuggestionEntity.show) {
                <h3>Review & Edit Show Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-show-form
                  mode="add"
                  [initialData]="getShowInitialData(editingSuggestion()!)"
                  (formSubmit)="saveShowFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-show-form>
              } @else if (editingSuggestion()!.entityType === SuggestionEntity.manga) {
                <h3>Review & Edit Manga Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-manga-form
                  mode="add"
                  [initialData]="getMangaInitialData(editingSuggestion()!)"
                  (formSubmit)="saveMangaFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-manga-form>
              } @else if (editingSuggestion()!.entityType === SuggestionEntity.art) {
                <h3>Review & Edit Art Before Accepting</h3>
                <p>Review and edit all the details before adding to your collection.</p>
                <app-art-form
                  mode="add"
                  [initialData]="getArtInitialData(editingSuggestion()!)"
                  (formSubmit)="saveArtFromSuggestion($event)"
                  (formCancel)="closeEditModal()"
                ></app-art-form>
              }
            }
          </div>
        </div>
      }
    </div>
  `,
  styles: [`
    .container {
      max-width: 900px;
      margin: 0 auto;
      padding: 2rem 1rem;
    }

    .header-section {
      margin-bottom: 2rem;
    }

    .header-section h2 {
      margin: 0 0 0.5rem 0;
    }

    .subtitle {
      color: #666;
      margin: 0;
    }

    .not-authorized,
    .loading,
    .empty-state {
      text-align: center;
      padding: 3rem;
      color: #666;
      background: #f8f9fa;
      border-radius: 8px;
    }

    .filters {
      display: flex;
      gap: 0.75rem;
      margin-bottom: 2rem;
      flex-wrap: wrap;
    }

    .filter-btn {
      padding: 0.5rem 1rem;
      background: #e5e7eb;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;
    }

    .filter-btn:hover {
      background: #d1d5db;
    }

    .filter-btn.active {
      color: white;
    }

    .filter-btn.active,
    .filter-btn.active.pending {
      background: #f59e0b;
    }

    .filter-btn.active.accepted {
      background: #10b981;
    }

    .filter-btn.active.declined {
      background: #ef4444;
    }

    .suggestions-list {
      display: flex;
      flex-direction: column;
      gap: 1rem;
    }

    .suggestion-card {
      background: white;
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      padding: 1.25rem;
      transition: box-shadow 0.3s;
    }

    .suggestion-card:hover {
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }

    .suggestion-card.status-accepted {
      border-left: 4px solid #10b981;
    }

    .suggestion-card.status-declined {
      border-left: 4px solid #ef4444;
    }

    .suggestion-card.status-unreviewed {
      border-left: 4px solid #f59e0b;
    }

    .suggestion-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.75rem;
      flex-wrap: wrap;
      gap: 0.5rem;
    }

    .badges {
      display: flex;
      gap: 0.5rem;
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-size: 0.875rem;
      color: #666;
    }

    .user-avatar {
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }

    .entity-badge,
    .status-badge {
      padding: 0.25rem 0.5rem;
      border-radius: 4px;
      font-size: 0.75rem;
      font-weight: 600;
      text-transform: uppercase;
    }

    .entity-badge {
      background: #e5e7eb;
      color: #374151;
    }

    .entity-badge.entity-game { background: #fff1f1; color: #dc2626; }
    .entity-badge.entity-book { background: #fdf4ed; color: #8b6f47; }
    .entity-badge.entity-music { background: #eff6ff; color: #2563eb; }
    .entity-badge.entity-manga { background: #ecfdf5; color: #059669; }
    .entity-badge.entity-show { background: #fdf2f8; color: #db2777; }
    .entity-badge.entity-art { background: #fefce8; color: #ca8a04; }

    .status-badge.status-unreviewed {
      background: #fef3c7;
      color: #92400e;
    }

    .status-badge.status-accepted {
      background: #d1fae5;
      color: #065f46;
    }

    .status-badge.status-declined {
      background: #fee2e2;
      color: #991b1b;
    }

    .suggestion-title {
      margin: 0 0 0.75rem 0;
      font-size: 1.1rem;
    }

    .suggestion-details {
      font-size: 0.9rem;
      color: #4b5563;
    }

    .suggestion-details p {
      margin: 0.25rem 0;
    }

    .suggestion-image {
      max-width: 150px;
      max-height: 200px;
      border-radius: 4px;
      margin-top: 0.5rem;
      border: 2px solid #e5e7eb;
    }

    .decline-reason {
      background: #fee2e2;
      border: 1px solid #fecaca;
      border-radius: 4px;
      padding: 0.75rem;
      margin-top: 0.75rem;
      font-size: 0.9rem;
      color: #991b1b;
    }

    .suggestion-footer {
      margin-top: 0.75rem;
      padding-top: 0.75rem;
      border-top: 1px solid #e5e7eb;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 0.5rem;
    }

    .date {
      font-size: 0.8rem;
      color: #9ca3af;
    }

    .actions {
      display: flex;
      gap: 0.5rem;
    }

    .btn {
      padding: 0.5rem 1rem;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-weight: 500;
      transition: all 0.3s;
    }

    .btn-accept {
      background: #10b981;
      color: white;
    }

    .btn-accept:hover {
      background: #059669;
    }

    .btn-decline {
      background: #ef4444;
      color: white;
    }

    .btn-decline:hover {
      background: #dc2626;
    }

    .btn-secondary {
      background: #e5e7eb;
      color: #374151;
    }

    .btn-secondary:hover {
      background: #d1d5db;
    }

    /* Modal styles */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }

    .modal {
      background: white;
      border-radius: 8px;
      padding: 1.5rem;
      max-width: 500px;
      width: 90%;
      max-height: 90vh;
      overflow-y: auto;
    }

    .edit-modal {
      max-width: 650px;
    }

    .edit-modal form {
      margin-top: 1rem;
    }

    .modal h3 {
      margin: 0 0 1rem 0;
    }

    .modal p {
      margin: 0 0 1rem 0;
      color: #666;
    }

    .form-group {
      margin-bottom: 1rem;
    }

    .form-group label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 500;
    }

    .form-group textarea {
      width: 100%;
      padding: 0.5rem;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 1rem;
      resize: vertical;
    }

    .modal-actions {
      display: flex;
      gap: 0.5rem;
      justify-content: flex-end;
    }
  `]
})
export class AdminSuggestionsComponent implements OnInit {
  suggestionService = inject(SuggestionService);
  authService = inject(AuthService);

  suggestions = signal<Suggestion[]>([]);
  loading = signal(true);
  statusFilter = signal<'all' | SuggestionStatus>('all');
  showDeclineModal = signal(false);
  decliningsuggestion = signal<Suggestion | null>(null);
  declineReason = '';

  // Edit modal state
  showEditModal = signal(false);
  editingSuggestion = signal<Suggestion | null>(null);
  editedData: any = {};

  // Pagination state
  currentPage = signal(1);
  pageSize = signal(25);

  SuggestionStatus = SuggestionStatus;
  SuggestionEntity = SuggestionEntity;

  unreviewedCount = () => this.suggestions().filter(s => s.status === SuggestionStatus.unreviewed).length;
  acceptedCount = () => this.suggestions().filter(s => s.status === SuggestionStatus.accepted).length;
  declinedCount = () => this.suggestions().filter(s => s.status === SuggestionStatus.declined).length;

  filteredSuggestions = computed(() => {
    const filter = this.statusFilter();
    if (filter === 'all') {
      return this.suggestions();
    }
    return this.suggestions().filter(s => s.status === filter);
  });

  paginatedSuggestions = computed(() => {
    const suggestions = this.filteredSuggestions();
    const start = (this.currentPage() - 1) * this.pageSize();
    const end = start + this.pageSize();
    return suggestions.slice(start, end);
  });

  totalFilteredSuggestions = computed(() => this.filteredSuggestions().length);

  ngOnInit() {
    if (this.authService.isAdmin()) {
      this.loadSuggestions();
    } else {
      this.loading.set(false);
    }
  }

  async loadSuggestions() {
    this.loading.set(true);
    try {
      const suggestions = await this.suggestionService.getAllSuggestions();
      this.suggestions.set(suggestions);
    } catch {
      // Handle error silently
    } finally {
      this.loading.set(false);
    }
  }

  setFilter(filter: 'all' | SuggestionStatus) {
    this.statusFilter.set(filter);
    this.currentPage.set(1); // Reset to first page when filter changes
  }

  onPageChange(page: number) {
    this.currentPage.set(page);
  }

  onPageSizeChange(pageSize: number) {
    this.pageSize.set(pageSize);
    // Calculate new current page to stay on approximately the same content
    const firstItemIndex = (this.currentPage() - 1) * this.pageSize();
    const newPage = Math.floor(firstItemIndex / pageSize) + 1;
    this.currentPage.set(newPage);
  }

  getStatusLabel(status: SuggestionStatus): string {
    switch (status) {
      case SuggestionStatus.unreviewed: return 'Pending';
      case SuggestionStatus.accepted: return 'Accepted';
      case SuggestionStatus.declined: return 'Declined';
    }
  }

  getEntityIcon(entityType: SuggestionEntity): string {
    switch (entityType) {
      case SuggestionEntity.game: return '🎮';
      case SuggestionEntity.book: return '📚';
      case SuggestionEntity.music: return '🎵';
      case SuggestionEntity.manga: return '📖';
      case SuggestionEntity.show: return '📺';
      case SuggestionEntity.art: return '🎨';
    }
  }

  formatDate(date: Date | string): string {
    return new Date(date).toLocaleDateString();
  }

  getGameInitialData(suggestion: Suggestion): Partial<CreateGameDto> {
    const gameData = suggestion.gameData as any;
    return {
      title: suggestion.title,
      platform: gameData?.platform || undefined,
      status: GameStatus.backlog, // Default to backlog for new suggestions
      notes: gameData?.notes || undefined,
      coverImage: gameData?.coverImage || undefined,
      tags: [],
      links: []
    };
  }

  async saveGameFromSuggestion(data: CreateGameDto | UpdateGameDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      // Treat it as CreateGameDto since we're creating a new item from a suggestion
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateGameDto);
      alert(`"${(data as CreateGameDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  getBookInitialData(suggestion: Suggestion): Partial<CreateBookDto> {
    const bookData = suggestion.bookData as any;
    return {
      title: suggestion.title,
      author: bookData?.author || '',
      isbn: bookData?.isbn || undefined,
      status: BookStatus.toRead,
      notes: bookData?.notes || undefined,
      coverImage: bookData?.coverImage || undefined,
      tags: [],
      links: []
    };
  }

  async saveBookFromSuggestion(data: CreateBookDto | UpdateBookDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateBookDto);
      alert(`"${(data as CreateBookDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  getMusicInitialData(suggestion: Suggestion): Partial<CreateMusicDto> {
    const musicData = suggestion.musicData as any;
    return {
      title: suggestion.title,
      artist: musicData?.artist || '',
      type: musicData?.type || MusicType.album,
      status: MusicStatus.wantToListen,
      notes: musicData?.notes || undefined,
      coverArt: musicData?.coverArt || undefined,
      tags: [],
      links: []
    };
  }

  async saveMusicFromSuggestion(data: CreateMusicDto | UpdateMusicDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateMusicDto);
      alert(`"${(data as CreateMusicDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  getShowInitialData(suggestion: Suggestion): Partial<CreateShowDto> {
    const showData = suggestion.showData as any;
    return {
      title: suggestion.title,
      type: showData?.type || ShowType.tvSeries,
      status: ShowStatus.wantToWatch,
      notes: showData?.notes || undefined,
      coverImage: showData?.coverImage || undefined,
      tags: [],
      links: []
    };
  }

  async saveShowFromSuggestion(data: CreateShowDto | UpdateShowDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateShowDto);
      alert(`"${(data as CreateShowDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  getMangaInitialData(suggestion: Suggestion): Partial<CreateMangaDto> {
    const mangaData = suggestion.mangaData as any;
    return {
      title: suggestion.title,
      author: mangaData?.author || '',
      status: MangaStatus.wantToRead,
      notes: mangaData?.notes || undefined,
      coverImage: mangaData?.coverImage || undefined,
      tags: [],
      links: []
    };
  }

  async saveMangaFromSuggestion(data: CreateMangaDto | UpdateMangaDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateMangaDto);
      alert(`"${(data as CreateMangaDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  getArtInitialData(suggestion: Suggestion): Partial<CreateArtDto> {
    const artData = suggestion.artData as any;
    return {
      title: suggestion.title,
      artist: artData?.artist || '',
      description: artData?.description || undefined,
      imageUrl: artData?.imageUrl || '',
      tags: [],
      links: []
    };
  }

  async saveArtFromSuggestion(data: CreateArtDto | UpdateArtDto) {
    const suggestion = this.editingSuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.acceptSuggestionWithEdits(suggestion.id, data as CreateArtDto);
      alert(`"${(data as CreateArtDto).title}" has been added to your collection!`);
      this.closeEditModal();
      this.loadSuggestions();
    } catch (error) {
      alert('Failed to accept suggestion. Please try again.');
    }
  }

  async acceptSuggestion(suggestion: Suggestion) {
    this.editingSuggestion.set(suggestion);

    // For all entity types, we'll use the form components which have their own initialization logic
    this.showEditModal.set(true);
  }

  openDeclineModal(suggestion: Suggestion) {
    this.decliningsuggestion.set(suggestion);
    this.declineReason = '';
    this.showDeclineModal.set(true);
  }

  closeDeclineModal() {
    this.showDeclineModal.set(false);
    this.decliningsuggestion.set(null);
    this.declineReason = '';
  }

  closeEditModal() {
    this.showEditModal.set(false);
    this.editingSuggestion.set(null);
    this.editedData = {};
  }

  async confirmDecline() {
    const suggestion = this.decliningsuggestion();
    if (!suggestion) return;

    try {
      await this.suggestionService.declineSuggestion(suggestion.id, {
        reason: this.declineReason || undefined
      });
      this.closeDeclineModal();
      this.loadSuggestions();
    } catch {
      alert('Failed to decline suggestion. Please try again.');
    }
  }
}
