import { Metadata } from "next";
import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { Clock, Download, Search, Trash2, SlidersHorizontal } from "lucide-react";
import prisma from "@/lib/prisma";
import Link from "next/link";
import { formatDistanceToNow } from "date-fns";

export const metadata: Metadata = {
    title: "Search History | Jobzio",
};

export default async function SearchHistoryPage() {
    const user = await getCurrentUser();
    if (!user) redirect("/login");

    // Fetch history
    const history = await prisma.searchHistory.findMany({
        where: { user_id: user.id },
        orderBy: { created_at: "desc" },
        take: 50,
    });

    return (
        <div className="space-y-6 max-w-5xl mx-auto">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-slate-900">Search History</h1>
                    <p className="text-sm text-slate-500 mt-1">
                        Your recent job searches from the last 30 days
                    </p>
                </div>
                <div className="flex items-center gap-3">
                    <button className="flex items-center gap-2 rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors">
                        <Download className="h-4 w-4" />
                        Export
                    </button>
                    {/* The Clear History action would be wired up to a client component button */}
                    <button className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-semibold text-red-700 hover:bg-red-100 transition-colors">
                        <Trash2 className="h-4 w-4" />
                        Clear All
                    </button>
                </div>
            </div>

            <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
                {history.length === 0 ? (
                    <div className="p-12 text-center">
                        <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-slate-50 mb-4">
                            <Clock className="h-8 w-8 text-slate-400" />
                        </div>
                        <h3 className="text-lg font-bold text-slate-900 mb-1">No search history</h3>
                        <p className="text-sm text-slate-500 mb-5 max-w-sm mx-auto">
                            Searches you make on the job board will appear here for 30 days.
                        </p>
                        <Link
                            href="/jobs"
                            className="inline-flex items-center gap-2 rounded-xl bg-blue-600 px-6 py-2.5 text-sm font-bold text-white hover:bg-blue-700 transition-colors shadow-sm"
                        >
                            <Search className="h-4 w-4" /> Go to Job Search
                        </Link>
                    </div>
                ) : (
                    <div className="divide-y divide-slate-100">
                        {history.map((item) => {
                            const filters = item.filters ? (item.filters as Record<string, any>) : {};
                            const filterKeys = Object.keys(filters).filter(k => k !== "q");

                            // Reconstruct the URL params to allow re-running the search
                            const params = new URLSearchParams();
                            if (item.query) params.set("q", item.query);
                            Object.entries(filters).forEach(([k, v]) => {
                                if (v) params.set(k, String(v));
                            });

                            const searchUrl = `/jobs?${params.toString()}`;

                            return (
                                <div key={item.id} className="group flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-5 hover:bg-slate-50 transition-colors">
                                    <div className="flex items-start gap-4">
                                        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-blue-50">
                                            <Search className="h-5 w-5 text-blue-500" />
                                        </div>
                                        <div>
                                            <Link href={searchUrl} className="font-bold text-slate-900 hover:text-blue-600 transition-colors inline-block mb-1">
                                                {item.query || "All Jobs"}
                                            </Link>

                                            <div className="flex flex-wrap items-center gap-2 text-xs text-slate-500">
                                                <span className="flex items-center gap-1 font-medium bg-slate-100 px-2 py-0.5 rounded text-slate-600">
                                                    {item.results_count} results
                                                </span>
                                                <span>•</span>
                                                <span className="flex items-center gap-1" title={new Date(item.created_at).toLocaleString()}>
                                                    <Clock className="h-3 w-3" />
                                                    {formatDistanceToNow(new Date(item.created_at), { addSuffix: true })}
                                                </span>
                                            </div>

                                            {filterKeys.length > 0 && (
                                                <div className="mt-2 flex flex-wrap gap-1.5">
                                                    <span className="flex items-center gap-1 text-[10px] uppercase font-bold text-slate-400 mr-1">
                                                        <SlidersHorizontal className="h-3 w-3" /> Filters
                                                    </span>
                                                    {filterKeys.map(k => (
                                                        <span key={k} className="inline-flex rounded-md bg-blue-50 px-2 py-0.5 text-[10px] font-medium text-blue-700 border border-blue-100">
                                                            {k}: {String(filters[k])}
                                                        </span>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                    </div>

                                    <div className="sm:opacity-0 sm:group-hover:opacity-100 transition-opacity pl-14 sm:pl-0 flex items-center gap-2">
                                        <Link
                                            href={searchUrl}
                                            className="rounded-lg bg-white border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:border-slate-300 transition-all"
                                        >
                                            Search Again
                                        </Link>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}
            </div>

            {history.length > 0 && (
                <p className="text-center text-xs text-slate-400">
                    Showing your {Math.min(history.length, 50)} most recent searches from the last 30 days.
                </p>
            )}
        </div>
    );
}
