"use client"

import { useMemo } from "react"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { DashboardPeriods, type DashboardPeriod } from "@garage/api"
import { Input } from "@/shared/components/ui/input"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/shared/components/ui/select"

const DEFAULT_PERIOD: DashboardPeriod = "this_month"

const PERIOD_LABELS: Record<DashboardPeriod, string> = {
    today: "Today",
    yesterday: "Yesterday",
    this_week: "This Week",
    this_month: "This Month",
    last_month: "Last Month",
    last_3_months: "Last 3 Months",
    last_6_months: "Last 6 Months",
    last_year: "Last Year",
    year_to_date: "Year to Date",
    all_time: "All Time",
    custom: "Custom",
}

function isDashboardPeriod(value: string | null): value is DashboardPeriod {
    return Boolean(value && (DashboardPeriods as readonly string[]).includes(value))
}

export function DashboardFiltersToolbar() {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()

    const period = useMemo<DashboardPeriod>(() => {
        const value = searchParams.get("period")
        return isDashboardPeriod(value) ? value : DEFAULT_PERIOD
    }, [searchParams])

    const startDate = searchParams.get("start_date") ?? ""
    const endDate = searchParams.get("end_date") ?? ""

    const updateParams = (updates: Record<string, string | null>) => {
        const params = new URLSearchParams(searchParams.toString())

        Object.entries(updates).forEach(([key, value]) => {
            if (!value) {
                params.delete(key)
                return
            }
            params.set(key, value)
        })

        const query = params.toString()
        router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false })
    }

    return (
        <div className="flex flex-wrap items-end gap-2">
            <div className="w-44">
                <Select
                    value={period}
                    onValueChange={(value) => {
                        const nextPeriod = value as DashboardPeriod
                        updateParams({
                            period: nextPeriod,
                            start_date: nextPeriod === "custom" ? startDate || null : null,
                            end_date: nextPeriod === "custom" ? endDate || null : null,
                        })
                    }}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Period" />
                    </SelectTrigger>
                    <SelectContent>
                        {DashboardPeriods.map((value) => (
                            <SelectItem key={value} value={value}>
                                {PERIOD_LABELS[value]}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>

            {period === "custom" ? (
                <>
                    <div className="w-36">
                        <Input
                            type="date"
                            value={startDate}
                            onChange={(event) => {
                                updateParams({ start_date: event.target.value || null })
                            }}
                        />
                    </div>
                    <div className="w-36">
                        <Input
                            type="date"
                            value={endDate}
                            onChange={(event) => {
                                updateParams({ end_date: event.target.value || null })
                            }}
                        />
                    </div>
                </>
            ) : null}
        </div>
    )
}
