"use client";

import { useFormContext, Controller } from "react-hook-form";
import { JobPostingFormValues } from "@/lib/validations/job";
import { DollarSign, EyeOff, PlusCircle } from "lucide-react";
import { useState } from "react";

// In a real app this might come from the database
const COMMON_BENEFITS = [
    "Comprehensive Health Insurance",
    "Dental and Vision Coverage",
    "401(k) Matching",
    "Unlimited PTO",
    "Flexible Working Hours",
    "Home Office Stipend",
    "Gym Membership / Wellness",
    "Paid Parental Leave",
    "Commuter Benefits",
    "Learning & Development Budget"
];

export function Step3Compensation() {
    const { register, watch, setValue, control, formState: { errors } } = useFormContext<JobPostingFormValues>();

    const salaryType = watch("salary_type");
    const selectedBenefits = watch("benefits") || [];

    const [customBenefit, setCustomBenefit] = useState("");

    const toggleBenefit = (benefit: string) => {
        if (selectedBenefits.includes(benefit)) {
            setValue("benefits", selectedBenefits.filter(b => b !== benefit), { shouldValidate: true });
        } else {
            setValue("benefits", [...selectedBenefits, benefit], { shouldValidate: true });
        }
    };

    const addCustomBenefit = () => {
        if (customBenefit.trim() && !selectedBenefits.includes(customBenefit.trim())) {
            setValue("benefits", [...selectedBenefits, customBenefit.trim()], { shouldValidate: true });
            setCustomBenefit("");
        }
    };

    return (
        <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
            <div>
                <h2 className="text-2xl font-bold text-slate-900">Compensation & Benefits</h2>
                <p className="text-slate-500 mt-1">Be transparent about pay and what your company offers.</p>
            </div>

            <div className="space-y-6">
                {/* Pay Type */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                        <label className="text-sm font-semibold text-slate-700">Salary Type <span className="text-red-500">*</span></label>
                        <select
                            {...register("salary_type")}
                            className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 bg-white"
                        >
                            <option value="annual">Annual Salary</option>
                            <option value="monthly">Monthly Salary</option>
                            <option value="hourly">Hourly Rate</option>
                            <option value="contract">Fixed Contract Rate</option>
                            <option value="commission">Commission Only</option>
                        </select>
                    </div>

                    <div className="space-y-2">
                        <label className="text-sm font-semibold text-slate-700">Currency</label>
                        <select
                            {...register("currency")}
                            className="w-full rounded-xl border border-slate-200 px-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 bg-white"
                        >
                            <option value="USD">USD ($)</option>
                            <option value="EUR">EUR (€)</option>
                            <option value="GBP">GBP (£)</option>
                            <option value="CAD">CAD ($)</option>
                            <option value="AUD">AUD ($)</option>
                            <option value="NGN">NGN (₦)</option>
                        </select>
                    </div>
                </div>

                {/* Pay Type Toggle */}
                <div className="bg-white p-2 rounded-2xl border border-slate-200 inline-flex items-center gap-1 self-start">
                    <button
                        type="button"
                        onClick={() => setValue("is_fixed_salary", true)}
                        className={`px-6 py-2 rounded-xl text-sm font-semibold transition-all ${watch("is_fixed_salary")
                            ? "bg-slate-900 text-white shadow-md shadow-slate-900/10"
                            : "text-slate-500 hover:text-slate-800 hover:bg-slate-50"
                            }`}
                    >
                        Fixed Rate
                    </button>
                    <button
                        type="button"
                        onClick={() => setValue("is_fixed_salary", false)}
                        className={`px-6 py-2 rounded-xl text-sm font-semibold transition-all ${!watch("is_fixed_salary")
                            ? "bg-slate-900 text-white shadow-md shadow-slate-900/10"
                            : "text-slate-500 hover:text-slate-800 hover:bg-slate-50"
                            }`}
                    >
                        Salary Range
                    </button>
                </div>

                {/* Salary Range */}
                {salaryType !== "commission" && (
                    <div className="bg-slate-50 p-6 rounded-2xl border border-slate-200 space-y-6 animate-in fade-in zoom-in-95 duration-300">
                        <div className="flex items-center justify-between">
                            <h3 className="font-semibold text-slate-800 flex items-center gap-2">
                                <DollarSign className="h-5 w-5 text-slate-400" /> {watch("is_fixed_salary") ? "Fixed Pay Amount" : "Pay Range"}
                            </h3>
                            <button
                                type="button"
                                onClick={() => setValue("hide_salary", !watch("hide_salary"))}
                                className={`text-xs font-semibold px-2 py-1 rounded flex items-center gap-1.5 transition-colors ${watch("hide_salary") ? "text-amber-600 bg-amber-50" : "text-slate-400 hover:text-slate-600"}`}
                            >
                                <EyeOff className="h-3.5 w-3.5" />
                                {watch("hide_salary") ? "Hidden from public" : "Visible to public"}
                            </button>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-2">
                                <label className="text-sm font-semibold text-slate-700">
                                    {watch("is_fixed_salary") ? "Exact Amount" : "Minimum Pay"} <span className="text-red-500">*</span>
                                </label>
                                <div className="relative">
                                    <span className="absolute left-4 top-3 text-slate-400 font-medium">
                                        {watch("currency") === "NGN" ? "₦" : watch("currency") === "USD" ? "$" : watch("currency")}
                                    </span>
                                    <Controller
                                        name="salary_min"
                                        control={control}
                                        render={({ field }) => (
                                            <input
                                                type="text"
                                                value={field.value != null ? Number(field.value).toLocaleString("en-US") : ""}
                                                onChange={(e) => {
                                                    const raw = e.target.value.replace(/\D/g, "");
                                                    field.onChange(raw ? Number(raw) : undefined);
                                                }}
                                                onBlur={field.onBlur}
                                                placeholder={watch("is_fixed_salary") ? "e.g. 500,000" : "e.g. 400,000"}
                                                className="w-full rounded-xl border border-slate-200 pl-16 pr-4 py-3 outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 bg-white"
                                            />
                                        )}
                                    />
                                </div>
                                {errors.salary_min && <p className="text-xs text-red-500 mt-1">{errors.salary_min.message}</p>}
                            </div>

                            {!watch("is_fixed_salary") && (
                                <div className="space-y-2 animate-in fade-in slide-in-from-left-2 duration-300">
                                    <label className="text-sm font-semibold text-slate-700">Maximum Pay</label>
                                    <div className="relative">
                                        <span className="absolute left-4 top-3 text-slate-400 font-medium">
                                            {watch("currency") === "NGN" ? "₦" : watch("currency") === "USD" ? "$" : watch("currency")}
                                        </span>
                                        <Controller
                                            name="salary_max"
                                            control={control}
                                            render={({ field }) => (
                                                <input
                                                    type="text"
                                                    value={field.value != null ? Number(field.value).toLocaleString("en-US") : ""}
                                                    onChange={(e) => {
                                                        const raw = e.target.value.replace(/\D/g, "");
                                                        field.onChange(raw ? Number(raw) : undefined);
                                                    }}
                                                    onBlur={field.onBlur}
                                                    placeholder="e.g. 800,000"
                                                    className={`w-full rounded-xl border pl-16 pr-4 py-3 outline-none bg-white transition-all ${errors.salary_max ? "border-red-300 focus:border-red-500 focus:ring-1 focus:ring-red-500/20" : "border-slate-200 focus:border-primary focus:ring-1 focus:ring-primary/20"
                                                        }`}
                                                />
                                            )}
                                        />
                                    </div>
                                    {errors.salary_max && <p className="text-xs text-red-500 mt-1">{errors.salary_max.message}</p>}
                                </div>
                            )}
                        </div>

                        <p className="text-xs text-slate-500 border-t border-slate-200 border-dashed pt-4">
                            {watch("is_fixed_salary")
                                ? "Candidates will see a single fixed amount for this position."
                                : "Providing a range helps attract more qualified candidates by setting clear expectations."}
                        </p>
                    </div>
                )}

                {/* Benefits Checkboxes */}
                <div className="space-y-4 pt-4">
                    <div>
                        <h3 className="font-semibold text-slate-800">Benefits & Perks</h3>
                        <p className="text-sm text-slate-500">Select all that apply, or add custom benefits.</p>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        {COMMON_BENEFITS.map((benefit) => {
                            const isSelected = selectedBenefits.includes(benefit);
                            return (
                                <label
                                    key={benefit}
                                    className={`flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer ${isSelected ? "border-primary bg-primary/5 shadow-sm" : "border-slate-200 hover:bg-slate-50"
                                        }`}
                                >
                                    <input
                                        type="checkbox"
                                        className="w-4 h-4 rounded border-slate-300 text-primary focus:ring-primary/20"
                                        checked={isSelected}
                                        onChange={() => toggleBenefit(benefit)}
                                    />
                                    <span className={`text-sm font-medium ${isSelected ? "text-primary" : "text-slate-700"}`}>
                                        {benefit}
                                    </span>
                                </label>
                            );
                        })}
                    </div>

                    {/* Custom Benefit Input */}
                    <div className="flex gap-2 pt-2">
                        <input
                            type="text"
                            value={customBenefit}
                            onChange={(e) => setCustomBenefit(e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    e.preventDefault();
                                    addCustomBenefit();
                                }
                            }}
                            placeholder="e.g. Free Catered Lunches"
                            className="flex-1 rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 bg-white"
                        />
                        <button
                            type="button"
                            onClick={addCustomBenefit}
                            disabled={!customBenefit.trim()}
                            className="px-4 py-3 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl font-medium flex items-center gap-2 transition-colors disabled:opacity-50"
                        >
                            <PlusCircle className="h-4 w-4" /> Add
                        </button>
                    </div>

                    {/* Render custom benefits that aren't in the common list */}
                    {selectedBenefits.filter(b => !COMMON_BENEFITS.includes(b)).length > 0 && (
                        <div className="flex flex-wrap gap-2 mt-4">
                            {selectedBenefits.filter(b => !COMMON_BENEFITS.includes(b)).map(custom => (
                                <span key={custom} className="bg-primary/10 text-primary border border-primary/20 px-3 py-1.5 rounded-full text-sm font-medium flex items-center gap-2">
                                    {custom}
                                    <button type="button" onClick={() => toggleBenefit(custom)} className="hover:text-primary/70">
                                        &times;
                                    </button>
                                </span>
                            ))}
                        </div>
                    )}

                </div>
            </div>
        </div>
    );
}
