"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { X } from "lucide-react";

const FILTER_LABELS: Record<string, Record<string, string>> = {
    type: {
        "full-time": "Full-Time",
        "part-time": "Part-Time",
        contract: "Contract",
        freelance: "Freelance",
        internship: "Internship",
        temporary: "Temporary",
    },
    workLocation: {
        remote: "🏠 Remote",
        "on-site": "🏢 On-Site",
        hybrid: "🔄 Hybrid",
    },
    experience: {
        entry: "Entry Level",
        mid: "Mid Level",
        senior: "Senior Level",
        executive: "Executive",
    },
    datePosted: {
        "24h": "Last 24 hours",
        "7d": "Last 7 days",
        "14d": "Last 14 days",
        "30d": "Last 30 days",
    },
    companySize: {
        startup: "Startup",
        small: "Small",
        medium: "Medium",
        large: "Large",
        enterprise: "Enterprise",
    },
    schedule: {
        day: "Day shift",
        evening: "Evening shift",
        night: "Night shift",
        flexible: "Flexible hours",
        weekends: "Weekends",
    },
};

export function ActiveFilters() {
    const router = useRouter();
    const searchParams = useSearchParams();

    const filters: { key: string; value: string; label: string }[] = [];

    // Collect all active multi-value filters
    for (const paramKey of ["type", "workLocation", "experience", "companySize", "schedule"]) {
        const values = searchParams.get(paramKey)?.split(",").filter(Boolean) || [];
        for (const v of values) {
            filters.push({
                key: paramKey,
                value: v,
                label: FILTER_LABELS[paramKey]?.[v] || v,
            });
        }
    }

    // Industry
    const industry = searchParams.get("industry");
    if (industry) {
        filters.push({ key: "industry", value: industry, label: `🏢 ${industry}` });
    }

    // Date posted
    const datePosted = searchParams.get("datePosted");
    if (datePosted && datePosted !== "any") {
        filters.push({
            key: "datePosted",
            value: datePosted,
            label: FILTER_LABELS.datePosted[datePosted] || datePosted,
        });
    }

    // Salary
    const salaryMin = searchParams.get("salaryMin");
    if (salaryMin) {
        filters.push({
            key: "salaryMin",
            value: salaryMin,
            label: `₦${Number(salaryMin).toLocaleString()}+`,
        });
    }

    // Search query
    const q = searchParams.get("q");
    if (q) {
        filters.push({ key: "q", value: q, label: `"${q}"` });
    }

    // Location
    const l = searchParams.get("l");
    if (l) {
        filters.push({ key: "l", value: l, label: `📍 ${l}` });
    }

    if (filters.length === 0) return null;

    const removeFilter = (key: string, value: string) => {
        const params = new URLSearchParams(searchParams.toString());
        if (["salaryMin", "datePosted", "q", "l", "industry"].includes(key)) {
            params.delete(key);
        } else {
            const current = params.get(key)?.split(",").filter(Boolean) || [];
            const updated = current.filter((v) => v !== value);
            if (updated.length) params.set(key, updated.join(","));
            else params.delete(key);
        }
        params.delete("page");
        router.push(`/jobs?${params.toString()}`);
    };

    const clearAll = () => {
        router.push("/jobs");
    };

    return (
        <div className="flex flex-wrap items-center gap-2">
            {filters.map(({ key, value, label }) => (
                <span
                    key={`${key}-${value}`}
                    className="inline-flex items-center gap-1.5 rounded-full bg-blue-50 px-3 py-1 text-xs font-semibold text-blue-700 border border-blue-100 animate-in fade-in duration-200"
                >
                    {label}
                    <button
                        onClick={() => removeFilter(key, value)}
                        className="ml-0.5 rounded-full p-0.5 hover:bg-blue-200/50 transition-colors"
                        aria-label={`Remove ${label} filter`}
                    >
                        <X className="h-3 w-3" />
                    </button>
                </span>
            ))}
            <button
                onClick={clearAll}
                className="text-xs font-semibold text-slate-500 hover:text-slate-700 transition-colors ml-1"
            >
                Clear all
            </button>
        </div>
    );
}
