"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import { RichTextEditor } from "@/components/jobs/wizard/RichTextEditor";

interface EditJobClientProps {
    job: {
        id: string;
        title: string;
        company: string;
        description: string;
        type: string;
        work_location_type: string;
        address: string;
        city: string;
        state: string;
        country: string;
        salary_min: number;
        salary_max: number;
        currency: string;
        experience_level: string;
        skills: string; // Comma separated
    }
}

export default function EditJobClient({ job }: EditJobClientProps) {
    const router = useRouter();
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState(job);

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

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);

        try {
            const res = await fetch(`/api/employer/jobs/${job.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    ...formData,
                    skills: formData.skills.split(',').map(s => s.trim()).filter(Boolean)
                })
            });

            if (!res.ok) {
                const errorData = await res.json().catch(() => ({}));
                throw new Error(errorData.error || 'Failed to update job');
            }

            toast.success("Job updated successfully! Submitted for review.");
            router.push('/dashboard/jobs');
            router.refresh();

        } catch (error: any) {
            toast.error(error.message || "An unexpected error occurred");
        } finally {
            setLoading(false);
        }
    };

    return (
        <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid gap-6 md:grid-cols-2">
                <div className="space-y-2">
                    <label htmlFor="title" className="text-sm font-medium text-slate-700">Job Title *</label>
                    <input
                        id="title" name="title" required
                        value={formData.title} onChange={handleChange}
                        className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                </div>
                <div className="space-y-2">
                    <label htmlFor="company" className="text-sm font-medium text-slate-700">Company Name *</label>
                    <input
                        id="company" name="company" required
                        value={formData.company} onChange={handleChange}
                        className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                </div>

                <div className="space-y-2">
                    <label htmlFor="type" className="text-sm font-medium text-slate-700">Employment Type *</label>
                    <select id="type" name="type" required value={formData.type} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary">
                        <option value="full-time">Full-time</option>
                        <option value="part-time">Part-time</option>
                        <option value="contract">Contract</option>
                        <option value="freelance">Freelance</option>
                        <option value="internship">Internship</option>
                    </select>
                </div>

                <div className="space-y-2">
                    <label htmlFor="work_location_type" className="text-sm font-medium text-slate-700">Work Setup *</label>
                    <select id="work_location_type" name="work_location_type" required value={formData.work_location_type} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary">
                        <option value="on-site">On-site</option>
                        <option value="remote">Remote</option>
                        <option value="hybrid">Hybrid</option>
                    </select>
                </div>
            </div>

            <div className="grid gap-6 md:grid-cols-3">
                <div className="space-y-2">
                    <label htmlFor="city" className="text-sm font-medium text-slate-700">City</label>
                    <input id="city" name="city" value={formData.city} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" />
                </div>
                <div className="space-y-2">
                    <label htmlFor="state" className="text-sm font-medium text-slate-700">State / Region</label>
                    <input id="state" name="state" value={formData.state} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" />
                </div>
                <div className="space-y-2">
                    <label htmlFor="country" className="text-sm font-medium text-slate-700">Country</label>
                    <input id="country" name="country" value={formData.country} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" />
                </div>
            </div>

            <div className="grid gap-6 md:grid-cols-3">
                <div className="space-y-2">
                    <label htmlFor="salary_min" className="text-sm font-medium text-slate-700">Minimum Salary</label>
                    <input id="salary_min" name="salary_min" type="number" value={formData.salary_min} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" />
                </div>
                <div className="space-y-2">
                    <label htmlFor="salary_max" className="text-sm font-medium text-slate-700">Maximum Salary</label>
                    <input id="salary_max" name="salary_max" type="number" value={formData.salary_max} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary" />
                </div>
                <div className="space-y-2">
                    <label htmlFor="currency" className="text-sm font-medium text-slate-700">Currency</label>
                    <select id="currency" name="currency" value={formData.currency} onChange={handleChange} className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary">
                        <option value="USD">USD ($)</option>
                        <option value="EUR">EUR (€)</option>
                        <option value="GBP">GBP (£)</option>
                        <option value="NGN">NGN (₦)</option>
                    </select>
                </div>
            </div>

            <div className="space-y-2">
                <label htmlFor="skills" className="text-sm font-medium text-slate-700">Skills (Comma separated)</label>
                <input
                    id="skills" name="skills"
                    value={formData.skills} onChange={handleChange}
                    placeholder="e.g. React, Node.js, Python, Marketing"
                    className="w-full text-slate-900 bg-white rounded-md border border-slate-300 px-3 py-2 text-sm focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
                />
            </div>

            <div className="space-y-2">
                <label className="text-sm font-medium text-slate-700">Job Description *</label>
                <RichTextEditor
                    content={formData.description}
                    onChange={(html) => setFormData({ ...formData, description: html })}
                />
            </div>

            <div className="pt-4 flex justify-end gap-3 border-t border-slate-100">
                <button
                    type="button"
                    onClick={() => router.back()}
                    className="px-4 py-2 text-sm font-bold text-slate-700 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors"
                >
                    Cancel
                </button>
                <button
                    type="submit"
                    disabled={loading}
                    className="px-8 py-2 text-sm font-bold text-white bg-primary hover:bg-primary/90 focus:ring-4 focus:ring-primary/20 rounded-lg transition-all disabled:opacity-50"
                >
                    {loading ? 'Saving...' : 'Save & Resubmit'}
                </button>
            </div>
        </form>
    );
}
