'use client';

import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { toast } from 'react-toastify';
import { api } from '@/lib/api';
import { CLASSIFICATION_BADGES } from './CandidateReportsTable';
import type { CandidateReportDetailData } from './types';

function ScoreRow({ label, value }: { label: string; value: number }) {
  const color = value >= 75 ? 'bg-emerald-500' : value >= 50 ? 'bg-amber-500' : 'bg-rose-500';
  return (
    <div>
      <div className="flex items-center justify-between mb-1">
        <span className="text-xs font-semibold text-slate-600 dark:text-slate-400">{label}</span>
        <span className="text-xs font-bold text-slate-800 dark:text-slate-200">{value}%</span>
      </div>
      <div className="h-2 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
        <div className={`h-full rounded-full ${color}`} style={{ width: `${Math.min(100, value)}%` }} />
      </div>
    </div>
  );
}

function Block({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="border border-slate-200 dark:border-slate-800 rounded-none p-4">
      <p className="text-[11px] font-extrabold uppercase tracking-wider text-indigo-600 dark:text-indigo-400 mb-2.5">{title}</p>
      {children}
    </div>
  );
}

function BulletList({ items }: { items: string[] }) {
  if (!items?.length) return <p className="text-xs text-slate-400">—</p>;
  return (
    <ul className="space-y-1.5">
      {items.map((s, i) => (
        <li key={i} className="text-xs font-medium text-slate-600 dark:text-slate-300 flex gap-2">
          <span className="w-1 h-1 rounded-full bg-indigo-500 mt-1.5 shrink-0" />
          {s}
        </li>
      ))}
    </ul>
  );
}

interface CandidateReportViewerProps {
  candidateId: number;
  onClose: () => void;
  onDownload: (candidateId: number, version?: number) => void;
  canGenerate: boolean;
  onGenerate: (candidateId: number) => void;
}

