"use client";

import { useState, useEffect, useCallback } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { JobPostingSchema, JobPostingFormValues } from "@/lib/validations/job";
import { useRouter } from "next/navigation";
import { CheckCircle2, ChevronRight, Save, Loader2, AlertCircle } from "lucide-react";
import { useDebounce } from "use-debounce";
import { createJobAction } from "@/app/actions/jobActions";

// We'll create these step components next
import { Step1Basics } from "./Step1Basics";
import { Step2Location } from "./Step2Location";
import { Step3Compensation } from "./Step3Compensation";
import { Step4Description } from "./Step4Description";
import { Step5Settings } from "./Step5Settings";
import { JobPreview } from "./JobPreview";

const STEPS = [
    { id: "basics", title: "Job Basics", description: "Title, level, and category" },
    { id: "location", title: "Location", description: "Where will they work?" },
    { id: "compensation", title: "Compensation", description: "Salary and benefits" },
    { id: "description", title: "Description", description: "Details and requirements" },
    { id: "settings", title: "Application Setup", description: "Screening and tracking" },
    { id: "preview", title: "Preview", description: "Final review" },
];

interface JobPostingWizardProps {
    initialData?: Partial<JobPostingFormValues>;
    jobId?: string; // If editing an existing job
}

export function JobPostingWizard({ initialData, jobId }: JobPostingWizardProps) {
    const router = useRouter();
    const [currentStep, setCurrentStep] = useState(0);
    const [isSavingDraft, setIsSavingDraft] = useState(false);
    const [lastSaved, setLastSaved] = useState<Date | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitError, setSubmitError] = useState<string | null>(null);
    const [stepError, setStepError] = useState<string | null>(null);

    const methods = useForm<JobPostingFormValues>({
        resolver: zodResolver(JobPostingSchema) as any,
        defaultValues: {
            type: "full-time",
            experience_level: "mid",
            number_of_openings: 1,
            work_location_type: "on-site",
            hide_salary: false,
            is_fixed_salary: false,
            currency: "NGN",
            application_method: "internal",
            tags: [],
            skills: [],
            responsibilities: [""],
            required_qualifications: [""],
            preferred_qualifications: [""],
            benefits: [],
            screening_questions: [],
            ...initialData,
        },
        mode: "onChange",
    });

    const { handleSubmit, watch, trigger, getValues, formState } = methods;
    const formValues = watch();

    // Auto-save debounced values
    const [debouncedValues] = useDebounce(formValues, 2000);

    // Auto-save to local storage / draft API
    useEffect(() => {
        const saveDraft = async () => {
            // Don't auto-save empty forms immediately
            if (!debouncedValues.title && !debouncedValues.company) return;

            setIsSavingDraft(true);
            try {
                // Save to local storage as backup
                const draftKey = jobId ? `job_draft_${jobId}` : "job_draft_new";
                localStorage.setItem(draftKey, JSON.stringify(debouncedValues));

                // In a real app, you might also ping a /api/jobs/draft endpoint here

                setLastSaved(new Date());
            } catch (error) {
                console.error("Failed to save draft", error);
            } finally {
                setIsSavingDraft(false);
            }
        };

        saveDraft();
    }, [debouncedValues, jobId]);

    const validateStep = async (stepIndex: number) => {
        setStepError(null);
        let fieldsToValidate: (keyof JobPostingFormValues)[] = [];

        switch (stepIndex) {
            case 0:
                fieldsToValidate = ["title", "company", "type", "experience_level", "number_of_openings"];
                break;
            case 1:
                fieldsToValidate = ["work_location_type"];
                break;
            case 2:
                // salary_type is optional now — only trigger if set
                fieldsToValidate = [];
                break;
            case 3:
                fieldsToValidate = ["description", "responsibilities", "required_qualifications"];
                break;
            case 4:
                fieldsToValidate = ["application_method"];
                break;
        }

        if (fieldsToValidate.length > 0) {
            const isValid = await trigger(fieldsToValidate);
            if (!isValid) {
                // Extract first error message and show it prominently
                const currentErrors = methods.formState.errors;
                const firstErrorField = fieldsToValidate.find(f => currentErrors[f]);
                const errorMsg = firstErrorField
                    ? (currentErrors[firstErrorField] as any)?.message
                    : null;
                setStepError(errorMsg || "Please fill in all required fields to continue.");
                window.scrollTo({ top: 0, behavior: "smooth" });
            }
            return isValid;
        }
        return true;
    };

    const nextStep = async () => {
        const isValid = await validateStep(currentStep);
        if (isValid) {
            setStepError(null);
            setCurrentStep((prev) => Math.min(prev + 1, STEPS.length - 1));
            window.scrollTo({ top: 0, behavior: "smooth" });
        }
    };

    const prevStep = () => {
        setCurrentStep((prev) => Math.max(prev - 1, 0));
        window.scrollTo({ top: 0, behavior: "smooth" });
    };

    const jumpToStep = async (stepIndex: number) => {
        // Only allow jumping back, or jumping forward if current step is valid
        if (stepIndex < currentStep) {
            setCurrentStep(stepIndex);
        } else {
            const isValid = await validateStep(currentStep);
            if (isValid) {
                setCurrentStep(stepIndex);
            }
        }
    };

    const publishJob = async () => {
        setIsSubmitting(true);
        setSubmitError(null);
        setStepError(null);

        try {
            // Clean up screening questions before validation:
            // Remove empty/unfilled questions so they don't block publishing
            const currentQuestions = methods.getValues("screening_questions") || [];
            const filledQuestions = currentQuestions
                .filter((q: any) => q.question_text && q.question_text.trim() !== "")
                .map((q: any, i: number) => ({
                    ...q,
                    order: i, // ensure order is a number, not a string from hidden input
                }));
            methods.setValue("screening_questions", filledQuestions);

            // Also clean up empty responsibilities/qualifications
            const resps = methods.getValues("responsibilities") || [];
            const filledResps = resps.filter((r: string) => r && r.trim() !== "");
            if (filledResps.length > 0) methods.setValue("responsibilities", filledResps);

            const reqs = methods.getValues("required_qualifications") || [];
            const filledReqs = reqs.filter((q: string) => q && q.trim() !== "");
            if (filledReqs.length > 0) methods.setValue("required_qualifications", filledReqs);

            // Validate ALL fields across all steps
            const allValid = await trigger();

            if (!allValid) {
                // Find which step has errors and navigate user there
                const errs = methods.formState.errors;
                const errorKeys = Object.keys(errs);

                console.log("[Publish Debug] Validation errors:", JSON.stringify(
                    errorKeys.map(k => ({ field: k, message: (errs as any)[k]?.message || (errs as any)[k]?.root?.message || 'unknown' }))
                ));

                // Map error fields to steps
                const stepFieldMap: Record<number, string[]> = {
                    0: ["title", "company", "type", "experience_level", "number_of_openings", "category_id", "industry_id", "tags"],
                    1: ["work_location_type", "address", "city", "state", "country", "zip_code", "remote_geo_restriction", "time_zone_requirements", "days_in_office"],
                    2: ["salary_type", "salary_min", "salary_max", "currency", "hide_salary", "is_fixed_salary", "additional_compensation", "benefits"],
                    3: ["description", "responsibilities", "required_qualifications", "preferred_qualifications", "summary", "skills"],
                    4: ["application_method", "external_url", "contact_email", "deadline", "screening_questions", "internal_notes"],
                };

                const failingStep = Object.entries(stepFieldMap).find(([, fields]) =>
                    fields.some(f => errorKeys.includes(f))
                );

                if (failingStep) {
                    const stepIndex = Number(failingStep[0]);
                    const stepName = STEPS[stepIndex]?.title || `Step ${stepIndex + 1}`;
                    const failingFields = failingStep[1].filter(f => errorKeys.includes(f));
                    const firstFieldError = (errs as any)[failingFields[0]];
                    const errorMessage = firstFieldError?.message || firstFieldError?.root?.message || 'Please fill in all required fields';

                    setCurrentStep(stepIndex);
                    setSubmitError(`Cannot publish: ${errorMessage} (in "${stepName}")`);
                } else {
                    setSubmitError(`Please complete all required fields. Errors in: ${errorKeys.join(', ')}`);
                }

                setIsSubmitting(false);
                window.scrollTo({ top: 0, behavior: "smooth" });
                return;
            }

            // All valid — call the server action directly
            const data = getValues();
            console.log("[Publish Debug] Submitting data:", data);

            const response = await createJobAction(data);

            if (response.success) {
                const draftKey = jobId ? `job_draft_${jobId}` : "job_draft_new";
                localStorage.removeItem(draftKey);
                router.push('/dashboard/jobs');
            } else {
                console.error("[Publish Debug] Server error:", response.error);
                setSubmitError(response.error || "Failed to publish job. Please try again.");
                window.scrollTo({ top: 0, behavior: "smooth" });
            }
        } catch (error) {
            console.error("[Publish Debug] Exception:", error);
            setSubmitError("An unexpected error occurred while publishing the job.");
            window.scrollTo({ top: 0, behavior: "smooth" });
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="max-w-6xl mx-auto pb-24">
            {/* Auto-save indicator */}
            <div className="flex justify-end mb-4 h-6">
                {isSavingDraft ? (
                    <span className="text-sm text-slate-500 animate-pulse flex items-center gap-1">
                        <Save className="h-4 w-4" /> Saving draft...
                    </span>
                ) : lastSaved ? (
                    <span className="text-sm text-slate-400 flex items-center gap-1">
                        <CheckCircle2 className="h-4 w-4 text-emerald-500" /> Draft saved at {lastSaved.toLocaleTimeString()}
                    </span>
                ) : null}
            </div>

            {(submitError || stepError) && (
                <div className="mb-6 bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-xl flex items-start gap-3">
                    <AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
                    <div>
                        <h4 className="font-semibold text-sm">{submitError ? "Failed to publish job" : "Cannot proceed"}</h4>
                        <p className="text-sm mt-1">{submitError || stepError}</p>
                    </div>
                </div>
            )}

            <div className="flex flex-col lg:flex-row gap-8">
                {/* Navigation Sidebar (Tabs) */}
                <div className="lg:w-64 shrink-0">
                    <div className="bg-white rounded-2xl border border-slate-200 p-4 sticky top-24 shadow-sm">
                        <nav className="space-y-1">
                            {STEPS.map((step, index) => {
                                const isActive = currentStep === index;
                                const isCompleted = currentStep > index;

                                return (
                                    <button
                                        key={step.id}
                                        onClick={() => jumpToStep(index)}
                                        className={`w-full text-left px-4 py-3 rounded-xl flex items-start gap-3 transition-colors ${isActive
                                            ? "bg-primary/5 border border-primary/20"
                                            : "hover:bg-slate-50 border border-transparent"
                                            }`}
                                    >
                                        <div className={`mt-0.5 w-6 h-6 rounded-full flex items-center justify-center text-xs font-semibold shrink-0 ${isActive ? "bg-primary text-white" :
                                            isCompleted ? "bg-emerald-500 text-white" :
                                                "bg-slate-100 text-slate-400"
                                            }`}>
                                            {isCompleted ? <CheckCircle2 className="h-3.5 w-3.5" /> : index + 1}
                                        </div>
                                        <div>
                                            <div className={`text-sm font-semibold ${isActive ? "text-primary" : "text-slate-700"}`}>
                                                {step.title}
                                            </div>
                                            <div className="text-xs text-slate-500 mt-0.5">{step.description}</div>
                                        </div>
                                    </button>
                                );
                            })}
                        </nav>
                    </div>
                </div>

                {/* Main Form Content */}
                <div className="flex-1 min-w-0">
                    <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden min-h-[600px]">
                        <FormProvider {...methods}>
                            <form onSubmit={(e) => { e.preventDefault(); publishJob(); }}>

                                {/* Dynamic Step Content */}
                                <div className="p-8">
                                    {currentStep === 0 && <Step1Basics />}
                                    {currentStep === 1 && <Step2Location />}
                                    {currentStep === 2 && <Step3Compensation />}
                                    {currentStep === 3 && <Step4Description />}
                                    {currentStep === 4 && <Step5Settings />}
                                    {currentStep === 5 && <JobPreview formData={getValues()} />}
                                </div>

                                {/* Bottom Navigation Bar */}
                                <div className="bg-slate-50 border-t border-slate-200 p-6 flex items-center justify-between">
                                    <button
                                        type="button"
                                        onClick={prevStep}
                                        disabled={currentStep === 0}
                                        className="px-6 py-2.5 text-sm font-semibold text-slate-600 hover:text-slate-900 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Back
                                    </button>

                                    {currentStep < STEPS.length - 1 ? (
                                        <button
                                            type="button"
                                            onClick={nextStep}
                                            className="px-6 py-2.5 text-sm font-bold text-white bg-slate-900 rounded-xl hover:bg-slate-800 transition-colors shadow-sm flex items-center gap-2"
                                        >
                                            Continue to {STEPS[currentStep + 1].title}
                                            <ChevronRight className="h-4 w-4" />
                                        </button>
                                    ) : (
                                        <button
                                            type="button"
                                            onClick={publishJob}
                                            disabled={isSubmitting}
                                            className="px-8 py-2.5 text-sm font-bold text-white bg-primary rounded-xl hover:bg-primary/90 transition-colors shadow-lg shadow-primary/20 disabled:opacity-70 flex items-center gap-2"
                                        >
                                            {isSubmitting ? (
                                                <>
                                                    <Loader2 className="h-4 w-4 animate-spin" /> Publishing...
                                                </>
                                            ) : (
                                                "Publish Job Posting"
                                            )}
                                        </button>
                                    )}
                                </div>

                            </form>
                        </FormProvider>
                    </div>
                </div>
            </div>
        </div>
    );
}
