"use client";

import { useState } from "react";
import { Loader2, Upload, Send, User, Mail, Phone, Briefcase, FileText } from "lucide-react";
import { useRouter } from "next/navigation";
import { applyToJobAction } from "@/app/actions/applicationActions";

interface ApplicationFormProps {
    jobId: string;
    jobTitle: string;
    companyName: string;
    user?: {
        id: string;
        name: string;
        email: string;
        phone?: string;
        cvLink?: string;
        bio?: string;
    };
}

export function ApplicationForm({ jobId, jobTitle, companyName, user }: ApplicationFormProps) {
    const router = useRouter();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    async function handleSubmit(formData: FormData) {
        setLoading(true);
        setError(null);
        try {
            const result = await applyToJobAction(formData as FormData);

            if (result.success) {
                // Show success feedback before redirecting or rely on redirect
                // Since this is a client component, let's redirect
                router.push("/dashboard?role=candidate");
                router.refresh();
            } else {
                setError(result.error || "Failed to submit application.");
            }
        } catch (error) {
            console.error(error);
            setError("Something went wrong. Please try again.");
        } finally {
            setLoading(false);
        }
    }

    return (
        <div className="mx-auto max-w-2xl rounded-2xl border border-slate-100 bg-white p-8 shadow-sm">
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-slate-900">Apply for {jobTitle}</h1>
                <p className="text-slate-500">at {companyName}</p>
            </div>

            {error && (
                <div className="mb-6 p-4 rounded-xl bg-red-50 border border-red-100 text-red-600 text-sm font-medium flex items-center gap-2">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="w-5 h-5">
                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                    </svg>
                    {error}
                </div>
            )}

            <form action={handleSubmit} className="space-y-6">
                <input type="hidden" name="jobId" value={jobId} />
                <input type="hidden" name="candidateId" value={user?.id || ""} />

                {/* Personal Info */}
                <div className="grid gap-6 md:grid-cols-2">
                    <div className="space-y-2">
                        <label className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                            <User className="h-4 w-4 text-slate-400" /> Full Name
                        </label>
                        <input
                            type="text"
                            name="name"
                            required
                            defaultValue={user?.name}
                            placeholder="e.g. Alex Johnson"
                            className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                        />
                    </div>
                    <div className="space-y-2">
                        <label className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                            <Mail className="h-4 w-4 text-slate-400" /> Email
                        </label>
                        <input
                            type="email"
                            name="email"
                            required
                            defaultValue={user?.email}
                            placeholder="alex@example.com"
                            className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                        />
                    </div>
                </div>

                <div className="grid gap-6 md:grid-cols-2">
                    <div className="space-y-2">
                        <label className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                            <Phone className="h-4 w-4 text-slate-400" /> Phone Number
                        </label>
                        <input
                            type="tel"
                            name="phone"
                            required
                            defaultValue={user?.phone}
                            placeholder="+1 (555) 000-0000"
                            className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                        />
                    </div>
                    <div className="space-y-2">
                        <label className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                            <Briefcase className="h-4 w-4 text-slate-400" /> Years of Experience
                        </label>
                        <input
                            type="number"
                            name="yearsOfExperience"
                            required
                            placeholder="e.g. 5"
                            className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                        />
                    </div>
                </div>

                {/* CV Link */}
                <div className="space-y-2">
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                        <FileText className="h-4 w-4 text-slate-400" /> CV / Resume Link
                    </label>
                    <input
                        type="url"
                        name="cvLink"
                        required
                        defaultValue={user?.cvLink}
                        placeholder="https://linkedin.com/in/alex..."
                        className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                    />
                    <p className="text-xs text-slate-500">Provide a link to your LinkedIn PDF, Portfolio, or Google Drive file.</p>
                </div>

                {/* Cover Letter */}
                <div className="space-y-2">
                    <label className="text-sm font-semibold text-slate-900">Cover Letter</label>
                    <textarea
                        name="coverLetter"
                        rows={6}
                        placeholder="Tell us why you're a great fit..."
                        className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                    />
                </div>

                <button
                    type="submit"
                    disabled={loading}
                    className="flex w-full items-center justify-center gap-2 rounded-xl bg-primary py-3.5 font-bold text-white transition-all hover:bg-blue-700 active:scale-[0.98] disabled:opacity-50"
                >
                    {loading ? <Loader2 className="h-5 w-5 animate-spin" /> : "Submit Application"}
                </button>
            </form>
        </div>
    );
}
