"use client";

import React from "react";
import Link from "next/link";
import { CalendarRange, RefreshCw } from "lucide-react";

import { getMonths, getYears } from "@/lib/frontend/apiClient";
import { branchPath, monthPath, yearPath } from "@/lib/frontend/routes";
import { sortNumericStringsDesc } from "@/lib/frontend/explorer/sorters";
import { formatMonthLabel } from "@/lib/frontend/explorer/formatters";
import { mapExplorerError } from "@/lib/frontend/explorer/errorMapping";
import { buildLoginUrl, LOGIN_REASONS } from "@/lib/frontend/authRedirect";
import { useExplorerQuery } from "@/lib/frontend/hooks/useExplorerQuery";
import { useDebouncedVisibility } from "@/lib/frontend/hooks/useDebouncedVisibility";
import { LOADING_UI_DELAY_MS } from "@/lib/frontend/ui/uxTimings";

import ExplorerBreadcrumbs from "@/components/explorer/breadcrumbs/ExplorerBreadcrumbs";
import ExplorerPageShell from "@/components/explorer/ExplorerPageShell";
import ExplorerSectionCard from "@/components/explorer/ExplorerSectionCard";
import ExplorerLoading from "@/components/explorer/states/ExplorerLoading";
import ExplorerEmpty from "@/components/explorer/states/ExplorerEmpty";
import ExplorerError from "@/components/explorer/states/ExplorerError";
import ExplorerNotFound from "@/components/explorer/states/ExplorerNotFound";

import ForbiddenView from "@/components/system/ForbiddenView";
import { Button } from "@/components/ui/button";

export default function MonthsExplorer({ branch, year }) {
	const monthsLoadFn = React.useCallback(
		() => getMonths(branch, year),
		[branch, year],
	);
	const monthsQuery = useExplorerQuery(monthsLoadFn, [monthsLoadFn]);

	const yearsLoadFn = React.useCallback(() => getYears(branch), [branch]);
	const yearsQuery = useExplorerQuery(yearsLoadFn, [yearsLoadFn]);

	const mapped = React.useMemo(
		() => mapExplorerError(monthsQuery.error),
		[monthsQuery.error],
	);

	const showLoadingUi = useDebouncedVisibility(
		monthsQuery.status === "loading",
		{
			delayMs: LOADING_UI_DELAY_MS,
			minVisibleMs: 0,
		},
	);

	React.useEffect(() => {
		if (mapped?.kind !== "unauthenticated") return;

		const next =
			typeof window !== "undefined"
				? `${window.location.pathname}${window.location.search}`
				: yearPath(branch, year);

		window.location.replace(
			buildLoginUrl({ reason: LOGIN_REASONS.EXPIRED, next }),
		);
	}, [mapped?.kind, branch, year]);

	const yearOptions =
		yearsQuery.status === "success" && Array.isArray(yearsQuery.data?.years)
			? yearsQuery.data.years
			: null;

	const breadcrumbsNode = (
		<ExplorerBreadcrumbs
			branch={branch}
			year={year}
			yearOptions={yearOptions}
		/>
	);

	const actions = (
		<Button
			variant="outline"
			size="sm"
			onClick={() => {
				monthsQuery.retry();
				yearsQuery.retry();
			}}
			title="Aktualisieren"
		>
			<RefreshCw className="h-4 w-4" />
			Aktualisieren
		</Button>
	);

	if (showLoadingUi) {
		return (
			<ExplorerPageShell
				title="Monate"
				description="Wählen Sie einen Monat aus."
				breadcrumbs={breadcrumbsNode}
				actions={actions}
			>
				<ExplorerSectionCard
					title="Verfügbare Monate"
					description={`Jahr ${year}`}
				>
					<ExplorerLoading variant="grid" count={12} />
				</ExplorerSectionCard>
			</ExplorerPageShell>
		);
	}

	if (monthsQuery.status === "loading") {
		return (
			<ExplorerPageShell
				title="Monate"
				description="Wählen Sie einen Monat aus."
				breadcrumbs={breadcrumbsNode}
				actions={actions}
			>
				<div className="h-16" aria-hidden="true" />
			</ExplorerPageShell>
		);
	}

	if (monthsQuery.status === "error" && mapped) {
		if (mapped.kind === "forbidden")
			return <ForbiddenView attemptedBranch={branch} />;

		if (mapped.kind === "notfound") {
			return (
				<ExplorerPageShell
					title="Monate"
					description="Wählen Sie einen Monat aus."
					breadcrumbs={breadcrumbsNode}
					actions={actions}
				>
					<ExplorerNotFound
						upHref={branchPath(branch)}
						branchRootHref={branchPath(branch)}
					/>
				</ExplorerPageShell>
			);
		}

		if (mapped.kind === "unauthenticated") {
			return (
				<ExplorerPageShell
					title="Monate"
					description="Sitzung abgelaufen — Weiterleitung zum Login…"
					breadcrumbs={breadcrumbsNode}
				>
					<div className="h-16" aria-hidden="true" />
				</ExplorerPageShell>
			);
		}

		return (
			<ExplorerPageShell
				title="Monate"
				description="Wählen Sie einen Monat aus."
				breadcrumbs={breadcrumbsNode}
				actions={actions}
			>
				<ExplorerSectionCard
					title="Verfügbare Monate"
					description={`Jahr ${year}`}
				>
					<ExplorerError
						title={mapped.title}
						description={mapped.description}
						onRetry={monthsQuery.retry}
					/>
				</ExplorerSectionCard>
			</ExplorerPageShell>
		);
	}

	const months = Array.isArray(monthsQuery.data?.months)
		? monthsQuery.data.months
		: [];
	const sorted = sortNumericStringsDesc(months);

	return (
		<ExplorerPageShell
			title="Monate"
			description="Wählen Sie einen Monat aus."
			breadcrumbs={breadcrumbsNode}
			actions={actions}
		>
			<ExplorerSectionCard
				title="Verfügbare Monate"
				description={`Niederlassung ${branch} • Jahr ${year}`}
				headerRight={
					<span className="rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground">
						{sorted.length} Monat{sorted.length === 1 ? "" : "e"}
					</span>
				}
			>
				{sorted.length === 0 ? (
					<ExplorerEmpty
						title="Keine Monate gefunden"
						description="Für dieses Jahr wurden keine Monate gefunden."
						upHref={branchPath(branch)}
					/>
				) : (
					<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4">
						{sorted.map((m) => (
							<Button
								key={m}
								variant="outline"
								className="w-full justify-start"
								asChild
							>
								<Link href={monthPath(branch, year, m)}>
									<CalendarRange className="h-4 w-4" />
									<span className="truncate">{formatMonthLabel(m)}</span>
								</Link>
							</Button>
						))}
					</div>
				)}
			</ExplorerSectionCard>
		</ExplorerPageShell>
	);
}
