"use client";

import { useFormContext, useFieldArray } from "react-hook-form";
import { JobPostingFormValues } from "@/lib/validations/job";
import { Link, Mail, Settings, MousePointerClick, Plus, Trash2, GripVertical, FileText, CheckSquare, AlignLeft, Type, Link2, Upload, MessageSquare } from "lucide-react";

const QUESTION_TYPES = [
    { id: "short_answer", label: "Short Answer", icon: Type },
    { id: "long_answer", label: "Long Answer", icon: AlignLeft },
    { id: "multiple_choice", label: "Multiple Choice", icon: MousePointerClick },
    { id: "checkbox", label: "Checkboxes", icon: CheckSquare },
    { id: "dropdown", label: "Dropdown Menu", icon: FileText },
    { id: "link", label: "Website/Portfolio Link", icon: Link2 },
    { id: "file", label: "File Upload", icon: Upload },
] as const;

function QuestionOptionsEditor({ nestIndex, control, register }: { nestIndex: number; control: any; register: any }) {
    const { fields, remove, append } = useFieldArray({
        control,
        name: `screening_questions.${nestIndex}.options`
    });

    return (
        <div className="space-y-2 mt-2">
            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Options</p>
            {fields.map((item, k) => (
                <div key={item.id} className="flex items-center gap-2 group/opt">
                    <div className="w-4 h-4 rounded-full border border-slate-300 shrink-0 flex items-center justify-center">
                        <div className="w-1.5 h-1.5 rounded-full bg-slate-200"></div>
                    </div>
                    <input
                        {...register(`screening_questions.${nestIndex}.options.${k}.label` as const)}
                        type="text"
                        placeholder={`Option ${k + 1}`}
                        className="flex-1 text-sm border-0 border-b border-transparent hover:border-slate-200 focus:border-primary/30 focus:ring-0 px-0 py-1 bg-transparent transition-colors"
                    />
                    <button
                        type="button"
                        onClick={() => remove(k)}
                        className="text-slate-400 hover:text-red-500 opacity-0 group-hover/opt:opacity-100 transition-opacity p-1"
                    >
                        <Trash2 className="h-3 w-3" />
                    </button>
                </div>
            ))}
            <button
                type="button"
                onClick={() => append({ id: crypto.randomUUID(), label: "" })}
                className="text-xs font-semibold text-primary hover:text-primary/80 flex items-center gap-1 mt-2 transition-colors"
            >
                <Plus className="h-3 w-3" /> Add Option
            </button>
        </div>
    );
}

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

    const applicationMethod = watch("application_method");

    const {
        fields: questionFields,
        append: appendQuestion,
        remove: removeQuestion,
        move: moveQuestion,
    } = useFieldArray({
        control,
        name: "screening_questions",
    });

    const addQuestion = (type: string) => {
        appendQuestion({
            question_text: "",
            question_type: type as any,
            is_required: true,
            options: (type === "multiple_choice" || type === "dropdown" || type === "checkbox") ? [{ id: crypto.randomUUID(), label: "" }] : [],
        });
    };

    return (
        <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4 duration-500">
            <div>
                <h2 className="text-2xl font-bold text-slate-900">Application Settings & Screening</h2>
                <p className="text-slate-500 mt-1">Configure how candidates apply and ask pre-screening questions.</p>
            </div>

            <div className="space-y-8">
                {/* Application Method */}
                <div className="space-y-4">
                    <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2">
                        <Settings className="h-4 w-4 text-slate-400" /> How should candidates apply?
                    </h3>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        {/* Internal */}
                        <label className={`cursor-pointer w-full rounded-2xl border-2 p-4 flex flex-col gap-2 transition-all ${applicationMethod === "internal"
                            ? "border-primary bg-primary/5 shadow-sm"
                            : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                            }`}>
                            <div className="flex items-center gap-3">
                                <input type="radio" value="internal" {...register("application_method")} className="w-4 h-4 text-primary focus:ring-primary/20" />
                                <span className={`font-bold ${applicationMethod === "internal" ? "text-primary" : "text-slate-800"}`}>Internal Platform</span>
                            </div>
                            <p className="text-xs text-slate-500 pl-7">Candidates apply directly on this job board. Full ATS tracking available.</p>
                        </label>

                        {/* External */}
                        <label className={`cursor-pointer w-full rounded-2xl border-2 p-4 flex flex-col gap-2 transition-all ${applicationMethod === "external"
                            ? "border-primary bg-primary/5 shadow-sm"
                            : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                            }`}>
                            <div className="flex items-center gap-3">
                                <input type="radio" value="external" {...register("application_method")} className="w-4 h-4 text-primary focus:ring-primary/20" />
                                <span className={`font-bold ${applicationMethod === "external" ? "text-primary" : "text-slate-800"}`}>External Link</span>
                            </div>
                            <p className="text-xs text-slate-500 pl-7">Redirect candidates to your own career site or ATS (e.g. Greenhouse).</p>
                        </label>

                        {/* Email */}
                        <label className={`cursor-pointer w-full rounded-2xl border-2 p-4 flex flex-col gap-2 transition-all ${applicationMethod === "email"
                            ? "border-primary bg-primary/5 shadow-sm"
                            : "border-slate-200 hover:border-slate-300 hover:bg-slate-50"
                            }`}>
                            <div className="flex items-center gap-3">
                                <input type="radio" value="email" {...register("application_method")} className="w-4 h-4 text-primary focus:ring-primary/20" />
                                <span className={`font-bold ${applicationMethod === "email" ? "text-primary" : "text-slate-800"}`}>Via Email</span>
                            </div>
                            <p className="text-xs text-slate-500 pl-7">Candidates send their resume directly to a specified email address.</p>
                        </label>
                    </div>

                    {/* Dynamic Inputs for Application Method */}
                    <div className="mt-4">
                        {applicationMethod === "external" && (
                            <div className="animate-in fade-in slide-in-from-top-2 duration-300 space-y-2">
                                <label className="text-sm font-semibold text-slate-700 flex items-center gap-2">
                                    <Link className="h-4 w-4 text-slate-400" /> External Application URL <span className="text-red-500">*</span>
                                </label>
                                <input
                                    {...register("external_url")}
                                    type="url"
                                    placeholder="https://boards.greenhouse.io/acme/jobs/123"
                                    className={`w-full rounded-xl border px-4 py-3 outline-none bg-white transition-all ${errors.external_url ? "border-red-300 focus:border-red-500" : "border-slate-200 focus:border-primary focus:ring-1"
                                        }`}
                                />
                                {errors.external_url && <p className="text-xs text-red-500 mt-1">{errors.external_url.message}</p>}
                            </div>
                        )}

                        {applicationMethod === "email" && (
                            <div className="animate-in fade-in slide-in-from-top-2 duration-300 space-y-2">
                                <label className="text-sm font-semibold text-slate-700 flex items-center gap-2">
                                    <Mail className="h-4 w-4 text-slate-400" /> Contact Email Address <span className="text-red-500">*</span>
                                </label>
                                <input
                                    {...register("contact_email")}
                                    type="email"
                                    placeholder="hiring@acmecorp.com"
                                    className={`w-full rounded-xl border px-4 py-3 outline-none bg-white transition-all ${errors.contact_email ? "border-red-300 focus:border-red-500" : "border-slate-200 focus:border-primary focus:ring-1"
                                        }`}
                                />
                                {errors.contact_email && <p className="text-xs text-red-500 mt-1">{errors.contact_email.message}</p>}
                            </div>
                        )}
                    </div>
                </div>

                {/* Tally-style Screening Question Builder */}
                {applicationMethod === "internal" && (
                    <div className="space-y-6 pt-6 border-t border-slate-200 animate-in fade-in duration-500">
                        <div>
                            <h3 className="text-sm font-semibold text-slate-800 flex items-center gap-2 mb-1">
                                <MessageSquare className="h-4 w-4 text-slate-400" /> Custom Screening Questions
                            </h3>
                            <p className="text-xs text-slate-500">Add questions candidates must answer when applying. Drag to reorder.</p>
                        </div>

                        {/* List of active questions */}
                        <div className="space-y-4">
                            {questionFields.map((field, index) => {
                                const qType = QUESTION_TYPES.find(t => t.id === field.question_type);
                                const isOptionsType = field.question_type === "multiple_choice" || field.question_type === "dropdown" || field.question_type === "checkbox";

                                return (
                                    <div
                                        key={field.id}
                                        className="bg-white border text-left border-slate-200 rounded-xl shadow-sm hover:border-slate-300 transition-colors group"
                                        draggable
                                        onDragStart={(e) => {
                                            e.dataTransfer.setData("text/plain", index.toString());
                                            e.dataTransfer.effectAllowed = "move";
                                        }}
                                        onDragOver={(e) => {
                                            e.preventDefault();
                                            e.dataTransfer.dropEffect = "move";
                                        }}
                                        onDrop={(e) => {
                                            e.preventDefault();
                                            const draggedIdx = Number(e.dataTransfer.getData("text/plain"));
                                            if (draggedIdx !== index && !isNaN(draggedIdx)) {
                                                moveQuestion(draggedIdx, index);
                                            }
                                        }}
                                    >
                                        <div className="flex items-start gap-4 p-4">
                                            <div className="mt-1 cursor-grab text-slate-300 hover:text-slate-500 active:cursor-grabbing">
                                                <GripVertical className="h-5 w-5" />
                                            </div>

                                            <div className="flex-1 space-y-4">
                                                <div className="flex items-start justify-between gap-4">
                                                    <div className="w-full space-y-1">
                                                        <div className="flex items-center gap-2 mb-2">
                                                            {qType && <qType.icon className="h-4 w-4 text-primary" />}
                                                            <span className="text-xs font-semibold text-slate-500 uppercase tracking-wide">{qType?.label}</span>
                                                        </div>
                                                        <input
                                                            {...register(`screening_questions.${index}.question_text` as const)}
                                                            type="text"
                                                            placeholder="Type your question here..."
                                                            className="w-full text-base font-medium border-0 border-b border-transparent focus:border-primary/50 focus:ring-0 px-0 py-1 bg-transparent"
                                                        />
                                                        {errors.screening_questions?.[index]?.question_text && (
                                                            <p className="text-xs text-red-500">{errors.screening_questions[index]?.question_text?.message}</p>
                                                        )}
                                                    </div>
                                                    <button
                                                        type="button"
                                                        onClick={() => removeQuestion(index)}
                                                        className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </button>
                                                </div>

                                                {/* Additional Options for certain types */}
                                                {isOptionsType && (
                                                    <div className="pl-4 border-l-2 border-slate-100 space-y-2">
                                                        <QuestionOptionsEditor nestIndex={index} control={control} register={register} />
                                                    </div>
                                                )}

                                                {field.question_type === "file" && (
                                                    <div className="pl-4 mt-2 border-l-2 border-slate-100">
                                                        <label className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Accepted File Types (Optional)</label>
                                                        <input
                                                            {...register(`screening_questions.${index}.ideal_answer` as const)}
                                                            type="text"
                                                            placeholder="e.g. .pdf, .docx, .zip"
                                                            className="w-full mt-1 text-sm border-0 border-b border-slate-200 focus:border-primary/30 focus:ring-0 px-0 py-1 bg-transparent transition-colors"
                                                        />
                                                        <p className="text-[10px] text-slate-400 mt-1">Leave blank to accept all file types.</p>
                                                    </div>
                                                )}

                                                <div className="flex items-center justify-between pt-2 border-t border-slate-50">
                                                    <label className="flex items-center gap-2 cursor-pointer">
                                                        <input
                                                            type="checkbox"
                                                            {...register(`screening_questions.${index}.is_required` as const)}
                                                            className="w-4 h-4 rounded border-slate-300 text-primary focus:ring-primary/20"
                                                        />
                                                        <span className="text-xs font-medium text-slate-600">Required question</span>
                                                    </label>
                                                    {/* Invisible Order Input for submission */}
                                                    <input type="hidden" {...register(`screening_questions.${index}.order` as const, { valueAsNumber: true })} value={index} />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}

                            {questionFields.length === 0 && (
                                <div className="text-center py-8 bg-slate-50 rounded-xl border-2 border-dashed border-slate-200">
                                    <MessageSquare className="h-8 w-8 text-slate-300 mx-auto mb-2" />
                                    <p className="text-sm font-medium text-slate-600">No screening questions yet.</p>
                                    <p className="text-xs text-slate-400 mb-4">Add questions below to start building your form.</p>
                                </div>
                            )}
                        </div>

                        {/* Question Type Selector Toolbar (Tally Style) */}
                        <div className="bg-slate-50 p-2 rounded-xl border border-slate-200">
                            <p className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2 px-2 pt-1">Insert block</p>
                            <div className="flex flex-wrap gap-1">
                                {QUESTION_TYPES.map((type) => (
                                    <button
                                        key={type.id}
                                        type="button"
                                        onClick={() => addQuestion(type.id)}
                                        className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-white hover:shadow-sm text-sm font-medium text-slate-700 transition-all"
                                    >
                                        <type.icon className="h-4 w-4 text-slate-400" />
                                        {type.label}
                                    </button>
                                ))}
                            </div>
                        </div>

                    </div>
                )}

            </div>
        </div>
    );
}
