"use client"

import * as React from "react"
import { useGetLeadHistoryQuery } from "@/api/rtk/deals-api"
import {
    History,
    User,
    ChevronRight,
    Move,
    Plus,
    Pencil,
    Trash2,
    RotateCcw,
    Info,
    Search,
    Monitor,
    Globe,
    ShieldCheck
} from "lucide-react"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { UserAvatar } from "@/components/ui/user-avatar"
import { format } from "date-fns"
import { cn } from "@/lib/utils"
import { Loading } from "@/components/ui/loading"

export interface DealHistoryViewProps {
    dealId: string
}

const ACTION_ICONS = {
    CREATE: <Plus className="size-3.5" />,
    UPDATE: <Pencil className="size-3.5" />,
    MOVE: <Move className="size-3.5" />,
    DELETE: <Trash2 className="size-3.5" />,
    RESTORE: <RotateCcw className="size-3.5" />,
}

const ACTION_COLORS = {
    CREATE: "border-emerald-100 bg-emerald-50 text-emerald-700",
    UPDATE: "border-amber-100 bg-amber-50 text-amber-700",
    MOVE: "border-blue-100 bg-blue-50 text-blue-700",
    DELETE: "border-red-100 bg-red-50 text-red-700",
    RESTORE: "border-purple-100 bg-purple-50 text-purple-700",
}