export default function CandidateReportViewer({
  candidateId, onClose, onDownload, canGenerate, onGenerate,
}: CandidateReportViewerProps) {
  const [data, setData] = useState<CandidateReportDetailData | null>(null);
  const [loading, setLoading] = useState(true);
  const [version, setVersion] = useState<number | ''>('');

  useEffect(() => {
    setLoading(true);
    const qs = version ? `?version=${version}` : '';
    (api.get(`/reports/candidate-reports/${candidateId}/${qs}`) as Promise<{ data: CandidateReportDetailData }>)
      .then((res) => setData(res.data))
      .catch((e) => {
        toast.error(e instanceof Error ? e.message : 'Failed to load report');
        onClose();
      })
      .finally(() => setLoading(false));
  }, [candidateId, version, onClose]);

  const report = data?.report ?? null;
  const p = report?.payload;

  return (
    <div className="fixed inset-0 z-[100] flex items-start justify-center bg-slate-950/60 backdrop-blur-sm p-4 overflow-y-auto" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, y: 24 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.25 }}
        onClick={(e) => e.stopPropagation()}
        className="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-2xl w-full max-w-3xl my-6"
      >
        {/* Header */}
        <div className="flex items-center justify-between gap-3 px-5 py-4 border-b border-slate-200 dark:border-slate-800 bg-[#405189]">
          <div className="min-w-0">
            <p className="text-[10px] font-extrabold uppercase tracking-widest text-indigo-200">Candidate Evaluation Report</p>
            <h2 className="text-base font-bold text-white truncate">
              {data?.candidate.name || 'Loading...'}
              {data?.candidate.code && <span className="ml-2 text-[11px] font-semibold text-indigo-200">{data.candidate.code}</span>}
            </h2>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            {(data?.versions?.length ?? 0) > 0 && (
              <select
                value={version || data?.report?.version || ''}
                onChange={(e) => setVersion(Number(e.target.value))}
                className="px-2 py-1.5 rounded-none text-xs font-bold bg-white/10 border border-white/20 text-white focus:outline-none cursor-pointer"
              >
                {data!.versions.map((v) => (
                  <option key={v.version} value={v.version} className="text-slate-900">v{v.version} — {v.generated_at}</option>
                ))}
              </select>
            )}
            {report && (
              <button
                onClick={() => onDownload(candidateId, report.version)}
                className="px-3 py-1.5 rounded-none text-xs font-bold bg-white text-[#405189] hover:bg-indigo-50 transition cursor-pointer"
              >
                <i className="fa-solid fa-download mr-1.5" />
                PDF
              </button>
            )}
            <button
              onClick={onClose}
              className="w-8 h-8 flex items-center justify-center text-white/80 hover:text-white hover:bg-white/10 transition cursor-pointer"
              title="Close"
            >
              <i className="fa-solid fa-xmark" />
            </button>
          </div>
        </div>

        {/* Body */}
        <div className="p-5 space-y-4 max-h-[75vh] overflow-y-auto custom-scrollbar">
          {loading ? (
            <div className="space-y-4">
              {[...Array(4)].map((_, i) => (
                <div key={i} className="h-28 bg-slate-100 dark:bg-slate-800 rounded-none animate-pulse" />
              ))}
            </div>
          ) : !report || !p ? (
            <div className="text-center py-12">
              <i className="fa-solid fa-file-circle-xmark text-4xl text-slate-300 dark:text-slate-700 mb-3" />
              <p className="text-sm font-semibold text-slate-600 dark:text-slate-300">No report generated for this candidate yet.</p>
              <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">Generate one to see the full AI evaluation and PDF.</p>
              {canGenerate && (
                <button
                  onClick={() => onGenerate(candidateId)}
                  className="mt-5 bg-[#405189] hover:bg-[#364574] text-white px-4 py-2 rounded-none text-sm font-medium transition cursor-pointer"
                >
                  <i className="fa-solid fa-wand-magic-sparkles mr-2" />
                  Generate Report
                </button>
              )}
            </div>
          ) : (
            <>
              {/* Classification + meta */}
              <div className="flex items-center justify-between gap-3 flex-wrap">
                <span className={`inline-flex px-3 py-1 rounded-full text-xs font-extrabold ${CLASSIFICATION_BADGES[p.classification.value] || ''}`}>
                  {p.classification.value}
                </span>
                <p className="text-[11px] font-semibold text-slate-400 dark:text-slate-500">
                  v{report.version} · {report.generated_at}{report.generated_by ? ` · by ${report.generated_by}` : ''}
                </p>
              </div>

              <Block title="Profile">
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-x-4 gap-y-2.5 text-xs">
                  {[
                    ['Email', p.candidate.email],
                    ['Phone', p.candidate.phone],
                    ['Location', p.candidate.location],
                    ['Experience', p.candidate.experience_years ? `${p.candidate.experience_years} yrs` : 'Fresher'],
                    ['Position', p.job.title],
                    ['Client', p.job.client],
                    ['Stage', p.job.stage],
                    ['Resume', p.candidate.resume_file],
                    ['Status', p.candidate.status],
                  ].map(([k, v]) => (
                    <div key={k as string}>
                      <p className="text-[10px] font-extrabold uppercase tracking-wide text-slate-400 dark:text-slate-500">{k}</p>
                      <p className="font-semibold text-slate-700 dark:text-slate-200 truncate" title={(v as string) || ''}>{v || '—'}</p>
                    </div>
                  ))}
                </div>
                {p.candidate.skills.length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mt-3">
                    {p.candidate.skills.map((s) => (
                      <span key={s} className="px-2 py-0.5 rounded-full text-[10px] font-bold bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300">{s}</span>
                    ))}
                  </div>
                )}
              </Block>

              <Block title="Resume Summary">
                <p className="text-xs font-medium text-slate-600 dark:text-slate-300 mb-3">{p.summary.professional_summary}</p>
                <p className="text-[10px] font-extrabold uppercase tracking-wide text-slate-400 mb-1.5">Key Strengths</p>
                <BulletList items={p.summary.key_strengths} />
                {p.summary.career_highlights.length > 0 && (
                  <>
                    <p className="text-[10px] font-extrabold uppercase tracking-wide text-slate-400 mt-3 mb-1.5">Career Highlights</p>
                    <BulletList items={p.summary.career_highlights} />
                  </>
                )}
              </Block>

              <Block title="Interview">
                {p.interview ? (
                  <div className="space-y-2">
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
                      {[
                        ['Interviewer', p.interview.interviewer],
                        ['Date', p.interview.date],
                        ['Result', p.interview.result],
                        ['Language', p.interview.language],
                      ].map(([k, v]) => (
                        <div key={k as string}>
                          <p className="text-[10px] font-extrabold uppercase tracking-wide text-slate-400">{k}</p>
                          <p className="font-semibold text-slate-700 dark:text-slate-200">{v || '—'}</p>
                        </div>
                      ))}
                    </div>
                    {p.interview.notes && (
                      <p className="text-xs font-medium text-slate-600 dark:text-slate-300 border-l-2 border-indigo-300 dark:border-indigo-800 pl-3">{p.interview.notes}</p>
                    )}
                    {!p.interview.transcript && (
                      <p className="text-xs italic text-slate-400 dark:text-slate-500">No interview transcript available.</p>
                    )}
                  </div>
                ) : (
                  <p className="text-xs italic text-slate-400 dark:text-slate-500">No interview transcript available.</p>
                )}
              </Block>

              <Block title="Scores">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3">
                  <ScoreRow label="Communication" value={p.scores.communication} />
                  <ScoreRow label="Technical" value={p.scores.technical} />
                  <ScoreRow label="Problem Solving" value={p.scores.problem_solving} />
                  <ScoreRow label="Experience Match" value={p.scores.experience_match} />
                  <ScoreRow label="Skill Match" value={p.scores.skill_match} />
                  <ScoreRow label="Overall Score" value={p.scores.overall} />
                </div>
                <p className="text-[11px] font-semibold text-slate-400 dark:text-slate-500 mt-3">
                  Confidence {p.classification.confidence}% · Skill matching {p.classification.matching_percentage}%
                </p>
              </Block>

              <Block title="AI Recommendation">
                <p className="text-xs font-bold text-slate-700 dark:text-slate-200 mb-3">{p.recommendation.summary}</p>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <p className="text-[10px] font-extrabold uppercase tracking-wide text-emerald-600 dark:text-emerald-400 mb-1.5">Strengths</p>
                    <BulletList items={p.recommendation.strengths} />
                  </div>
                  <div>
                    <p className="text-[10px] font-extrabold uppercase tracking-wide text-rose-600 dark:text-rose-400 mb-1.5">Weaknesses</p>
                    <BulletList items={p.recommendation.weaknesses} />
                  </div>
                  <div>
                    <p className="text-[10px] font-extrabold uppercase tracking-wide text-amber-600 dark:text-amber-400 mb-1.5">Skill Gaps</p>
                    <BulletList items={p.recommendation.skill_gaps} />
                  </div>
                  <div>
                    <p className="text-[10px] font-extrabold uppercase tracking-wide text-indigo-600 dark:text-indigo-400 mb-1.5">Suggested Interview Areas</p>
                    <BulletList items={p.recommendation.interview_areas} />
                  </div>
                </div>
                <p className="text-xs font-semibold text-slate-600 dark:text-slate-300 mt-3">
                  Suggested next stage:{' '}
                  <span className="inline-flex px-2 py-0.5 rounded-full text-[10px] font-extrabold bg-indigo-50 text-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-300">
                    {p.recommendation.next_stage}
                  </span>
                </p>
              </Block>

              <p className="text-[10px] italic text-slate-400 dark:text-slate-500 text-center pb-1">
                Generated by ATS System · {p.meta.generated_at} · {p.meta.system_version} — confidential, for internal recruitment use only.
              </p>
            </>
          )}
        </div>
      </motion.div>
    </div>
  );
}
