"use client";

import { useState, useCallback } from "react";
import { SlidersHorizontal, X, ChevronDown, ChevronUp, Search, Tag } from "lucide-react";

export interface PipelineFilters {
    stages: string[];        // stage IDs
    scoreMin: number | null;
    scoreMax: number | null;
    daysInStageMin: number | null;
    daysInStageMax: number | null;
    tags: string[];           // tag names
    applicationDateRange: "all" | "today" | "week" | "month" | "quarter";
    source: string | null;
    workPreference: string | null;
}

export const DEFAULT_FILTERS: PipelineFilters = {
    stages: [],
    scoreMin: null,
    scoreMax: null,
    daysInStageMin: null,
    daysInStageMax: null,
    tags: [],
    applicationDateRange: "all",
    source: null,
    workPreference: null,
};

interface Stage {
    id: string;
    name: string;
    color: string;
}

interface AvailableTag {
    id: string;
    name: string;
    color: string;
}

interface PipelineFilterPanelProps {
    stages: Stage[];
    availableTags: AvailableTag[];
    filters: PipelineFilters;
    totalCount: number;
    filteredCount: number;
    onChange: (filters: PipelineFilters) => void;
    onClear: () => void;
}

function AccordionSection({ title, children, defaultOpen = false }: { title: string; children: React.ReactNode; defaultOpen?: boolean }) {
    const [open, setOpen] = useState(defaultOpen);
    return (
        <div className="border-b border-slate-100 last:border-b-0">
            <button onClick={() => setOpen(!open)} className="w-full flex items-center justify-between py-3 px-1 text-xs font-bold text-slate-600 uppercase tracking-wider hover:text-slate-800 transition-colors">
                {title}
                {open ? <ChevronUp className="w-3.5 h-3.5 text-slate-400" /> : <ChevronDown className="w-3.5 h-3.5 text-slate-400" />}
            </button>
            {open && <div className="pb-3 space-y-2">{children}</div>}
        </div>
    );
}

