import React, { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import Board from "./Board";
import BoardTabs, { type ViewMode } from "./BoardTabs";
import DependencyViewD3 from "./DependencyViewD3";
import DependencyFilters from "./DependencyFilters";
import type { Task } from "../../types";
import type { GraphFilters } from "../types/graph";

interface BoardPageProps {
	onEditTask: (task: Task) => void;
	onNewTask: () => void;
	tasks: Task[];
	onRefreshData?: () => Promise<void>;
	statuses: string[];
	isLoading: boolean;
}

export default function BoardPage({
	onEditTask,
	onNewTask,
	tasks,
	onRefreshData,
	statuses,
	isLoading,
}: BoardPageProps) {
	const [searchParams, setSearchParams] = useSearchParams();
	const [highlightTaskId, setHighlightTaskId] = useState<string | null>(null);

	// View mode state (synced with URL)
	const [activeView, setActiveView] = useState<ViewMode>(
		(searchParams.get("view") as ViewMode) || "kanban",
	);

	// Filter state for dependency view
	const [filters, setFilters] = useState<GraphFilters>({
		showCompleted: false,
	});

	// Collect unique labels from all tasks
	const availableLabels = [...new Set(tasks.flatMap((t) => t.labels || []))];

	// Sync view mode to URL
	useEffect(() => {
		setSearchParams(
			(params) => {
				if (activeView === "kanban") {
					params.delete("view");
				} else {
					params.set("view", activeView);
				}
				return params;
			},
			{ replace: true },
		);
	}, [activeView, setSearchParams]);

	// Handle highlight parameter from URL
	useEffect(() => {
		const highlight = searchParams.get("highlight");
		if (highlight) {
			setHighlightTaskId(highlight);
			// Clear the highlight parameter after setting it
			setSearchParams(
				(params) => {
					params.delete("highlight");
					return params;
				},
				{ replace: true },
			);
		}
	}, [searchParams, setSearchParams]);

	// Handle view change
	const handleViewChange = (view: ViewMode) => {
		setActiveView(view);
	};

	// Clear highlight after it's been used
	const handleEditTask = (task: Task) => {
		setHighlightTaskId(null); // Clear highlight so popup doesn't reopen
		onEditTask(task);
	};

	return (
		<div className="container mx-auto px-4 py-8 transition-colors duration-200">
			{/* Tab Navigation */}
			<BoardTabs activeView={activeView} onViewChange={handleViewChange} />

			{/* View Content */}
			{activeView === "kanban" ? (
				<Board
					onEditTask={handleEditTask}
					onNewTask={onNewTask}
					highlightTaskId={highlightTaskId}
					tasks={tasks}
					onRefreshData={onRefreshData}
					statuses={statuses}
					isLoading={isLoading}
				/>
			) : (
				<div className="space-y-4">
					{/* Header with filters */}
					<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
						<h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Dependency Graph</h2>
						<DependencyFilters
							filters={filters}
							onChange={setFilters}
							statuses={statuses}
							availableLabels={availableLabels}
						/>
					</div>

					{/* Dependency Visualization (D3.js) */}
					<DependencyViewD3 tasks={tasks} onEditTask={handleEditTask} filters={filters} />
				</div>
			)}
		</div>
	);
}
