"use client";

import { useState } from "react";
import { Send, Plus, X, Loader2 } from "lucide-react";
import { createJobAction } from "@/app/actions/jobActions";

export function JobPostForm() {
    const [skills, setSkills] = useState<string[]>(["React", "TypeScript"]);
    const [skillInput, setSkillInput] = useState("");
    const [loading, setLoading] = useState(false);

    const [formData, setFormData] = useState({
        title: "",
        type: "Remote",
        salaryMin: "",
        salaryMax: "",
        description: "",
    });

    const addSkill = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter' && skillInput.trim()) {
            e.preventDefault();
            if (!skills.includes(skillInput.trim())) {
                setSkills([...skills, skillInput.trim()]);
            }
            setSkillInput("");
        }
    };

    const removeSkill = (skillToRemove: string) => {
        setSkills(skills.filter(s => s !== skillToRemove));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);
        const payload: any = {
            title: formData.title,
            type: formData.type === "On-site" ? "full-time" : "remote",
            work_location_type: formData.type.toLowerCase(),
            experience_level: "mid",
            salary_min: formData.salaryMin ? parseInt(formData.salaryMin) : undefined,
            salary_max: formData.salaryMax ? parseInt(formData.salaryMax) : undefined,
            description: formData.description,
            company: "My Company", // TODO: specific company name
            location: "Remote", // TODO: specific location
            skills: skills,
        };

        try {
            await createJobAction(payload);
            // Reset form
            setFormData({
                title: "",
                type: "Remote",
                salaryMin: "",
                salaryMax: "",
                description: "",
            });
            setSkills([]);
            alert("Job posted successfully!");
        } catch (error) {
            console.error(error);
            alert("Failed to post job.");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="rounded-xl border border-slate-100 bg-white p-8 shadow-sm">
            <form className="space-y-6" onSubmit={handleSubmit}>
                <div className="grid gap-6 md:grid-cols-2">
                    <div className="space-y-2">
                        <label className="text-sm font-semibold text-slate-900">Job Title</label>
                        <input
                            type="text"
                            required
                            value={formData.title}
                            onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                            placeholder="e.g. Senior Frontend Developer"
                            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="text-sm font-semibold text-slate-900">Work Model</label>
                        <select
                            value={formData.type}
                            onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                            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"
                        >
                            <option>Remote</option>
                            <option>On-site</option>
                            <option>Hybrid</option>
                        </select>
                    </div>
                </div>

                <div className="grid gap-6 md:grid-cols-2">
                    <div className="space-y-2">
                        <label className="text-sm font-semibold text-slate-900">Salary Range (Minimum)</label>
                        <div className="relative">
                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">$</span>
                            <input
                                type="number"
                                value={formData.salaryMin}
                                onChange={(e) => setFormData({ ...formData, salaryMin: e.target.value })}
                                placeholder="40,000"
                                className="w-full rounded-lg border border-slate-200 pl-8 pr-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                            />
                        </div>
                    </div>
                    <div className="space-y-2">
                        <label className="text-sm font-semibold text-slate-900">Salary Range (Maximum)</label>
                        <div className="relative">
                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">$</span>
                            <input
                                type="number"
                                value={formData.salaryMax}
                                onChange={(e) => setFormData({ ...formData, salaryMax: e.target.value })}
                                placeholder="80,000"
                                className="w-full rounded-lg border border-slate-200 pl-8 pr-4 py-2.5 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                            />
                        </div>
                    </div>
                </div>

                <div className="space-y-2">
                    <label className="text-sm font-semibold text-slate-900">Skills Required</label>
                    <div className="flex flex-wrap gap-2 mb-2">
                        {skills.map(skill => (
                            <span key={skill} className="flex items-center gap-1.5 rounded-lg bg-primary/5 px-2.5 py-1.5 text-xs font-semibold text-primary border border-primary/10">
                                {skill}
                                <button type="button" onClick={() => removeSkill(skill)}><X className="h-3 w-3" /></button>
                            </span>
                        ))}
                    </div>
                    <div className="relative">
                        <Plus className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                        <input
                            type="text"
                            value={skillInput}
                            onChange={(e) => setSkillInput(e.target.value)}
                            onKeyDown={addSkill}
                            placeholder="Add skill and press Enter..."
                            className="w-full rounded-lg border border-slate-200 py-2.5 pl-9 pr-4 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                        />
                    </div>
                </div>

                <div className="space-y-2">
                    <label className="text-sm font-semibold text-slate-900">Job Description</label>
                    <textarea
                        rows={5}
                        required
                        value={formData.description}
                        onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                        placeholder="Describe the job responsibilities, requirements..."
                        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
                    disabled={loading}
                    className="flex w-full items-center justify-center gap-2 rounded-xl bg-primary py-3 font-bold text-white transition-colors hover:bg-blue-700 md:w-auto md:px-12 disabled:opacity-50"
                >
                    {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "Post Job"} <Send className="h-4 w-4" />
                </button>
            </form>
        </div>
    );
}