export function PipelineFilterPanel({ stages, availableTags, filters, totalCount, filteredCount, onChange, onClear }: PipelineFilterPanelProps) {
    const [tagSearch, setTagSearch] = useState("");
    const activeFilterCount = [
        filters.stages.length > 0,
        filters.scoreMin !== null || filters.scoreMax !== null,
        filters.daysInStageMin !== null || filters.daysInStageMax !== null,
        filters.tags.length > 0,
        filters.applicationDateRange !== "all",
        filters.source !== null,
        filters.workPreference !== null,
    ].filter(Boolean).length;

    const update = useCallback(<K extends keyof PipelineFilters>(key: K, value: PipelineFilters[K]) => {
        onChange({ ...filters, [key]: value });
    }, [filters, onChange]);

    const toggleStage = (id: string) => {
        const next = filters.stages.includes(id) ? filters.stages.filter(s => s !== id) : [...filters.stages, id];
        update("stages", next);
    };

    const toggleTag = (name: string) => {
        const next = filters.tags.includes(name) ? filters.tags.filter(t => t !== name) : [...filters.tags, name];
        update("tags", next);
    };

    const filteredTags = availableTags.filter(t => t.name.toLowerCase().includes(tagSearch.toLowerCase()));

    return (
        <div className="w-64 flex-shrink-0 bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-slate-100">
                <div className="flex items-center gap-2">
                    <SlidersHorizontal className="w-4 h-4 text-primary" />
                    <span className="text-sm font-bold text-slate-800">Filters</span>
                    {activeFilterCount > 0 && (
                        <span className="w-5 h-5 bg-primary text-white text-xs rounded-full flex items-center justify-center font-bold">
                            {activeFilterCount}
                        </span>
                    )}
                </div>
                {activeFilterCount > 0 && (
                    <button onClick={onClear} className="text-xs text-red-500 font-bold hover:text-red-700 transition-colors">Clear all</button>
                )}
            </div>

            {/* Results count */}
            <div className="px-4 py-2.5 bg-slate-50 border-b border-slate-100">
                <p className="text-xs text-slate-500">
                    Showing <span className="font-bold text-slate-800">{filteredCount}</span> of <span className="font-bold text-slate-800">{totalCount}</span> candidates
                </p>
            </div>

            <div className="p-4 overflow-y-auto max-h-[calc(100vh-280px)] space-y-1">
                {/* Stages */}
                <AccordionSection title="Stage" defaultOpen>
                    <div className="space-y-1">
                        {stages.map(stage => (
                            <label key={stage.id} className="flex items-center gap-2 p-1.5 rounded-lg hover:bg-slate-50 cursor-pointer">
                                <input
                                    type="checkbox"
                                    checked={filters.stages.includes(stage.id)}
                                    onChange={() => toggleStage(stage.id)}
                                    className="w-3.5 h-3.5 rounded accent-primary"
                                />
                                <span className="w-2.5 h-2.5 rounded-full flex-shrink-0" style={{ backgroundColor: stage.color }} />
                                <span className="text-xs text-slate-700 font-medium">{stage.name}</span>
                            </label>
                        ))}
                    </div>
                </AccordionSection>

                {/* Score range */}
                <AccordionSection title="Match Score">
                    <div className="flex items-center gap-2">
                        <input
                            type="number" min={0} max={100}
                            value={filters.scoreMin ?? ""}
                            onChange={e => update("scoreMin", e.target.value ? parseInt(e.target.value) : null)}
                            placeholder="Min"
                            className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                        />
                        <span className="text-slate-400 text-xs">—</span>
                        <input
                            type="number" min={0} max={100}
                            value={filters.scoreMax ?? ""}
                            onChange={e => update("scoreMax", e.target.value ? parseInt(e.target.value) : null)}
                            placeholder="Max"
                            className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                        />
                    </div>
                    <div className="flex gap-1.5 flex-wrap mt-2">
                        {[{ label: "Top 80+", min: 80, max: 100 }, { label: "High 60+", min: 60, max: 79 }, { label: "Medium", min: 40, max: 59 }].map(p => (
                            <button key={p.label} onClick={() => onChange({ ...filters, scoreMin: p.min, scoreMax: p.max })}
                                className={`px-2 py-1 text-xs rounded-lg font-medium transition-colors ${filters.scoreMin === p.min && filters.scoreMax === p.max ? "bg-primary text-white" : "bg-slate-100 text-slate-600 hover:bg-slate-200"}`}>
                                {p.label}
                            </button>
                        ))}
                    </div>
                </AccordionSection>

                {/* Days in stage */}
                <AccordionSection title="Time in Stage">
                    <div className="flex gap-1.5 flex-wrap">
                        {[{ label: "< 3 days", max: 3 }, { label: "3–7 days", min: 3, max: 7 }, { label: "> 7 days", min: 7 }, { label: "Overdue", min: 14 }].map(p => (
                            <button key={p.label}
                                onClick={() => onChange({ ...filters, daysInStageMin: p.min ?? null, daysInStageMax: p.max ?? null })}
                                className={`px-2 py-1 text-xs rounded-lg font-medium transition-colors ${filters.daysInStageMin === (p.min ?? null) && filters.daysInStageMax === (p.max ?? null) ? "bg-amber-500 text-white" : "bg-slate-100 text-slate-600 hover:bg-slate-200"}`}>
                                {p.label}
                            </button>
                        ))}
                    </div>
                </AccordionSection>

                {/* Tags */}
                <AccordionSection title="Tags">
                    <div className="relative mb-2">
                        <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-slate-400" />
                        <input
                            value={tagSearch}
                            onChange={e => setTagSearch(e.target.value)}
                            placeholder="Search tags..."
                            className="w-full pl-6 pr-2 py-1.5 text-xs border border-slate-200 rounded-lg outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                        />
                    </div>
                    <div className="flex flex-wrap gap-1.5 max-h-32 overflow-y-auto">
                        {filteredTags.map(tag => (
                            <button key={tag.id}
                                onClick={() => toggleTag(tag.name)}
                                className={`flex items-center gap-1 px-2 py-1 text-xs rounded-full font-medium transition-all border ${filters.tags.includes(tag.name) ? "text-white border-transparent" : "text-slate-700 border-slate-200 hover:border-slate-300"}`}
                                style={filters.tags.includes(tag.name) ? { backgroundColor: tag.color, borderColor: tag.color } : {}}
                            >
                                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: tag.color }} />
                                {tag.name}
                                {filters.tags.includes(tag.name) && <X className="w-2.5 h-2.5 ml-0.5" />}
                            </button>
                        ))}
                        {filteredTags.length === 0 && <p className="text-xs text-slate-400">No tags found</p>}
                    </div>
                </AccordionSection>

                {/* Date Applied */}
                <AccordionSection title="Application Date">
                    <div className="space-y-1">
                        {([
                            ["all", "All time"],
                            ["today", "Today"],
                            ["week", "Last 7 days"],
                            ["month", "Last 30 days"],
                            ["quarter", "Last 90 days"],
                        ] as const).map(([val, label]) => (
                            <label key={val} className="flex items-center gap-2 p-1.5 rounded-lg hover:bg-slate-50 cursor-pointer">
                                <input type="radio" name="dateRange" value={val} checked={filters.applicationDateRange === val} onChange={() => update("applicationDateRange", val)} className="w-3.5 h-3.5 accent-primary" />
                                <span className="text-xs text-slate-700 font-medium">{label}</span>
                            </label>
                        ))}
                    </div>
                </AccordionSection>

                {/* Source */}
                <AccordionSection title="Application Source">
                    <select
                        value={filters.source ?? ""}
                        onChange={e => update("source", e.target.value || null)}
                        className="w-full px-2 py-1.5 text-xs border border-slate-200 rounded-lg outline-none bg-white focus:ring-2 focus:ring-primary/30 focus:border-primary"
                    >
                        <option value="">All sources</option>
                        <option value="platform">Platform</option>
                        <option value="linkedin">LinkedIn</option>
                        <option value="referral">Employee Referral</option>
                        <option value="agency">Agency</option>
                        <option value="direct">Direct</option>
                    </select>
                </AccordionSection>

                {/* Work Preference */}
                <AccordionSection title="Work Preference">
                    <div className="flex flex-wrap gap-1.5">
                        {[["remote", "Remote"], ["hybrid", "Hybrid"], ["onsite", "On-site"]].map(([val, label]) => (
                            <button key={val}
                                onClick={() => update("workPreference", filters.workPreference === val ? null : val)}
                                className={`px-3 py-1.5 text-xs rounded-lg font-medium transition-colors border ${filters.workPreference === val ? "bg-primary text-white border-primary" : "bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`}
                            >
                                {label}
                            </button>
                        ))}
                    </div>
                </AccordionSection>
            </div>
        </div>
    );
}
