"use client";

import { CheckCircle, XCircle, AlertCircle, Sparkles, MessageSquare } from "lucide-react";

interface OverviewTabProps {
    application: any;
    candidate: any;
    job: any;
    isEmployer: boolean;
}

function MatchBreakdownItem({ label, value, max = 100 }: { label: string; value: number; max?: number }) {
    const pct = Math.min((value / max) * 100, 100);
    const color = pct >= 85 ? "bg-emerald-500" : pct >= 70 ? "bg-blue-500" : pct >= 50 ? "bg-amber-500" : "bg-red-500";

    return (
        <div className="space-y-1.5">
            <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-slate-600">{label}</span>
                <span className="text-sm font-bold text-slate-900">{Math.round(value)}%</span>
            </div>
            <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                <div
                    className={`h-full rounded-full ${color} transition-all duration-700`}
                    style={{ width: `${pct}%` }}
                />
            </div>
        </div>
    );
}

export function OverviewTab({ application, candidate, job, isEmployer }: OverviewTabProps) {
    const profile = candidate?.profile;
    const skills = candidate?.skills?.map((s: any) => s.skill?.name || s.name || s).filter(Boolean) || [];
    const matchScore = application.match_score;

    // Simulated match breakdown (based on overall score) to avoid hydration mismatches
    const matchBreakdown = matchScore
        ? {
            skills: Math.min(100, matchScore + 5),
            experience: Math.min(100, Math.max(0, matchScore - 2)),
            education: Math.min(100, Math.max(0, matchScore - 5)),
            location: 100,
            salary: Math.min(100, matchScore + 2),
        }
        : null;

    // Parse screening question answers
    const answers = application.answers ? (typeof application.answers === 'string' ? JSON.parse(application.answers) : application.answers) : null;

    return (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
            {/* Main Content */}
            <div className="lg:col-span-2 space-y-8">
                {/* AI Match Analysis */}
                {isEmployer && matchScore && matchBreakdown && (
                    <section className="bg-gradient-to-br from-slate-50 to-blue-50/30 rounded-xl border border-slate-200/80 p-6">
                        <div className="flex items-center gap-2 mb-5">
                            <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center">
                                <Sparkles className="w-4 h-4 text-white" />
                            </div>
                            <h3 className="text-lg font-bold text-slate-900">AI Match Analysis</h3>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <MatchBreakdownItem label="Skills Match" value={matchBreakdown.skills} />
                            <MatchBreakdownItem label="Experience Level" value={matchBreakdown.experience} />
                            <MatchBreakdownItem label="Education" value={matchBreakdown.education} />
                            <MatchBreakdownItem label="Location" value={matchBreakdown.location} />
                            <MatchBreakdownItem label="Salary Fit" value={matchBreakdown.salary} />
                        </div>

                        {/* Quick Assessment */}
                        <div className="mt-5 p-4 bg-white rounded-xl border border-slate-100">
                            <p className="text-sm text-slate-700 leading-relaxed">
                                <strong>Assessment:</strong>{" "}
                                {matchScore >= 85
                                    ? `This candidate is an excellent match for the ${job?.title} position. They possess strong relevant skills and experience.`
                                    : matchScore >= 70
                                        ? `This candidate is a strong fit. They meet most requirements with some areas for growth.`
                                        : matchScore >= 50
                                            ? `This candidate shows moderate alignment. Consider reviewing their specific qualifications.`
                                            : `This candidate may not be the best fit. Consider other applicants first.`}
                            </p>
                        </div>
                    </section>
                )}

                {/* Cover Letter */}
                {application.cover_letter && (
                    <section>
                        <h3 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
                            <MessageSquare className="w-5 h-5 text-primary" />
                            Cover Letter
                        </h3>
                        <div className="p-6 bg-slate-50 rounded-xl border border-slate-100">
                            <p className="text-sm text-slate-700 whitespace-pre-line leading-relaxed">
                                {application.cover_letter}
                            </p>

                            {/* Cover letter quality indicators */}
                            {isEmployer && (
                                <div className="mt-4 pt-4 border-t border-slate-200 flex flex-wrap gap-2">
                                    {application.cover_letter.length > 200 && (
                                        <span className="text-xs font-medium text-emerald-700 bg-emerald-50 px-2 py-1 rounded-md flex items-center gap-1">
                                            <CheckCircle className="w-3 h-3" /> Detailed
                                        </span>
                                    )}
                                    {application.cover_letter.toLowerCase().includes(job?.company?.toLowerCase() || '') && (
                                        <span className="text-xs font-medium text-emerald-700 bg-emerald-50 px-2 py-1 rounded-md flex items-center gap-1">
                                            <CheckCircle className="w-3 h-3" /> Personalized
                                        </span>
                                    )}
                                    {application.cover_letter.toLowerCase().includes(job?.title?.toLowerCase() || '') && (
                                        <span className="text-xs font-medium text-emerald-700 bg-emerald-50 px-2 py-1 rounded-md flex items-center gap-1">
                                            <CheckCircle className="w-3 h-3" /> Role-specific
                                        </span>
                                    )}
                                </div>
                            )}
                        </div>
                    </section>
                )}

                {/* Screening Question Answers */}
                {answers && typeof answers === 'object' && Object.keys(answers).length > 0 && (
                    <section>
                        <h3 className="text-lg font-bold text-slate-900 mb-4">Screening Questions</h3>
                        <div className="space-y-4">
                            {Object.entries(answers).map(([questionId, answer], idx) => (
                                <div key={questionId} className="p-4 bg-slate-50 rounded-xl border border-slate-100">
                                    <p className="text-xs font-bold text-slate-500 uppercase tracking-wide mb-2">
                                        Question {idx + 1}
                                    </p>
                                    <p className="text-sm text-slate-700">{String(answer)}</p>
                                </div>
                            ))}
                        </div>
                    </section>
                )}

                {/* Experience */}
                {application.years_of_experience && (
                    <section>
                        <h3 className="text-lg font-bold text-slate-900 mb-4">Experience</h3>
                        <div className="p-4 bg-slate-50 rounded-xl border border-slate-100">
                            <p className="text-sm text-slate-700">
                                <strong>{application.years_of_experience} years</strong> of professional experience
                            </p>
                        </div>
                    </section>
                )}
            </div>

            {/* Sidebar */}
            <div className="space-y-6">
                {/* Skills */}
                <div className="p-5 bg-slate-50 rounded-xl border border-slate-100">
                    <h3 className="text-sm font-bold text-slate-900 mb-3 uppercase tracking-wider">
                        Skills
                    </h3>
                    <div className="flex flex-wrap gap-2">
                        {skills.length > 0 ? (
                            skills.map((skill: string, i: number) => (
                                <span
                                    key={i}
                                    className="px-2.5 py-1 text-xs font-semibold bg-white border border-slate-200 text-slate-700 rounded-lg"
                                >
                                    {skill}
                                </span>
                            ))
                        ) : (
                            <span className="text-sm text-slate-400">No skills listed</span>
                        )}
                    </div>
                </div>

                {/* Resume & Links */}
                {(application.resume_url || application.cv_link) && (
                    <div className="p-5 bg-blue-50/50 rounded-xl border border-blue-100">
                        <h3 className="text-sm font-bold text-blue-900 mb-3">Resume & Links</h3>
                        <div className="space-y-2">
                            {application.resume_url && (
                                <a
                                    href={application.resume_url}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="flex items-center justify-between w-full p-3 bg-white border border-blue-200 rounded-lg hover:bg-blue-50 transition-colors text-sm font-medium text-slate-700"
                                >
                                    📄 Download Resume
                                </a>
                            )}
                            {application.cv_link && (
                                <a
                                    href={application.cv_link}
                                    target="_blank"
                                    rel="noreferrer"
                                    className="text-sm font-medium text-primary hover:underline block break-all"
                                >
                                    🔗 {application.cv_link}
                                </a>
                            )}
                        </div>
                    </div>
                )}

                {/* Tags */}
                {application.tags && application.tags.length > 0 && (
                    <div className="p-5 bg-violet-50/50 rounded-xl border border-violet-100">
                        <h3 className="text-sm font-bold text-violet-900 mb-3">Tags</h3>
                        <div className="flex flex-wrap gap-2">
                            {application.tags.map((tag: string, i: number) => (
                                <span key={i} className="px-2.5 py-1 text-xs font-semibold bg-white border border-violet-200 text-violet-700 rounded-lg">
                                    {tag}
                                </span>
                            ))}
                        </div>
                    </div>
                )}

                {/* Application Flags */}
                {isEmployer && (
                    <div className="p-5 bg-slate-50 rounded-xl border border-slate-100">
                        <h3 className="text-sm font-bold text-slate-900 mb-3">Quick Insights</h3>
                        <div className="space-y-2">
                            {matchScore && matchScore >= 85 && (
                                <div className="flex items-center gap-2 text-xs text-emerald-700 bg-emerald-50 p-2 rounded-lg">
                                    <CheckCircle className="w-3.5 h-3.5" />
                                    Top Applicant — High match score
                                </div>
                            )}
                            {application.cover_letter && (
                                <div className="flex items-center gap-2 text-xs text-blue-700 bg-blue-50 p-2 rounded-lg">
                                    <CheckCircle className="w-3.5 h-3.5" />
                                    Cover letter submitted
                                </div>
                            )}
                            {application.resume_url && (
                                <div className="flex items-center gap-2 text-xs text-blue-700 bg-blue-50 p-2 rounded-lg">
                                    <CheckCircle className="w-3.5 h-3.5" />
                                    Resume attached
                                </div>
                            )}
                            {!application.viewed_at && (
                                <div className="flex items-center gap-2 text-xs text-orange-700 bg-orange-50 p-2 rounded-lg">
                                    <AlertCircle className="w-3.5 h-3.5" />
                                    Not yet viewed
                                </div>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
