"use client";

import { useState, useTransition } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import {
    MessageSquare, Search, Star, Archive, Filter, Inbox,
    Mail, MailOpen, ChevronDown, MoreHorizontal, Clock,
    Briefcase, ArrowUpDown
} from "lucide-react";
import { ConversationSummary, toggleConversationStar, toggleConversationArchive } from "@/app/actions/conversationActions";

interface MessagesClientProps {
    conversations: ConversationSummary[];
    currentUserId: string;
    currentUserRole: string;
    initialFilter: string;
    initialSearch: string;
    initialSort: string;
}

const filterTabs = [
    { id: "all", label: "All Messages", icon: Inbox },
    { id: "unread", label: "Unread", icon: Mail },
    { id: "starred", label: "Starred", icon: Star },
    { id: "archived", label: "Archived", icon: Archive },
];

const sortOptions = [
    { id: "recent", label: "Most Recent" },
    { id: "unread_first", label: "Unread First" },
    { id: "starred_first", label: "Starred First" },
    { id: "alphabetical", label: "Alphabetical" },
];

const statusColors: Record<string, string> = {
    pending: "bg-amber-100 text-amber-700",
    reviewing: "bg-blue-100 text-blue-700",
    interview: "bg-purple-100 text-purple-700",
    offered: "bg-emerald-100 text-emerald-700",
    hired: "bg-emerald-200 text-emerald-800",
    rejected: "bg-red-100 text-red-700",
};

function timeAgo(dateStr: string): string {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMin = Math.floor(diffMs / 60000);
    const diffHr = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHr / 24);

    if (diffMin < 1) return "Just now";
    if (diffMin < 60) return `${diffMin}m ago`;
    if (diffHr < 24) return `${diffHr}h ago`;
    if (diffDay < 7) return `${diffDay}d ago`;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