export function DealHistoryView({ dealId }: DealHistoryViewProps) {
    const { data: history = [], isLoading, isError } = useGetLeadHistoryQuery(dealId)
    const [searchQuery, setSearchQuery] = React.useState("")

    const filteredHistory = React.useMemo(() => {
        if (!searchQuery.trim()) return history
        const q = searchQuery.toLowerCase()
        return history.filter(h =>
            h.actionType.toLowerCase().includes(q) ||
            h.userName.toLowerCase().includes(q) ||
            h.metadata?.stageName?.toLowerCase().includes(q)
        )
    }, [history, searchQuery])

    if (isLoading) {
        return (
            <Loading
                layout="section"
                className="h-64 animate-in fade-in"
                size="lg"
                spinnerClassName="text-[#6C63FF]"
                message="Loading audit history…"
            />
        )
    }

    if (isError) {
        return (
            <div className="p-8 rounded-2xl bg-red-50 border border-red-100 text-center animate-in zoom-in-95">
                <Info className="mx-auto size-10 text-red-400 mb-3" />
                <h3 className="font-semibold text-red-900">Failed to load history</h3>
                <p className="text-sm text-red-700 mt-1">There was an error connecting to the audit service.</p>
            </div>
        )
    }

    if (history.length === 0) {
        return (
            <div className="p-12 border-2 border-dashed border-gray-100 rounded-3xl text-center animate-in fade-in">
                <div className="size-16 rounded-full bg-gray-50 flex items-center justify-center mx-auto mb-4 border border-gray-100">
                    <History className="size-8 text-gray-300" />
                </div>
                <h3 className="text-lg font-semibold text-gray-900 font-['Lexend']">No History Found</h3>
                <p className="text-sm text-gray-500 mt-2 max-w-xs mx-auto">We couldn't find any audit logs for this lead. Changes will appear here as they happen.</p>
            </div>
        )
    }

    return (
        <div className="space-y-6 animate-in fade-in slide-in-from-bottom-4 duration-500">
            {/* Search and Filters */}
            <div className="relative group">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 size-4 text-gray-400 group-focus-within:text-[#6C63FF] transition-colors" />
                <input
                    type="search"
                    placeholder="Search history by user, action or stage..."
                    className="w-full pl-11 pr-4 py-3 rounded-2xl bg-gray-50/50 border border-gray-100/80 focus:bg-white focus:border-[#6C63FF]/30 focus:outline-none transition-all placeholder:text-gray-400 text-sm font-medium"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                />
            </div>

            <div className="flex flex-col gap-4">
                {filteredHistory.map((item, idx) => (
                    <Card key={item.id} className="p-0 border-none bg-white shadow-sm hover:shadow-md transition-all duration-300 rounded-3xl overflow-hidden group/card border border-gray-50">
                        <div className="flex">
                            {/* Color Strip */}
                            <div className={cn(
                                "w-1.5 shrink-0",
                                item.actionType === 'CREATE' && "bg-emerald-500",
                                item.actionType === 'UPDATE' && "bg-amber-500",
                                item.actionType === 'MOVE' && "bg-blue-500",
                                item.actionType === 'DELETE' && "bg-red-500",
                                item.actionType === 'RESTORE' && "bg-purple-500",
                            )} />

                            <div className="flex-1 p-5">
                                <div className="flex items-start justify-between gap-4">
                                    <div className="flex items-start gap-4">
                                        <div className="relative">
                                            <UserAvatar
                                                avatar={item.user?.profile?.avatar}
                                                name={item.userName}
                                                size="lg"
                                                className="border-2 border-white shadow-sm"
                                            />
                                            <div className={cn(
                                                "absolute -bottom-1 -right-1 size-6 rounded-full border-2 border-white flex items-center justify-center shadow-sm",
                                                ACTION_COLORS[item.actionType as keyof typeof ACTION_COLORS]
                                            )}>
                                                {ACTION_ICONS[item.actionType as keyof typeof ACTION_ICONS]}
                                            </div>
                                        </div>

                                        <div className="flex flex-col">
                                            <div className="flex items-center gap-2 flex-wrap">
                                                <span className="text-[15px] font-bold text-gray-900 font-['Lexend'] tracking-tight">
                                                    {item.userName}
                                                </span>
                                                <Badge variant="outline" className={cn("text-[10px] font-bold uppercase tracking-widest px-2 py-0.5 rounded-lg border-opacity-50", ACTION_COLORS[item.actionType as keyof typeof ACTION_COLORS])}>
                                                    {item.actionType}
                                                </Badge>
                                                {item.actionType === 'MOVE' && item.metadata?.stageName && (
                                                    <div className="flex items-center gap-2 text-blue-700 bg-blue-50 px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase tracking-widest border border-blue-100">
                                                        <span>To: {item.metadata.stageName}</span>
                                                    </div>
                                                )}
                                            </div>

                                            <div className="mt-1 flex items-center gap-3 text-[11px] text-gray-400 font-medium">
                                                <div className="flex items-center gap-1.5">
                                                    <History size={12} className="text-gray-300" />
                                                    {format(new Date(item.createdAt), "MMM d, yyyy · h:mm a")}
                                                </div>
                                                {item.ipAddress && (
                                                    <div className="flex items-center gap-1.5">
                                                        <Globe size={12} className="text-gray-300" />
                                                        {item.ipAddress}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    </div>

                                    <div className="text-right">
                                        <div className="flex flex-col items-end gap-1 opacity-0 group-hover/card:opacity-100 transition-opacity">
                                            {item.userAgent && (
                                                <div className="px-2 py-1 bg-gray-50 rounded-lg text-[9px] text-gray-400 font-mono max-w-[150px] truncate" title={item.userAgent}>
                                                    {item.userAgent}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Detailed Changes (Simplified view for MVP) */}
                                {item.actionType === 'UPDATE' && item.beforeState && item.afterState && (
                                    <div className="mt-4 p-4 rounded-2xl bg-gray-50/50 border border-gray-100/80 space-y-3">
                                        <div className="flex items-center gap-2 text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-2">
                                            <Info size={12} className="text-[#6C63FF]/60" />
                                            State Changes Recorded
                                        </div>
                                        <p className="text-[12px] text-gray-500 font-medium leading-relaxed italic">
                                            A granular snapshot was captured. Full diffing will be available in future releases.
                                        </p>
                                    </div>
                                )}

                                {item.actionType === 'CREATE' && (
                                    <div className="mt-4 p-4 rounded-2xl bg-emerald-50/30 border border-emerald-100/50">
                                        <p className="text-[12px] text-emerald-700 font-medium leading-relaxed">
                                            Initialized lead with all required BANT metrics and contact information.
                                        </p>
                                    </div>
                                )}
                            </div>
                        </div>
                    </Card>
                ))}
            </div>

        </div>
    )
}
