import { Component, OnInit, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { AuthService } from '../../../services/auth.service';
import { QuizService } from '../../../services/quiz.service';

@Component({
  selector: 'app-user-history',
  standalone: true,
  imports: [CommonModule, RouterLink],
  templateUrl: './user-history.html',
  styleUrl: './user-history.css'
})
export class UserHistoryComponent implements OnInit {
  userId = '';
  user = signal<any>(null);
  interviews = signal<any[]>([]);
  // The interview the user has drilled into
  selectedInterview = signal<any>(null);
  // Submissions for the selected interview's quizzes
  submissions = signal<any[]>([]);
  loadingInterviews = signal<boolean>(true);
  loadingSubmissions = signal<boolean>(false);

  currentLevel = signal<string>('beginner');
  toast = signal<{ message: string; type: 'success' | 'error' } | null>(null);

  // Expose String for template
  readonly String = String;

  levels = [
    { value: 'beginner', label: 'Fresher' },
    { value: 'intermediate', label: 'Intern' },
    { value: 'advanced', label: 'Pre final year' },
    { value: 'expert', label: 'Final year' }
  ];

  /** Difficulty → level code mapping */
  private levelCodeMap: Record<string, string> = {
    easy: 'BEG',
    medium: 'INT',
    hard: 'ADV'
  };

  constructor(
    private route: ActivatedRoute,
    public authService: AuthService,
    private quizService: QuizService
  ) { }

  ngOnInit(): void {
    this.userId = this.route.snapshot.params['userId'];
    this.loadInterviews();
  }

  loadInterviews(): void {
    this.loadingInterviews.set(true);
    this.quizService.getUserInterviews(this.userId).subscribe({
      next: (res) => {
        this.user.set(res.user);
        this.currentLevel.set(res.user.level || 'beginner');
        this.interviews.set(res.interviews);
        this.loadingInterviews.set(false);
      },
      error: () => this.loadingInterviews.set(false)
    });
  }

  selectInterview(interview: any): void {
    this.selectedInterview.set(interview);
    // Load submissions for the quizzes in this interview
    this.loadingSubmissions.set(true);
    this.quizService.getUserHistory(this.userId).subscribe({
      next: (res) => {
        this.submissions.set(res.submissions || []);
        this.loadingSubmissions.set(false);
      },
      error: () => this.loadingSubmissions.set(false)
    });
  }

  goBackToList(): void {
    this.selectedInterview.set(null);
    this.submissions.set([]);
  }

  /** Find submission for a given quizId from the loaded submissions */
  getSubmissionForQuiz(quizId: any): any {
    if (!quizId) return null;
    const qidStr = quizId.toString();
    return this.submissions().find((s: any) =>
      (s.quizId?._id?.toString() || s.quizId?.toString()) === qidStr
    ) || null;
  }

  /** Generate a quiz ID like Q_Aptitude_BEG_001 for a given quiz within an interview */
  getQuizId(interviewQuiz: any, index: number): string {
    const quizData = interviewQuiz.quizId || {};
    const topic = (quizData.category || 'General').replace(/\s+/g, '_');
    const diff = (quizData.difficulty || 'easy').toLowerCase();
    const levelCode = this.levelCodeMap[diff] || 'BEG';
    const seq = String(index + 1).padStart(3, '0');
    return `Q_${topic}_${levelCode}_${seq}`;
  }

  changeLevel(newLevel: string): void {
    if (newLevel === this.currentLevel()) return;

    this.quizService.updateUserLevel(this.userId, newLevel).subscribe({
      next: (res) => {
        this.currentLevel.set(newLevel);
        this.showToast(
          `Level changed from ${this.capitalize(res.previousLevel)} to ${this.capitalize(res.newLevel)}`,
          'success'
        );
      },
      error: (err) => {
        this.showToast(err.error?.message || 'Failed to update level', 'error');
      }
    });
  }

  getStatusClass(status: string): string {
    switch (status) {
      case 'completed': return 'status-done';
      case 'evaluation': return 'status-evaluation';
      default: return 'status-pending';
    }
  }

  getStatusLabel(status: string): string {
    switch (status) {
      case 'completed': return 'Done';
      case 'evaluation': return 'Evaluation';
      case 'coding_phase': return 'Coding Round';
      case 'quiz_phase': return 'Quiz Phase';
      default: return 'Pending';
    }
  }

  private showToast(message: string, type: 'success' | 'error'): void {
    this.toast.set({ message, type });
    setTimeout(() => this.toast.set(null), 3500);
  }

  private capitalize(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  formatTime(seconds: number): string {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}m ${s}s`;
  }

  getComfortLevel(topic: string): string {
    const u = this.user();
    if (!u || !u.topicsOfInterest || !topic) return 'N/A';
    const interest = u.topicsOfInterest.find((t: any) => t.topic.toLowerCase() === topic.toLowerCase());
    return interest ? `${interest.comfortLevel}%` : 'N/A';
  }

  getResumeUrl(resumePath: string): string {
    if (!resumePath) return '';
    return `http://localhost:5000${resumePath}`;
  }

  hasEvaluations(interview: any): boolean {
    return (interview.evaluations?.length || 0) > 0;
  }

  downloadEvaluationForm(interview: any): void {
    const u = this.user();
    const candidateName = u?.name || '';
    const dateStr = interview.dateOfInterview
      ? new Date(interview.dateOfInterview).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })
      : '';
    const position = interview.position || '';
    const source = interview.source || '';
    const techStack = interview.techStack || '';

    const interviewerNames = (interview.assignedInterviewers || [])
      .map((i: any) => i.name || '').filter(Boolean).join(', ')
      || interview.interviewerId?.name || 'Unassigned';

    const quizzes = interview.quizzes || [];
    const q1 = quizzes[0];
    const q2 = quizzes[1];
    const q1Name = q1?.quizId?.title || q1?.title || '';
    const q1Score = (q1?.score != null) ? `${q1.score}/${q1.totalMarks}` : '';
    const q2Name = q2?.quizId?.title || q2?.title || '';
    const q2Score = (q2?.score != null) ? `${q2.score}/${q2.totalMarks}` : '';

    const evals = interview.evaluations || [];
    const ivEval = evals.find((e: any) => e.evaluatorRole === 'interviewer');
    const pmEval = evals.find((e: any) => e.evaluatorRole === 'pm');
    const hrEval = evals.find((e: any) => e.evaluatorRole === 'hr');
    const adminEval = evals.find((e: any) => e.evaluatorRole === 'admin');

    const recMap: Record<string, string> = {
      offer: 'Offer/Hire as Intern', on_hold: 'On Hold',
      rejected: 'Rejected', '2nd_round': '2nd Round'
    };

    const buildCheckboxes = (groupName: string, rec: string): string =>
      ['offer', 'on_hold', 'rejected', '2nd_round'].map(val => {
        const checked = rec === val ? 'checked' : '';
        const label = val === '2nd_round' ? '2<sup>nd</sup> Round' : recMap[val];
        return `<label style="display:flex;align-items:center;gap:5px;font-size:13px;"><input type="checkbox" name="${groupName}" ${checked} style="width:14px;height:14px;accent-color:#4472C4;"> ${label}</label>`;
      }).join('');

    const fmtDate = (d: any) => d ? new Date(d).toLocaleDateString('en-GB') : '';
    const ivName = ivEval?.evaluatorId?.name || 'Interviewer';
    const pmName = pmEval?.evaluatorId?.name || 'Project Manager';
    const hrName = hrEval?.evaluatorId?.name || 'HR';
    const adminName = adminEval?.evaluatorId?.name || 'Administrator';
    const overallRec = adminEval?.recommendation || interview.finalDecision || '';

    const getSigHtml = (evalObj: any, fallbackName: string) => {
      if (evalObj && evalObj.evaluatorId && evalObj.evaluatorId.signature) {
        return `<img src="http://localhost:5000${evalObj.evaluatorId.signature}" alt="Signature"/>`;
      }
      return fallbackName || '';
    };

    const ITL_LOGO = '/logo.jpeg';
    const html = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"/>
<title>ITL Evaluation - ${candidateName}</title><style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
body{font-family:Arial,sans-serif;background:#fff;color:#000;padding:24px;font-size:13px;}
.page-wrap{max-width:780px;margin:0 auto;border:1px solid #ccc;}
.header{background:#4472C4;display:flex;align-items:center;justify-content:space-between;padding:10px 16px;}
.header h1{color:#fff;font-size:26px;font-weight:bold;}
.logo-wrap img{height:52px;object-fit:contain;}
.info-table{width:100%;border-collapse:collapse;}
.info-table td{border:1px solid #bbb;padding:6px 10px;vertical-align:middle;}
.info-table .label{font-weight:bold;background:#fff;width:160px;white-space:nowrap;}
.info-table .value{background:#fff;color:#444;font-style:italic;}
.comments-section{border:1px solid #bbb;border-top:none;padding:10px 16px;}
.comments-label{font-weight:bold;margin-bottom:6px;}
.comments-text{min-height:65px;font-size:13px;font-family:Arial,sans-serif;color:#333;line-height:1.5;padding:4px 0;}
.rec-row{border:1px solid #bbb;border-top:none;padding:8px 16px;display:flex;align-items:center;gap:20px;flex-wrap:wrap;}
.rec-label{font-weight:bold;white-space:nowrap;}

.sig-row{
  border:1px solid #bbb;
  border-top:none;
  padding:14px 16px 10px;
  display:flex;
  justify-content:space-between;
  align-items:flex-end;
  gap:40px;
  page-break-inside: avoid;
  break-inside: avoid;
}

.sig-field{
  display:flex;
  align-items:flex-end;
  gap:10px;
  flex:1;
}

.sig-field label{
  font-weight:bold;
  white-space:nowrap;
  font-size:14px;
}

.signature-box{
  border-bottom:2px solid #222;
  width:165px;          
  height:26px;          
  display:flex;
  justify-content:center;
  align-items:flex-end;
  padding-bottom:4px;
}

.signature-box img{
  max-height:18px;      
  max-width:90px;       
  object-fit:contain;
}

.date-box{
  border-bottom:2px solid #222;
  width:130px;         
  height:22px;          
  display:flex;
  align-items:flex-end;
  padding-bottom:3px;
  font-style:italic;
  color:#444;
}



.actions{margin-top:16px;display:flex;justify-content:flex-end;gap:10px;}
.btn{font-size:13px;font-family:Arial,sans-serif;padding:7px 18px;border-radius:3px;cursor:pointer;border:1px solid #aaa;}
.btn-print{background:#4472C4;color:#fff;border-color:#3360b0;}
@media print{body{padding:0;}.actions{display:none;}}
</style></head><body>
<div class="page-wrap">
  <div class="header">
    <h1>Candidate Evaluation Form</h1>
    <div class="logo-wrap"><img src="${ITL_LOGO}" alt="ITL Logo"/></div>
  </div>
  <table class="info-table"><tbody>
    <tr>
      <td class="label">Candidate Name:</td><td class="value">${candidateName}</td>
      <td class="label">Date of Interview:</td><td class="value">${dateStr}</td>
    </tr>
    <tr>
      <td class="label">Position:</td><td class="value">${position}</td>
      <td class="label">Source:</td><td class="value">${source}</td>
    </tr>
    <tr>
      <td class="label">Tech Stack:</td><td class="value">${techStack}</td>
      <td class="label"><strong>Interviewer:</strong></td><td class="value">${interviewerNames}</td>
    </tr>
    <tr>
      <td class="label">General Aptitude Test QP Set</td><td class="value">${q1Name}</td>
      <td class="label"><strong>General Aptitude Test Score</strong></td><td class="value">${q1Score}</td>
    </tr>
    <tr>
      <td class="label">Technical MCQ Test QP Set</td><td class="value">${q2Name}</td>
      <td class="label"><strong>Technical MCQ Test Score</strong></td><td class="value">${q2Score}</td>
    </tr>
  </tbody></table>

  <div class="comments-section" style="margin-top:0;">
    <div class="comments-label">Interviewer's Comments (${ivName}):</div>
    <div class="comments-text">${ivEval?.comments || ''}</div>
  </div>
  <div class="rec-row"><span class="rec-label">Recommendation:</span>${buildCheckboxes('rec1', ivEval?.recommendation || '')}</div>
<div class="sig-row">
  <div class="sig-field">
    <label>Evaluator's Signature:</label>
    <div class="signature-box">
      ${getSigHtml(ivEval, ivName)}
    </div>
  </div>

  <div class="sig-field" style="flex:0.55;">
    <label>Date:</label>
    <div class="date-box">
      ${fmtDate(ivEval?.date)}
    </div>
  </div>
</div>

  <div class="comments-section">
    <div class="comments-label">Project Manager Comments (${pmName}):</div>
    <div class="comments-text">${pmEval?.comments || ''}</div>
  </div>
  <div class="rec-row"><span class="rec-label">Recommendation:</span>${buildCheckboxes('rec2', pmEval?.recommendation || '')}</div>
  <div class="sig-row">
  <div class="sig-field">
    <label>Evaluator's Signature:</label>
    <div class="signature-box">
${getSigHtml(pmEval, pmName)}
    </div>
  </div>

  <div class="sig-field" style="flex:0.55;">
    <label>Date:</label>
    <div class="date-box">
${fmtDate(pmEval?.date)}
    </div>
  </div>
</div>


  <div class="comments-section">
    <div class="comments-label">HR Comments (${hrName}):</div>
    <div class="comments-text" style="min-height:52px;">${hrEval?.comments || ''}</div>
  </div>
  <div class="rec-row"><span class="rec-label">Recommendation:</span>${buildCheckboxes('rec3', hrEval?.recommendation || '')}</div>
<div class="sig-row">
  <div class="sig-field">
    <label>Evaluator's Signature:</label>
    <div class="signature-box">
 ${getSigHtml(hrEval, hrName)}
    </div>
  </div>

  <div class="sig-field" style="flex:0.55;">
    <label>Date:</label>
    <div class="date-box">
${fmtDate(hrEval?.date)}
    </div>
  </div>
</div>


    <div class="comments-section">
    <div class="comments-label">Overall Comments (${adminEval?.evaluatorId?.name}):</div>
    <div class="comments-text" style="min-height:52px;">${adminEval?.comments || ''}</div>
  </div>
  <div class="rec-row"><span class="rec-label">Recommendation:</span>${buildCheckboxes('rec-overall', overallRec)}</div>
  
  <div class="sig-row">
  <div class="sig-field">
    <label>Evaluator's Signature:</label>
    <div class="signature-box">
${getSigHtml(adminEval, adminName)}
    </div>
  </div>

  <div class="sig-field" style="flex:0.55;">
    <label>Date:</label>
    <div class="date-box">${fmtDate(adminEval?.date)}</div>
  </div>
</div>

</div>
<div class="actions">
  <button class="btn btn-print" onclick="window.print()">&#128438; Print / Save as PDF</button>
</div>
</body></html>`;

    const win = window.open('', '_blank');
    if (win) {
      win.document.write(html);
      win.document.close();
      win.focus();
    }
  }
}
