"use client";

import { useState } from "react";
import { submitStandardApplication } from "@/app/actions/applicationAdvanced";
import { generateCoverLetterDraft } from "@/app/actions/aiAssistant";
import { CheckCircle2, ChevronRight, ChevronLeft, Loader2, Sparkles, FileText, Upload } from "lucide-react";
import { toast } from "react-hot-toast";

interface StandardApplicationFormProps {
    jobId: string;
    jobTitle: string;
    companyName: string;
    candidateId: string;
    candidateProfile: any;
    onSuccess?: () => void;
    onCancel?: () => void;
}

const steps = [
    { id: "contact", title: "Contact Info" },
    { id: "resume", title: "Resume & Cover Letter" },
    { id: "questions", title: "Questionnaire" },
    { id: "review", title: "Review" }
];

export function StandardApplicationForm({
    jobId,
    jobTitle,
    companyName,
    candidateId,
    candidateProfile,
    onSuccess,
    onCancel
}: StandardApplicationFormProps) {
    const [currentStep, setCurrentStep] = useState(0);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isGenerating, setIsGenerating] = useState(false);

    // Form State
    const [formData, setFormData] = useState({
        phone: candidateProfile?.phone || "",
        cvLink: candidateProfile?.resume_url || "",
        coverLetter: "",
        yearsOfExperience: "",
        q1: "",
        q2: ""
    });

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const handleGenerateCoverLetter = async () => {
        setIsGenerating(true);
        try {
            const prompt = `Write a cover letter for the role of ${jobTitle} at ${companyName}. 
      My background includes: ${candidateProfile?.headline || 'Professional experience'}. 
      Highlight my skills in: ${candidateProfile?.skills?.join(", ") || 'General soft skills'}.`;

            const result = await generateCoverLetterDraft(prompt);
            if (result.success && result.draft) {
                setFormData(prev => ({ ...prev, coverLetter: result.draft! }));
                toast.success("Cover letter generated!");
            } else {
                toast.error("Failed to generate cover letter.");
            }
        } catch (error) {
            toast.error("An error occurred during generation.");
        } finally {
            setIsGenerating(false);
        }
    };

    const handleSubmit = async () => {
        setIsSubmitting(true);
        try {
            const submitData = new FormData();
            submitData.append("jobId", jobId);
            submitData.append("candidateId", candidateId);
            submitData.append("cvLink", formData.cvLink);
            submitData.append("coverLetter", formData.coverLetter);
            submitData.append("yearsOfExperience", formData.yearsOfExperience);

            const answers = {
                "Why are you interested in this role?": formData.q1,
                "What is your greatest strength?": formData.q2
            };
            submitData.append("answers", JSON.stringify(answers));

            const result = await submitStandardApplication(submitData);

            if (result.success) {
                toast.success("Application submitted successfully!");
                if (onSuccess) onSuccess();
            } else {
                toast.error(result.error || "Failed to submit application");
            }
        } catch (error) {
            toast.error("An unexpected error occurred.");
        } finally {
            setIsSubmitting(false);
        }
    };

    const nextStep = () => setCurrentStep(prev => Math.min(prev + 1, steps.length - 1));
    const prevStep = () => setCurrentStep(prev => Math.max(prev - 1, 0));

    // Common input styling
    const inputClasses = "w-full rounded-lg border border-slate-300 px-4 py-2.5 outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all";

    return (
        <div className="bg-white rounded-2xl shadow-xl overflow-hidden max-w-2xl w-full border border-slate-100">
            {/* Header / Stepper Wrapper */}
            <div className="bg-slate-50 border-b border-slate-100 p-6">
                <div>
                    <h2 className="text-xl font-bold text-slate-900">Apply to {companyName}</h2>
                    <p className="text-sm text-slate-500 mt-1">Role: <span className="font-semibold text-slate-700">{jobTitle}</span></p>
                </div>

                {/* Stepper logic */}
                <div className="flex items-center justify-between mt-8 relative">
                    <div className="absolute left-0 top-1/2 w-full h-0.5 bg-slate-200 -z-10 -translate-y-1/2 rounded-full" />
                    <div
                        className="absolute left-0 top-1/2 h-0.5 bg-primary -z-10 -translate-y-1/2 rounded-full transition-all duration-300"
                        style={{ width: `${(currentStep / (steps.length - 1)) * 100}%` }}
                    />

                    {steps.map((step, idx) => (
                        <div key={step.id} className="flex flex-col items-center gap-2 bg-slate-50 px-2 relative z-10">
                            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold transition-colors ${idx < currentStep ? 'bg-primary text-white' :
                                idx === currentStep ? 'bg-primary text-white ring-4 ring-primary/20' :
                                    'bg-white border-2 border-slate-300 text-slate-400'
                                }`}>
                                {idx < currentStep ? <CheckCircle2 className="h-5 w-5" /> : idx + 1}
                            </div>
                            <span className={`text-xs font-semibold hidden sm:block ${idx <= currentStep ? 'text-slate-900' : 'text-slate-400'}`}>
                                {step.title}
                            </span>
                        </div>
                    ))}
                </div>
            </div>

            {/* Form Content */}
            <div className="p-6 md:p-8 min-h-[400px]">
                {/* Step 1: Contact Info */}
                <div className={currentStep === 0 ? "block" : "hidden"}>
                    <h3 className="text-lg font-bold text-slate-900 mb-6">Contact Information</h3>
                    <div className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-1.5">First Name</label>
                                <input type="text" value={candidateProfile?.first_name || ""} disabled className="w-full rounded-lg border border-slate-200 bg-slate-50 px-4 py-2.5 text-slate-500 cursor-not-allowed" />
                            </div>
                            <div>
                                <label className="block text-sm font-semibold text-slate-700 mb-1.5">Last Name</label>
                                <input type="text" value={candidateProfile?.last_name || ""} disabled className="w-full rounded-lg border border-slate-200 bg-slate-50 px-4 py-2.5 text-slate-500 cursor-not-allowed" />
                            </div>
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Email Address</label>
                            <input type="email" value={candidateProfile?.user?.email || ""} disabled className="w-full rounded-lg border border-slate-200 bg-slate-50 px-4 py-2.5 text-slate-500 cursor-not-allowed" />
                        </div>
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Phone Number</label>
                            <input
                                type="tel"
                                name="phone"
                                value={formData.phone}
                                onChange={handleChange}
                                placeholder="+1 (555) 000-0000"
                                className={inputClasses}
                            />
                        </div>
                        <p className="text-xs text-slate-500 mt-2 flex items-center gap-1.5">
                            * Profile details are automatically synced from your account setup.
                        </p>
                    </div>
                </div>

                {/* Step 2: Resume & Cover Letter */}
                <div className={currentStep === 1 ? "block" : "hidden"}>
                    <h3 className="text-lg font-bold text-slate-900 mb-6">Resume & Cover Letter</h3>
                    <div className="space-y-6">
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Resume / CV Link</label>
                            <p className="text-xs text-slate-500 mb-3">Provide a link to your hosted resume (e.g. Google Drive, Dropbox, Notion, Personal Website).</p>
                            <div className="relative">
                                <FileText className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 h-5 w-5" />
                                <input
                                    type="url"
                                    name="cvLink"
                                    value={formData.cvLink}
                                    onChange={handleChange}
                                    placeholder="https://"
                                    className={`${inputClasses} pl-10`}
                                />
                            </div>
                        </div>

                        <div>
                            <div className="flex items-center justify-between mb-1.5">
                                <label className="block text-sm font-semibold text-slate-700">Cover Letter</label>
                                <button
                                    onClick={handleGenerateCoverLetter}
                                    disabled={isGenerating}
                                    className="text-xs font-bold text-primary hover:text-blue-700 flex items-center gap-1 transition-colors disabled:opacity-50"
                                    type="button"
                                >
                                    {isGenerating ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Sparkles className="h-3.5 w-3.5" />}
                                    {isGenerating ? "Drafting..." : "Auto-Draft with AI"}
                                </button>
                            </div>
                            <textarea
                                name="coverLetter"
                                value={formData.coverLetter}
                                onChange={handleChange}
                                rows={6}
                                placeholder="Write your cover letter here or use the AI to generate a draft..."
                                className={`${inputClasses} resize-none`}
                            />
                        </div>
                    </div>
                </div>

                {/* Step 3: Questionnaire */}
                <div className={currentStep === 2 ? "block" : "hidden"}>
                    <h3 className="text-lg font-bold text-slate-900 mb-6">Employer Questions</h3>
                    <div className="space-y-6">
                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Years of Professional Experience</label>
                            <input
                                type="number"
                                name="yearsOfExperience"
                                value={formData.yearsOfExperience}
                                onChange={handleChange}
                                min="0"
                                placeholder="e.g. 5"
                                className={inputClasses}
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">Why are you interested in this role?</label>
                            <textarea
                                name="q1"
                                value={formData.q1}
                                onChange={handleChange}
                                rows={3}
                                className={inputClasses}
                            />
                        </div>

                        <div>
                            <label className="block text-sm font-semibold text-slate-700 mb-1.5">What is your greatest strength?</label>
                            <textarea
                                name="q2"
                                value={formData.q2}
                                onChange={handleChange}
                                rows={3}
                                className={inputClasses}
                            />
                        </div>
                    </div>
                </div>

                {/* Step 4: Review */}
                <div className={currentStep === 3 ? "block" : "hidden"}>
                    <h3 className="text-lg font-bold text-slate-900 mb-6">Review your Application</h3>

                    <div className="bg-slate-50 border border-slate-200 rounded-xl p-5 space-y-4 text-sm">
                        <div className="grid grid-cols-3 gap-4 border-b border-slate-200 pb-4">
                            <span className="text-slate-500 font-medium">Name</span>
                            <span className="col-span-2 text-slate-900 font-semibold">{candidateProfile?.first_name} {candidateProfile?.last_name}</span>
                        </div>
                        <div className="grid grid-cols-3 gap-4 border-b border-slate-200 pb-4">
                            <span className="text-slate-500 font-medium">Email</span>
                            <span className="col-span-2 text-slate-900 font-semibold">{candidateProfile?.user?.email}</span>
                        </div>
                        <div className="grid grid-cols-3 gap-4 border-b border-slate-200 pb-4">
                            <span className="text-slate-500 font-medium">Resume Link</span>
                            <span className="col-span-2 text-slate-900 font-medium break-words overflow-hidden text-ellipsis">
                                {formData.cvLink || <span className="text-slate-400 italic">Not provided</span>}
                            </span>
                        </div>
                        <div className="grid grid-cols-3 gap-4">
                            <span className="text-slate-500 font-medium">Cover Letter</span>
                            <span className="col-span-2 text-slate-700 whitespace-pre-wrap max-h-32 overflow-y-auto pr-2 custom-scrollbar">
                                {formData.coverLetter ? formData.coverLetter : <span className="text-slate-400 italic">None included</span>}
                            </span>
                        </div>
                    </div>

                    <p className="text-xs text-slate-500 mt-6 text-center">
                        By submitting this application, you agree to share your profile information with the employer.
                    </p>
                </div>
            </div>

            {/* Footer / Controls */}
            <div className="bg-slate-50 border-t border-slate-100 p-6 flex items-center justify-between">
                {currentStep > 0 ? (
                    <button
                        onClick={prevStep}
                        className="px-5 py-2.5 rounded-lg text-sm font-bold text-slate-600 hover:bg-slate-200 transition-colors flex items-center gap-2"
                        type="button"
                    >
                        <ChevronLeft className="h-4 w-4" /> Back
                    </button>
                ) : (
                    <button
                        onClick={onCancel}
                        className="px-5 py-2.5 rounded-lg text-sm font-bold text-slate-500 hover:bg-slate-200 transition-colors"
                        type="button"
                    >
                        Cancel
                    </button>
                )}

                {currentStep < steps.length - 1 ? (
                    <button
                        onClick={nextStep}
                        className="px-6 py-2.5 rounded-lg text-sm font-bold bg-slate-900 text-white hover:bg-slate-800 transition-colors shadow-sm flex items-center gap-2"
                        type="button"
                    >
                        Continue <ChevronRight className="h-4 w-4" />
                    </button>
                ) : (
                    <button
                        onClick={handleSubmit}
                        disabled={isSubmitting}
                        className="px-8 py-2.5 rounded-lg text-sm bg-primary text-white hover:bg-blue-700 transition-colors font-bold flex items-center gap-2 shadow-sm disabled:opacity-50"
                        type="button"
                    >
                        {isSubmitting && <Loader2 className="h-4 w-4 animate-spin" />}
                        {isSubmitting ? "Submitting..." : "Submit Application"}
                    </button>
                )}
            </div>
        </div>
    );
}
