import { Component,OnInit } from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";
import { ImageInputComponent } from "../shared/shared-forms/image-input.component";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { DatePickerModule } from "primeng/datepicker";
import { LiveApiService } from "../+schedule-live/live-api-service";
import { Notifier } from "@app/core";


interface AdminVideoForm {
  title: string;
  camera: string;
}

type AdminLiveState = "active" | "disabled";
type ApiLiveStatus = "scheduled" | "cancelled" | "completed";

@Component({
  selector: "app-admin-controller",
  standalone: true,
  templateUrl: "./admin-live.component.html",
  styleUrls: ["./admin-live.component.scss"],
  imports: [ImageInputComponent, CommonModule, FormsModule, DatePickerModule],
})
export class AdminLiveComponent implements OnInit {
  formVideo: AdminVideoForm = {
    title: "",
    camera: "",
  };

  thumbnailFile: File | null = null;
  thumbnailPreview: string | null = null;
  videoFile: File | null = null;
  subtitleFile: File | null = null;
  dropdownOpen = false;
  selectedCamera: string | null = null;
  startTime: Date | null = null;
  endTime: Date | null = null;
  liveId: number | null = null;
  liveState: AdminLiveState = "active";
  isEditMode = true;
  pendingDelete = false;
  hasPendingAction = false;

  cameras: string[] = [
    "camera001",
    "camera002",
    "camera003",
    "camera004",
    "camera005",
  ];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private liveApi: LiveApiService,
    private notifier: Notifier
  ) {}
  enableEditMode() {
    this.isEditMode = true;
  }
  onBitmapChange(file: File) {
    this.thumbnailFile = file;
  }
  ngOnInit() {
    const id = this.route.snapshot.paramMap.get("id");

    if (id) {
      this.liveId = Number(id);
      this.loadLiveVideo();
      this.isEditMode = false;
    }
  }
  loadLiveVideo() {
    if (!this.liveId) return;

    this.liveApi.getLiveVideo(this.liveId).subscribe({
      next: (video: any) => {
        this.formVideo.title = video.title;
        this.formVideo.camera = video.targetCamera;

        this.selectedCamera = video.targetCamera;

        this.startTime = this.normalizeToMinute(video.startTime);
        this.endTime = this.normalizeToMinute(video.endTime);

        if (video.thumbnailFilename) {
          this.thumbnailPreview = '/lazy-static/thumbnails/' + video.thumbnailFilename;
        }

        this.liveState = this.mapStatusToState(video.status);
      },
      error: (err) => {
        console.error(err);
        this.notifier.error("Failed to load live video");
      },
    });
  }
  onVideoSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (!input.files || input.files.length === 0) return;

    this.videoFile = input.files[0];
  }
  onSubtitleSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (!input.files || input.files.length === 0) return;

    this.subtitleFile = input.files[0];
  }
  setLiveState(state: AdminLiveState) {
    if (!this.liveId) return;

    this.liveState = state;
    this.pendingDelete = false;
    this.hasPendingAction = true;

    this.notifier.success(`Live marked as ${state}`);
  }
  deleteCurrentLive() {
    if (!this.liveId) return;

    if (!confirm(`Delete "${this.formVideo.title}"?`)) return;

    this.pendingDelete = true;
  
    this.liveApi.deleteLiveVideo(this.liveId).subscribe({
      next: () => {
        this.notifier.success("Live deleted successfully");
        this.router.navigateByUrl("/admin-controller/live");
      },
      error: () => {
        this.pendingDelete = false;
        this.notifier.error("Failed to delete live");
      }
    });
  }

  toggleDropdown() {
    this.dropdownOpen = !this.dropdownOpen;
  }
  selectCamera(cam: string, event: Event) {
    event.stopPropagation();
    this.selectedCamera = cam;
    this.formVideo.camera = cam;
    this.dropdownOpen = false;
  }

  onStartTimeChange(value: Date | string | null) {
    this.startTime = this.normalizeToMinute(value);
  }

  onEndTimeChange(value: Date | string | null) {
    this.endTime = this.normalizeToMinute(value);
  }

  saveVideo() {
    if (!this.formVideo.title || !this.formVideo.camera) {
      this.notifier.error("Please fill required fields");
      return;
    }

    const formData = new FormData();
    const normalizedStartTime = this.normalizeToMinute(this.startTime);
    const normalizedEndTime = this.normalizeToMinute(this.endTime);

    this.startTime = normalizedStartTime;
    this.endTime = normalizedEndTime;

    formData.append("title", this.formVideo.title);
    formData.append("targetCamera", this.formVideo.camera);

    if (normalizedStartTime)
      formData.append("startTime", normalizedStartTime.toISOString());

    if (normalizedEndTime) formData.append("endTime", normalizedEndTime.toISOString());

    if (this.thumbnailFile instanceof File)
      formData.append("thumbnailfile", this.thumbnailFile);

    if (this.videoFile) formData.append("videofile", this.videoFile);
    if (this.subtitleFile) formData.append("subtitlefile", this.subtitleFile);

    formData.append("status", this.mapStateToStatus(this.liveState));

    // DELETE
    // if (this.liveId && this.pendingDelete) {
    //   this.liveApi.deleteLiveVideo(this.liveId).subscribe({
    //     next: () => {
    //       this.notifier.success("Live deleted successfully");
    //       this.router.navigateByUrl("/admin-controller/live");
    //     },
    //     error: (err) => {
    //       console.error(err);
    //       this.notifier.error("Failed to delete live");
    //     },
    //   });

    //   return;
    // }

    // UPDATE
    if (this.liveId) {
      this.liveApi.updateLiveVideo(this.liveId, formData).subscribe({
        next: () => {
          this.notifier.success("Live updated successfully");
          this.router.navigateByUrl("/admin-controller/live");
        },
        error: (err) => {
          console.error(err);
        },
      });

      return;
    }

    // CREATE
    this.liveApi.createLiveVideo(formData).subscribe({
      next: () => {
        this.notifier.success("Live created successfully");
        this.router.navigateByUrl("/admin-controller/live");
      },
      error: (err) => {
        console.error(err)
      
        let message = 'Failed to schedule live video'
      
        if (err?.error?.message) {
          message = err.error.message
        } else if (err?.message) {
          message = err.message
        }
      
        this.notifier.error(message)
      }
    });
  }
  cancel() {
    this.router.navigateByUrl("/admin-controller/live");
  }

  private normalizeToMinute(value: Date | string | null) {
    if (!value) return null;

    const date = value instanceof Date ? new Date(value.getTime()) : new Date(value);
    if (Number.isNaN(date.getTime())) return null;

    date.setSeconds(0, 0);
    return date;
  }

  private mapStatusToState(status: ApiLiveStatus | undefined): AdminLiveState {
    return status === "cancelled" ? "disabled" : "active";
  }

  private mapStateToStatus(state: AdminLiveState): ApiLiveStatus {
    return state === "disabled" ? "cancelled" : "scheduled";
  }
}
