import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  TemplateRef,
  ViewChild,
  computed,
  effect,
  signal,
} from '@angular/core';
import { DataTable, SortState, TableColumn } from '@shared/components/data-table/data-table';
import { Modal } from '@shared/components/modal/modal';
import { Paginator } from '@shared/components/paginator/paginator';
import { SearchBar } from '@shared/components/search-bar/search-bar';
import { HippodromeForm } from '@shared/forms/hippodrome-form/hippodrome-form';
import { Hippodrome as HippodromeType } from 'src/app/core/interfaces/hippodrome';
import { HippodromeService } from 'src/app/core/services/hippodrome';
import { ZardBreadcrumbModule } from '@shared/components/sheet/sheet.module';
import { ZardCardComponent } from '@shared/components/card/card.component';
import { LucideAngularModule } from 'lucide-angular';

@Component({
  standalone: true,
  selector: 'app-hippodrome-list',
  imports: [
    CommonModule,
    DataTable,
    Paginator,
    SearchBar,
    Modal,
    HippodromeForm,
    ZardBreadcrumbModule,
    ZardCardComponent,
    LucideAngularModule,
  ],
  templateUrl: './hippodrome.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Hippodrome {
  rows = signal<HippodromeType[]>([]);
  loading = signal(false);
  total = signal(0);
  uniqueCountries = signal(0);
  uniqueCities = signal(0);
  averageByCountry = signal(0);
  totalReunions = signal(0);
  totalCourses = signal(0);

  page = signal(0);
  perPage = signal(10);
  pageSize = [10, 20, 50];
  search = signal('');
  sort = signal<SortState>({ key: 'nom', dir: 'asc' });

  @ViewChild(HippodromeForm) formComp?: HippodromeForm;

  cols: TableColumn<HippodromeType>[] = [
    { key: 'nom', label: 'Nom', sortable: true },
    { key: 'ville', label: 'Ville', sortable: true },
    { key: 'pays', label: 'Pays', sortable: true },
    {
      key: 'capacite',
      label: 'Capacité',
      sortable: true,
      cell: (h) => (h.capacite ? h.capacite.toLocaleString('fr-FR') : '—'),
    },
    {
      key: 'actif',
      label: 'Statut',
      sortable: true,
      cell: (h) =>
        `<span class="inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${
          h.actif
            ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300'
            : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'
        }">
          <span class="h-2 w-2 rounded-full ${h.actif ? 'bg-green-500' : 'bg-red-500'}"></span>
          ${h.actif ? 'Actif' : 'Inactif'}
        </span>`,
    },
    {
      key: 'createdAt',
      label: 'Créé le',
      sortable: true,
      cell: (h) =>
        new Date(h.createdAt).toLocaleDateString('fr-FR', {
          day: '2-digit',
          month: 'short',
          year: 'numeric',
        }),
    },
  ];

  // Modale
  modalOpen = signal(false);
  modalTitle = signal('Nouvel hippodrome');
  editingItem = signal<Partial<HippodromeType> | null>(null); // null => création

  constructor(private api: HippodromeService) {
    effect(() => this.fetch());
  }

  private fetch() {
    this.loading.set(true);
    this.api
      .list({
        page: this.page(),
        size: this.perPage(),
        search: this.search(),
        sortKey: this.sort().key,
        sortDir: this.sort().dir,
      })
      .subscribe({
        next: (res) => {
          const content = res.content;
          this.rows.set(content);
          this.total.set(res.pageable.total ?? 0);
          this.uniqueCities.set(new Set(content.map(i=> i.ville)).size);
          this.uniqueCountries.set(new Set(content.map(i=>i.pays)).size);
          this.averageByCountry.set(0);
          this.loading.set(false);
        },
        error: (err) => {
          this.rows.set([]);
          this.total.set(0);
          this.uniqueCities.set(0);
          this.uniqueCountries.set(0);
          this.averageByCountry.set(0);
          this.loading.set(false);
        },
      });
  }

  onSearch(q: string) {
    this.search.set(q);
    this.page.set(1);
  }
  onSort(s: SortState) {
    this.sort.set(s);
    this.page.set(1);
  }
  onPerPage(n: number) {
    this.perPage.set(n);
    this.page.set(1);
  }

  openCreate() {
    this.modalTitle.set('Nouvel hippodrome');
    this.editingItem.set(null);
    queueMicrotask(() => this.modalOpen.set(true));
  }

  openEdit(ev: HippodromeType) {
    this.modalTitle.set('Modifier l’hippodrome');
    this.editingItem.set(ev);
    queueMicrotask(() => this.modalOpen.set(true));
  }

  closeModal() {
    this.modalOpen.set(false);
  }

  submitChildForm() {
    // Déclenche le submit du formulaire enfant
    this.formComp?.onSubmit();
  }

  onFormSave(payload: Partial<HippodromeType>) {
    const current = this.editingItem();
    const req$ = current?.id
      ? this.api.update(current.id, payload)
      : this.api.create(payload as Omit<HippodromeType, 'id'>);

    req$.subscribe(() => {
      this.closeModal();
      // Reset editing item to null to clear the form
      this.editingItem.set(null);
      this.fetch();
    });
  }

  remove(ev: HippodromeType) {
    if (!confirm(`Supprimer l’hippodrome « ${ev.nom} » ?`)) return;
    this.api.delete(ev.id).subscribe(() => this.fetch());
  }
}