export function MessagesClient({
    conversations,
    currentUserId,
    currentUserRole,
    initialFilter,
    initialSearch,
    initialSort,
}: MessagesClientProps) {
    const router = useRouter();
    const [activeFilter, setActiveFilter] = useState(initialFilter);
    const [search, setSearch] = useState(initialSearch);
    const [sort, setSort] = useState(initialSort);
    const [showSort, setShowSort] = useState(false);
    const [isPending, startTransition] = useTransition();

    const updateParams = (filter: string, searchVal: string, sortVal: string) => {
        const params = new URLSearchParams();
        if (filter !== "all") params.set("filter", filter);
        if (searchVal) params.set("search", searchVal);
        if (sortVal !== "recent") params.set("sort", sortVal);
        const qs = params.toString();
        startTransition(() => {
            router.push(`/dashboard/messages${qs ? `?${qs}` : ""}`);
        });
    };

    const handleFilterChange = (filter: string) => {
        setActiveFilter(filter);
        updateParams(filter, search, sort);
    };

    const handleSearch = (val: string) => {
        setSearch(val);
        // Debounce search via timeout
        clearTimeout((window as any).__msgSearchTimer);
        (window as any).__msgSearchTimer = setTimeout(() => {
            updateParams(activeFilter, val, sort);
        }, 400);
    };

    const handleSort = (s: string) => {
        setSort(s);
        setShowSort(false);
        updateParams(activeFilter, search, s);
    };

    const handleStar = async (e: React.MouseEvent, applicationId: string) => {
        e.preventDefault();
        e.stopPropagation();
        await toggleConversationStar(applicationId);
        router.refresh();
    };

    const handleArchive = async (e: React.MouseEvent, applicationId: string) => {
        e.preventDefault();
        e.stopPropagation();
        await toggleConversationArchive(applicationId);
        router.refresh();
    };

    const totalUnread = conversations.reduce((sum, c) => sum + c.unreadCount, 0);

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900 flex items-center gap-3">
                        <div className="p-2 rounded-xl bg-gradient-to-br from-primary/10 to-blue-50">
                            <MessageSquare className="h-7 w-7 text-primary" />
                        </div>
                        Messages
                        {totalUnread > 0 && (
                            <span className="ml-2 px-2.5 py-0.5 text-sm font-bold bg-red-500 text-white rounded-full">
                                {totalUnread}
                            </span>
                        )}
                    </h1>
                    <p className="text-slate-500 mt-1">
                        {conversations.length} conversation{conversations.length !== 1 ? "s" : ""}
                        {totalUnread > 0 && ` · ${totalUnread} unread`}
                    </p>
                </div>
            </div>

            {/* Filter Tabs */}
            <div className="flex items-center gap-1 p-1 bg-slate-100 rounded-xl w-fit">
                {filterTabs.map((tab) => {
                    const Icon = tab.icon;
                    return (
                        <button
                            key={tab.id}
                            onClick={() => handleFilterChange(tab.id)}
                            className={`flex items-center gap-1.5 px-3 py-2 text-sm font-semibold rounded-lg transition-all ${activeFilter === tab.id
                                    ? "bg-white text-primary shadow-sm"
                                    : "text-slate-500 hover:text-slate-700"
                                }`}
                        >
                            <Icon className="w-4 h-4" />
                            {tab.label}
                        </button>
                    );
                })}
            </div>

            {/* Search + Sort Row */}
            <div className="flex gap-3">
                <div className="relative flex-1">
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-4.5 w-4.5 text-slate-400" />
                    <input
                        type="text"
                        value={search}
                        onChange={(e) => handleSearch(e.target.value)}
                        placeholder="Search conversations by name, job title, or message content..."
                        className="w-full pl-11 pr-4 py-2.5 rounded-xl border border-slate-200 outline-none focus:border-primary focus:ring-2 focus:ring-primary/10 transition-all text-sm"
                    />
                </div>
                <div className="relative">
                    <button
                        onClick={() => setShowSort(!showSort)}
                        className="flex items-center gap-2 px-4 py-2.5 rounded-xl border border-slate-200 text-sm font-medium text-slate-600 hover:bg-slate-50 transition-colors"
                    >
                        <ArrowUpDown className="w-4 h-4" />
                        Sort
                        <ChevronDown className="w-3.5 h-3.5" />
                    </button>
                    {showSort && (
                        <div className="absolute right-0 top-full mt-1 w-48 bg-white rounded-xl shadow-lg border border-slate-100 z-20 py-1">
                            {sortOptions.map((opt) => (
                                <button
                                    key={opt.id}
                                    onClick={() => handleSort(opt.id)}
                                    className={`w-full text-left px-4 py-2 text-sm transition-colors ${sort === opt.id
                                            ? "bg-primary/5 text-primary font-semibold"
                                            : "text-slate-600 hover:bg-slate-50"
                                        }`}
                                >
                                    {opt.label}
                                </button>
                            ))}
                        </div>
                    )}
                </div>
            </div>

            {/* Loading overlay */}
            {isPending && (
                <div className="flex items-center justify-center py-4">
                    <div className="w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                    <span className="ml-2 text-sm text-slate-500">Loading...</span>
                </div>
            )}

            {/* Conversation List */}
            {conversations.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-20 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50/50">
                    <div className="p-4 rounded-2xl bg-slate-100 mb-4">
                        <MessageSquare className="h-10 w-10 text-slate-300" />
                    </div>
                    <h3 className="text-lg font-bold text-slate-800">
                        {activeFilter === "unread" ? "No unread messages" :
                            activeFilter === "starred" ? "No starred conversations" :
                                activeFilter === "archived" ? "No archived conversations" :
                                    search ? "No conversations match your search" :
                                        "No messages yet"}
                    </h3>
                    <p className="text-sm text-slate-500 mt-2 max-w-sm text-center">
                        {search
                            ? "Try a different search term."
                            : currentUserRole === "candidate"
                                ? "Messages from employers will appear here when they reach out regarding your applications."
                                : "Start conversations with candidates by reviewing their applications."}
                    </p>
                    {!search && (
                        <Link
                            href={currentUserRole === "candidate" ? "/jobs" : "/dashboard/applications"}
                            className="mt-5 px-5 py-2.5 bg-primary text-white rounded-xl font-semibold text-sm hover:bg-primary/90 transition-colors shadow-sm"
                        >
                            {currentUserRole === "candidate" ? "Browse Jobs" : "View Applications"}
                        </Link>
                    )}
                </div>
            ) : (
                <div className="space-y-2">
                    {conversations.map((conv) => (
                        <Link
                            key={conv.applicationId}
                            href={`/dashboard/messages/${conv.applicationId}`}
                            className={`group block rounded-xl transition-all border ${conv.unreadCount > 0
                                    ? "bg-blue-50/50 border-primary/20 hover:border-primary/40 shadow-sm"
                                    : "bg-white border-slate-100 hover:border-slate-200 hover:shadow-sm"
                                }`}
                        >
                            <div className="flex items-start gap-3.5 p-4">
                                {/* Unread indicator bar */}
                                {conv.unreadCount > 0 && (
                                    <div className="w-1 self-stretch rounded-full bg-primary -ml-1 mr-0.5 shrink-0" />
                                )}

                                {/* Avatar */}
                                <div className="relative shrink-0">
                                    {conv.otherUser.avatar_url ? (
                                        <img
                                            src={conv.otherUser.avatar_url}
                                            alt={conv.otherUser.name}
                                            className="w-12 h-12 rounded-full object-cover border-2 border-white shadow-sm"
                                        />
                                    ) : (
                                        <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold text-white text-sm shadow-sm ${conv.unreadCount > 0 ? "bg-primary" : "bg-slate-400"
                                            }`}>
                                            {(conv.otherUser.name || "?")[0]?.toUpperCase()}
                                        </div>
                                    )}
                                </div>

                                {/* Content */}
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center justify-between gap-2">
                                        <h3 className={`text-sm truncate ${conv.unreadCount > 0 ? "font-bold text-slate-900" : "font-semibold text-slate-700"
                                            }`}>
                                            {conv.otherUser.name}
                                        </h3>
                                        <div className="flex items-center gap-2 shrink-0">
                                            <span className="text-xs text-slate-400 flex items-center gap-1">
                                                <Clock className="w-3 h-3" />
                                                {timeAgo(conv.lastMessage.createdAt)}
                                            </span>
                                            {conv.unreadCount > 0 && (
                                                <span className="px-1.5 py-0.5 text-[10px] font-bold bg-red-500 text-white rounded-full min-w-[18px] text-center">
                                                    {conv.unreadCount}
                                                </span>
                                            )}
                                        </div>
                                    </div>

                                    <div className="flex items-center gap-2 mt-0.5">
                                        <span className="text-xs text-slate-500 flex items-center gap-1 truncate">
                                            <Briefcase className="w-3 h-3 shrink-0" />
                                            {conv.jobTitle}
                                        </span>
                                        <span className={`text-[10px] font-semibold px-1.5 py-0.5 rounded-full shrink-0 ${statusColors[conv.applicationStatus] || "bg-slate-100 text-slate-600"}`}>
                                            {conv.applicationStatus}
                                        </span>
                                    </div>

                                    <p className={`text-sm mt-1.5 line-clamp-1 ${conv.unreadCount > 0 ? "font-medium text-slate-700" : "text-slate-500"
                                        }`}>
                                        {conv.lastMessage.senderId === currentUserId && (
                                            <span className="text-slate-400">You: </span>
                                        )}
                                        {conv.lastMessage.content}
                                    </p>
                                </div>

                                {/* Actions */}
                                <div className="flex flex-col items-center gap-1.5 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <button
                                        onClick={(e) => handleStar(e, conv.applicationId)}
                                        className={`p-1.5 rounded-lg transition-colors ${conv.isStarred
                                                ? "text-amber-500 bg-amber-50"
                                                : "text-slate-300 hover:text-amber-500 hover:bg-amber-50"
                                            }`}
                                        title={conv.isStarred ? "Unstar" : "Star"}
                                    >
                                        <Star className="w-4 h-4" fill={conv.isStarred ? "currentColor" : "none"} />
                                    </button>
                                    <button
                                        onClick={(e) => handleArchive(e, conv.applicationId)}
                                        className="p-1.5 rounded-lg text-slate-300 hover:text-slate-600 hover:bg-slate-100 transition-colors"
                                        title={conv.isArchived ? "Unarchive" : "Archive"}
                                    >
                                        <Archive className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        </Link>
                    ))}
                </div>
            )}
        </div>
    );
}
