"use client";

import { useState, useTransition } from "react";
import { completeOnboarding } from "@/app/actions/auth";
import { CheckCircle, MapPin, Briefcase, GraduationCap, ArrowRight, ArrowLeft, Loader2, X } from "lucide-react";

const STEPS = [
    { id: 1, label: "Profile", icon: "👤" },
    { id: 2, label: "Skills", icon: "⚡" },
    { id: 3, label: "Preferences", icon: "🎯" },
];

const JOB_TYPE_OPTIONS = ["Full-time", "Part-time", "Contract", "Remote", "Internship"];
const SKILL_SUGGESTIONS = ["JavaScript", "Python", "React", "Node.js", "TypeScript", "SQL", "AWS", "Product Management", "UI/UX Design", "Data Analysis", "Project Management", "Marketing"];

interface Props { userId: string }

export default function CandidateOnboardingWizard({ userId }: Props) {
    const [step, setStep] = useState(1);
    const [isPending, startTransition] = useTransition();

    // Step 1 — Profile
    const [headline, setHeadline] = useState("");
    const [location, setLocation] = useState("");
    const [bio, setBio] = useState("");

    // Step 2 — Skills
    const [skills, setSkills] = useState<string[]>([]);
    const [skillInput, setSkillInput] = useState("");

    // Step 3 — Preferences
    const [jobTypes, setJobTypes] = useState<string[]>([]);
    const [salary, setSalary] = useState("");

    const addSkill = (s: string) => {
        const val = s.trim();
        if (val && !skills.includes(val) && skills.length < 15) {
            setSkills([...skills, val]);
            setSkillInput("");
        }
    };

    const removeSkill = (s: string) => setSkills(skills.filter((x) => x !== s));

    const toggleJobType = (t: string) =>
        setJobTypes((prev) => prev.includes(t) ? prev.filter((x) => x !== t) : [...prev, t]);

    const handleFinish = () => {
        const fd = new FormData();
        fd.append("userId", userId);
        fd.append("role", "candidate");
        fd.append("headline", headline);
        fd.append("location", location);
        fd.append("bio", bio);
        fd.append("skills", JSON.stringify(skills));
        fd.append("jobTypes", JSON.stringify(jobTypes));
        fd.append("salary", salary);
        startTransition(() => { completeOnboarding(fd); });
    };

    const progress = ((step - 1) / (STEPS.length - 1)) * 100;

    return (
        <div className="px-4 pb-16 pt-4 max-w-2xl mx-auto">
            {/* Progress Header */}
            <div className="mb-10">
                <div className="flex items-center justify-between mb-4">
                    {STEPS.map((s, i) => (
                        <div key={s.id} className="flex items-center">
                            <div className={`flex items-center gap-2 ${i < STEPS.length - 1 ? "" : ""}`}>
                                <div className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold transition-all duration-300 ${
                                    step > s.id
                                        ? "bg-emerald-500 text-white shadow-lg shadow-emerald-500/30"
                                        : step === s.id
                                        ? "bg-[#0070f3] text-white shadow-lg shadow-[#0070f3]/30"
                                        : "bg-white/10 text-slate-500"
                                }`}>
                                    {step > s.id ? <CheckCircle className="w-5 h-5" /> : s.icon}
                                </div>
                                <span className={`text-sm font-medium hidden sm:block ${step === s.id ? "text-white" : "text-slate-500"}`}>
                                    {s.label}
                                </span>
                            </div>
                            {i < STEPS.length - 1 && (
                                <div className="w-16 sm:w-24 h-px mx-3 bg-white/10 relative">
                                    <div
                                        className="absolute inset-y-0 left-0 bg-[#0070f3] transition-all duration-500"
                                        style={{ width: step > s.id ? "100%" : "0%" }}
                                    />
                                </div>
                            )}
                        </div>
                    ))}
                </div>
                <div className="text-center">
                    <p className="text-slate-400 text-sm">Step {step} of {STEPS.length}</p>
                </div>
            </div>

            {/* Step Cards */}
            <div className="bg-white/5 backdrop-blur-xl border border-white/10 rounded-2xl shadow-2xl p-8">

                {/* STEP 1 — Profile */}
                {step === 1 && (
                    <div className="space-y-6">
                        <div>
                            <h2 className="text-2xl font-bold text-white mb-1">Tell us about yourself</h2>
                            <p className="text-slate-400 text-sm">Help employers discover you with a strong profile</p>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-1.5">
                                Professional Headline
                            </label>
                            <input
                                type="text"
                                value={headline}
                                onChange={(e) => setHeadline(e.target.value)}
                                className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                                placeholder="e.g. Senior Frontend Engineer · React · TypeScript"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-1.5">
                                <MapPin className="w-4 h-4 inline mr-1" />
                                Location
                            </label>
                            <input
                                type="text"
                                value={location}
                                onChange={(e) => setLocation(e.target.value)}
                                className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                                placeholder="e.g. Lagos, Nigeria · Open to Remote"
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-1.5">
                                Bio <span className="text-slate-600 font-normal">(optional)</span>
                            </label>
                            <textarea
                                value={bio}
                                onChange={(e) => setBio(e.target.value)}
                                rows={4}
                                maxLength={500}
                                className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm resize-none"
                                placeholder="A brief introduction about yourself, your experience and what you're looking for..."
                            />
                            <p className="text-xs text-slate-600 mt-1 text-right">{bio.length}/500</p>
                        </div>
                    </div>
                )}

                {/* STEP 2 — Skills */}
                {step === 2 && (
                    <div className="space-y-6">
                        <div>
                            <h2 className="text-2xl font-bold text-white mb-1">Your skills</h2>
                            <p className="text-slate-400 text-sm">Add up to 15 skills that best represent your expertise</p>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-1.5">Add a skill</label>
                            <div className="flex gap-2">
                                <input
                                    type="text"
                                    value={skillInput}
                                    onChange={(e) => setSkillInput(e.target.value)}
                                    onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addSkill(skillInput); } }}
                                    className="flex-1 rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                                    placeholder="Type a skill and press Enter"
                                />
                                <button
                                    type="button"
                                    onClick={() => addSkill(skillInput)}
                                    className="px-4 py-3 rounded-xl bg-[#0070f3]/20 border border-[#0070f3]/30 text-[#0070f3] hover:bg-[#0070f3]/30 transition-colors text-sm font-medium"
                                >
                                    Add
                                </button>
                            </div>
                        </div>

                        {/* Suggestions */}
                        <div>
                            <p className="text-xs text-slate-500 mb-2 uppercase tracking-wider">Popular skills</p>
                            <div className="flex flex-wrap gap-2">
                                {SKILL_SUGGESTIONS.filter((s) => !skills.includes(s)).map((s) => (
                                    <button
                                        key={s}
                                        type="button"
                                        onClick={() => addSkill(s)}
                                        className="px-3 py-1.5 rounded-lg bg-white/5 border border-white/10 text-slate-300 text-xs hover:border-[#0070f3]/50 hover:text-white hover:bg-[#0070f3]/10 transition-all"
                                    >
                                        + {s}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Selected Skills */}
                        {skills.length > 0 && (
                            <div>
                                <p className="text-xs text-slate-500 mb-2 uppercase tracking-wider">Your skills ({skills.length})</p>
                                <div className="flex flex-wrap gap-2">
                                    {skills.map((s) => (
                                        <span key={s} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#0070f3]/15 border border-[#0070f3]/30 text-[#60a5fa] text-sm font-medium">
                                            {s}
                                            <button type="button" onClick={() => removeSkill(s)} className="hover:text-red-400 transition-colors">
                                                <X className="w-3.5 h-3.5" />
                                            </button>
                                        </span>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* STEP 3 — Job Preferences */}
                {step === 3 && (
                    <div className="space-y-6">
                        <div>
                            <h2 className="text-2xl font-bold text-white mb-1">Job preferences</h2>
                            <p className="text-slate-400 text-sm">Tell us what you&apos;re looking for in your next role</p>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-3">
                                <Briefcase className="w-4 h-4 inline mr-1" />
                                Employment type
                            </label>
                            <div className="flex flex-wrap gap-2">
                                {JOB_TYPE_OPTIONS.map((t) => (
                                    <button
                                        key={t}
                                        type="button"
                                        onClick={() => toggleJobType(t)}
                                        className={`px-4 py-2 rounded-xl text-sm font-medium border-2 transition-all duration-200 ${
                                            jobTypes.includes(t)
                                                ? "border-[#0070f3] bg-[#0070f3]/15 text-[#60a5fa]"
                                                : "border-white/10 bg-white/5 text-slate-400 hover:border-white/25 hover:text-slate-300"
                                        }`}
                                    >
                                        {jobTypes.includes(t) ? "✓ " : ""}{t}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-slate-300 mb-1.5">
                                Salary expectation <span className="text-slate-600 font-normal">(optional)</span>
                            </label>
                            <input
                                type="text"
                                value={salary}
                                onChange={(e) => setSalary(e.target.value)}
                                className="w-full rounded-xl bg-white/5 border border-white/10 px-4 py-3 text-white placeholder-slate-500 focus:border-[#0070f3]/60 focus:ring-2 focus:ring-[#0070f3]/20 outline-none transition-all text-sm"
                                placeholder="e.g. $80k–$120k / year"
                            />
                        </div>

                        {/* Completion preview */}
                        <div className="p-4 rounded-xl bg-emerald-500/10 border border-emerald-500/20">
                            <div className="flex items-center gap-3">
                                <CheckCircle className="w-6 h-6 text-emerald-400 flex-shrink-0" />
                                <div>
                                    <p className="text-sm font-semibold text-white">You&apos;re almost ready!</p>
                                    <p className="text-xs text-slate-400 mt-0.5">Your profile will be visible to employers. You can update everything later.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Navigation */}
                <div className="flex items-center justify-between mt-8 pt-6 border-t border-white/10">
                    <button
                        type="button"
                        onClick={() => setStep((s) => Math.max(1, s - 1))}
                        disabled={step === 1}
                        className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-slate-400 hover:text-white border border-white/10 hover:border-white/20 transition-all text-sm disabled:opacity-30 disabled:cursor-not-allowed"
                    >
                        <ArrowLeft className="w-4 h-4" /> Back
                    </button>

                    {step < STEPS.length ? (
                        <button
                            type="button"
                            onClick={() => setStep((s) => s + 1)}
                            className="flex items-center gap-2 px-6 py-2.5 rounded-xl bg-[#0070f3] text-white font-semibold hover:bg-[#0060d3] shadow-lg shadow-[#0070f3]/30 transition-all text-sm group"
                        >
                            Continue <ArrowRight className="w-4 h-4 group-hover:translate-x-0.5 transition-transform" />
                        </button>
                    ) : (
                        <button
                            type="button"
                            onClick={handleFinish}
                            disabled={isPending}
                            className="flex items-center gap-2 px-6 py-2.5 rounded-xl bg-emerald-500 text-white font-semibold hover:bg-emerald-600 shadow-lg shadow-emerald-500/30 transition-all text-sm"
                        >
                            {isPending ? <Loader2 className="w-4 h-4 animate-spin" /> : <><CheckCircle className="w-4 h-4" /> Complete Setup</>}
                        </button>
                    )}
                </div>
            </div>
        </div>
    );
}
