"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import {
    ArrowLeft, Phone, Mail, MapPin, User,
    CheckCircle2, MessageSquare,
    FileText, Bell, GitBranch, Activity,
    Search, CalendarRange, X, RotateCcw,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { KPICard } from "@/components/ui/kpi-card"
import { Input } from "@/components/ui/input"
import { DatePicker } from "@/components/ui/date-picker"
import { Label } from "@/components/ui/label"
import { cn } from "@/lib/utils"
import { Loading } from "@/components/ui/loading"
import { useGetBusinessDealQuery } from "@/api/rtk/business-deals-api"
import type { BusinessDealRecord } from "@/api/rtk/business-deals-api"
import { useGetDealQuery, type Deal } from "@/api/rtk/deals-api"
import {
    useGetActivitiesByBusinessDealQuery,
    useGetActivitiesByDealQuery,
} from "@/api/rtk/activities-api"
import { useGetPipelineStagesQuery, useGetPipelinesQuery } from "@/api/rtk/pipelines-api"
import { useAuthToken } from "@/hooks/use-auth-token"
import { buildStageNameMap, formatNotificationTextWithStageName } from "@/lib/notification-message"
import type { ApiActivityLog } from "@/api/rtk/activities-api"
import type { DealNote, DealTimelineEntry } from "@/api/rtk/deals-api"
import {
    ActivityTimelinePanel,
    type ActivityTimelineEvent,
} from "@/components/deals/activity-timeline-panel"

// ─── Helpers ──────────────────────────────────────────────────────────────────

const ACTIVITY_COLORS: Record<string, string> = {
    Call: "#6C63FF",
    Email: "#3b82f6",
    Meeting: "#10b981",
    Note: "#f59e0b",
    Deal: "#8b5cf6",
    Win: "#22c55e",
    default: "#94a3b8",
}

/** Local calendar YYYY-MM-DD for date-only filtering of ISO timestamps. */
function eventLocalYmd(iso: string): string {
    const d = new Date(iso)
    if (Number.isNaN(d.getTime())) return ""
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, "0")
    const day = String(d.getDate()).padStart(2, "0")
    return `${y}-${m}-${day}`
}

function activityIcon(type: string) {
    switch (type) {
        case "Call": return <Phone size={13} />
        case "Email": return <Mail size={13} />
        case "Meeting": return <User size={13} />
        case "Note": return <MessageSquare size={13} />
        case "Deal": return <GitBranch size={13} />
        case "Win": return <CheckCircle2 size={13} />
        default: return <Activity size={13} />
    }
}

export type DealTrackerContext = "lead" | "sales-deal"

function businessDealToTrackerDeal(b: BusinessDealRecord): Deal {
    const stageId = (b.pipelineSubStageId?.trim() || b.pipelineStageId?.trim() || "") as Deal["stage"]
    const pipelineId =
        (b.PipelineStage?.pipelineId ?? b.PipelineStage?.pipeline?.id ?? "") as Deal["pipelineId"]


    const customerName =
        b.title?.trim() ||
        b.linkedLead?.customerName?.trim() ||
        b.linkedCustomer?.fullName?.trim() ||
        b.linkedCustomer?.companyName?.trim() ||
        b.linkedCustomer?.customerName?.trim() ||
        "Business deal"
    return {
        id: b.id,
        stage: stageId,
        pipelineId,
        customerName,
        email: b.linkedLead?.email ?? b.linkedCustomer?.email ?? undefined,
        phone: b.linkedLead?.phone ?? b.linkedCustomer?.phone ?? undefined,
        homePhone: b.linkedLead?.homePhone ?? undefined,
        createdAt: b.createdAt,
        timeline: [],
        dealNotes: [],
        dealReminders: [],
        dealDocuments: [],
    }
}

// ─── Main Component ───────────────────────────────────────────────────────────

export function DealTracker({
    dealId,
    dealContext = "lead",
}: {
    dealId: string
    dealContext?: DealTrackerContext
}) {
    const router = useRouter()
    const { token } = useAuthToken()
    const listPath = dealContext === "sales-deal" ? "/sales-deals" : "/leads"
    const dealDetailPath = dealContext === "sales-deal" ? `/sales-deals/${dealId}` : `/leads/${dealId}`

    const isSalesDealBoard = dealContext === "sales-deal"
    const { data: leadDeal, isLoading: leadDealLoading } = useGetDealQuery(dealId, {
        skip: !token || isSalesDealBoard,
    })
    const { data: businessDeal, isLoading: businessDealLoading } = useGetBusinessDealQuery(dealId, {
        skip: !token || !isSalesDealBoard,
    })
    const deal = isSalesDealBoard
        ? businessDeal
            ? businessDealToTrackerDeal(businessDeal)
            : undefined
        : leadDeal
    const dealLoading = isSalesDealBoard ? businessDealLoading : leadDealLoading

    const [timelineSearch, setTimelineSearch] = React.useState("")
    const [timelineDate, setTimelineDate] = React.useState("")

    const leadActivitiesQueryArg = React.useMemo(
        () => ({
            dealId,
            ...(timelineDate.trim()
                ? {
                    date: timelineDate.trim(),
                    tzOffset: new Date().getTimezoneOffset(),
                }
                : {}),
        }),
        [dealId, timelineDate],
    )
    const businessActivitiesQueryArg = React.useMemo(
        () => ({
            businessDealId: dealId,
            ...(timelineDate.trim()
                ? {
                    date: timelineDate.trim(),
                    tzOffset: new Date().getTimezoneOffset(),
                }
                : {}),
        }),
        [dealId, timelineDate],
    )

    const { data: leadActivities = [], isLoading: leadActivitiesLoading } =
        useGetActivitiesByDealQuery(leadActivitiesQueryArg, {
            skip: !token || isSalesDealBoard,
        })
    const { data: businessActivities = [], isLoading: businessActivitiesLoading } =
        useGetActivitiesByBusinessDealQuery(businessActivitiesQueryArg, {
            skip: !token || !isSalesDealBoard,
        })
    const dealActivities = isSalesDealBoard ? businessActivities : leadActivities
    const activitiesLoading = isSalesDealBoard
        ? businessActivitiesLoading
        : leadActivitiesLoading

    const { data: stagesData, isLoading: stagesLoading } = useGetPipelineStagesQuery(
        { pipelineId: deal?.pipelineId ?? "", limit: 100 },
        { skip: !token || !deal?.pipelineId },
    )
    const { data: pipelines = [] } = useGetPipelinesQuery(undefined, {
        skip: !token,
    })

    const stageNameMap = React.useMemo(
        () =>
            buildStageNameMap(
                pipelines.flatMap((pipeline) =>
                    (pipeline.stages ?? []).map((stage) => ({
                        id: stage.id,
                        name: stage.name,
                        subStages: (stage.subStages ?? []).map((subStage) => ({
                            id: subStage.id,
                            name: subStage.name,
                        })),
                    })),
                ),
            ),
        [pipelines],
    )

    // Build unified timeline events
    const timelineEvents = React.useMemo((): ActivityTimelineEvent[] => {
        const events: ActivityTimelineEvent[] = []

        // Deal created
        const dealCreatedAt = (deal as unknown as { createdAt?: string })?.createdAt
        if (dealCreatedAt) {
            events.push({
                id: "created",
                type: "stage",
                title: "Deal created",
                description: deal?.customerName ? `Customer: ${deal.customerName}` : undefined,
                date: dealCreatedAt,
                color: "#6C63FF",
                icon: <GitBranch size={13} />,
            })
        }

        // Timeline entries (stage moves stored in deal.timeline JSONB)
        const timelineEntries: DealTimelineEntry[] = Array.isArray(deal?.timeline)
            ? (deal.timeline as DealTimelineEntry[])
            : []

        timelineEntries.forEach((entry) => {
            events.push({
                id: `tl-${entry.id}`,
                type: "timeline",
                title: formatNotificationTextWithStageName(entry.title, stageNameMap),
                description: entry.description ? formatNotificationTextWithStageName(entry.description, stageNameMap) : undefined,
                date: entry.createdAt ?? entry.date,
                author: entry.addedByName,
                color: "#8b5cf6",
                icon: <GitBranch size={13} />,
            })
        })

        // Activities
        dealActivities.forEach((act: ApiActivityLog) => {
            events.push({
                id: `act-${act.id}`,
                type: "activity",
                title: formatNotificationTextWithStageName(act.subject, stageNameMap),
                description: act.company ?? undefined,
                date: act.createdAt,
                author: act.user?.name,
                meta: act.type,
                color: ACTIVITY_COLORS[act.type] ?? ACTIVITY_COLORS.default,
                icon: activityIcon(act.type),
            })
        })

        // Notes
        const notes: DealNote[] = Array.isArray(deal?.dealNotes) ? deal.dealNotes : []
        notes.forEach((note) => {
            events.push({
                id: `note-${note.id}`,
                type: "note",
                title: "Note added",
                description: note.text?.replace(/<[^>]+>/g, "").slice(0, 200),
                date: note.createdAt,
                author: note.author?.name,
                color: "#f59e0b",
                icon: <MessageSquare size={13} />,
            })
        })

        // Reminders
        const reminders: Array<{ id: string; text: string; remindAt: string; isSent?: boolean; createdBy?: { name: string } }> =
            Array.isArray(deal?.dealReminders) ? deal.dealReminders : []
        reminders.forEach((r) => {
            events.push({
                id: `rem-${r.id}`,
                type: "reminder",
                title: `Reminder: ${r.text}`,
                date: r.remindAt,
                author: r.createdBy?.name,
                meta: r.isSent ? "Sent" : "Pending",
                color: r.isSent ? "#10b981" : "#f97316",
                icon: <Bell size={13} />,
            })
        })

        // Sort newest first
        return events.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    }, [deal, dealActivities, stageNameMap])

    const filteredTimelineEvents = React.useMemo(() => {
        const q = timelineSearch.trim().toLowerCase()
        const day = timelineDate.trim()
        return timelineEvents.filter((ev) => {
            if (q) {
                const hay = [ev.title, ev.description, ev.author, ev.meta]
                    .filter(Boolean)
                    .join(" ")
                    .toLowerCase()
                if (!hay.includes(q)) return false
            }
            if (day) {
                const ymd = eventLocalYmd(ev.date)
                if (!ymd || ymd !== day) return false
            }
            return true
        })
    }, [timelineEvents, timelineSearch, timelineDate])

    const timelineFiltersActive = Boolean(
        timelineSearch.trim() || timelineDate.trim(),
    )

    const clearTimelineFilters = React.useCallback(() => {
        setTimelineSearch("")
        setTimelineDate("")
    }, [])

    const trackerKpiItems = React.useMemo(
        () => [
            {
                key: "activities",
                label: "Activities",
                value: dealActivities.length,
                icon: <Activity className="size-3.5 text-[#6C63FF]" aria-hidden />,
            },
            {
                key: "notes",
                label: "Notes",
                value: deal?.dealNotes?.length ?? 0,
                icon: <MessageSquare className="size-3.5 text-amber-500" aria-hidden />,
            },
            {
                key: "reminders",
                label: "Reminders",
                value: deal?.dealReminders?.length ?? 0,
                icon: <Bell className="size-3.5 text-orange-500" aria-hidden />,
            },
            {
                key: "documents",
                label: "Documents",
                value: deal?.dealDocuments?.length ?? 0,
                icon: <FileText className="size-3.5 text-emerald-600" aria-hidden />,
            },
        ],
        [
            dealActivities.length,
            deal?.dealNotes?.length,
            deal?.dealReminders?.length,
            deal?.dealDocuments?.length,
        ],
    )

    const stages = stagesData?.data ?? []
    const currentStage = stages.find((s) => s.id === deal?.stage)
    const isLoading = dealLoading || stagesLoading

    if (isLoading) {
        return (
            <Loading
                layout="panel"
                className="h-full p-12"
                size="lg"
                spinnerClassName="text-gray-300"
            />
        )
    }

    if (!deal) {
        return (
            <div className="flex flex-col items-center justify-center h-full p-12 text-center">
                <p className="text-[14px] font-semibold text-gray-700">Deal not found</p>
                <div className="mt-3">
                    <Button variant="ghost" size="sm" onClick={() => router.push(listPath)}>
                        <ArrowLeft size={14} className="mr-1.5" />{" "}
                        {dealContext === "sales-deal" ? "Back to sales" : "Back to leads"}
                    </Button>
                </div>
            </div>
        )
    }

    return (
        <div className="flex h-full min-h-0 flex-col gap-5 overflow-y-auto p-2 md:p-4 scrollbar-themed animate-in fade-in duration-300">

            {/* Header */}
            <div className="flex shrink-0 items-center gap-3 rounded-2xl border border-white/40 bg-white/50 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] p-4">
                <Button
                    variant="ghostIconBack"
                    onClick={() => router.push(dealDetailPath)}
                    aria-label="Back to deal"
                >
                    <ArrowLeft size={16} />
                </Button>
                <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                        <h1 className="text-[18px] font-extrabold text-gray-900 font-['Lexend'] tracking-tight truncate">
                            {deal.customerName || "Unnamed Deal"}
                        </h1>
                        {currentStage && (
                            <Badge
                                className="text-[11px] text-white shrink-0"
                                style={{ backgroundColor: currentStage.color ?? "#6C63FF" }}
                            >
                                {currentStage.stageName}
                            </Badge>
                        )}
                    </div>
                    <div className="flex items-center gap-3 mt-1 flex-wrap">
                        {deal.email && (
                            <span className="flex items-center gap-1 text-[11px] text-gray-400">
                                <Mail size={10} /> {deal.email}
                            </span>
                        )}
                        {deal.phone && (
                            <span className="flex items-center gap-1 text-[11px] text-gray-400">
                                <Phone size={10} /> {deal.phone}
                            </span>
                        )}
                        {deal.homePhone && (
                            <span className="flex items-center gap-1 text-[11px] text-gray-400" title="Home phone">
                                <Phone size={10} /> {deal.homePhone}
                            </span>
                        )}
                        {deal.address && (
                            <span className="flex items-center gap-1 text-[11px] text-gray-400">
                                <MapPin size={10} /> {deal.address}
                            </span>
                        )}
                    </div>
                </div>
            </div>

            {/* Primary: activity — filters + timeline first */}
            <div className="flex min-h-0 flex-1 flex-col gap-3">
                <p className="sr-only">Deal activity and history</p>
                {/* Timeline filters */}
                <div className="shrink-0 rounded-2xl border border-white/40 bg-white/50 p-4 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] backdrop-blur-[15px]">
                    <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
                        <div className="flex items-center gap-2">
                            <CalendarRange size={15} className="shrink-0 text-accent" aria-hidden />
                            <h2 className="font-['Lexend'] text-[13px] font-bold text-gray-800">
                                Activity filters
                            </h2>
                        </div>
                        <Button
                            type="button"
                            variant="outlineTimelineClear"
                            disabled={!timelineFiltersActive}
                            onClick={clearTimelineFilters}
                        >
                            <RotateCcw size={13} className="shrink-0" aria-hidden />
                            Clear filters
                        </Button>
                    </div>
                    <div className="flex flex-col gap-3 lg:flex-row lg:items-end">
                        <div className="min-w-0 flex-1">
                            <Label htmlFor="deal-tracker-timeline-search" className="sr-only">
                                Search timeline
                            </Label>
                            <div className="relative">
                                <Search
                                    className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"
                                    aria-hidden
                                />
                                <Input
                                    id="deal-tracker-timeline-search"
                                    type="search"
                                    placeholder="Search title, notes, author, type…"
                                    value={timelineSearch}
                                    onChange={(e) => setTimelineSearch(e.target.value)}
                                    className={cn(
                                        "h-10 rounded-xl border-gray-200/90 bg-white shadow-sm hover:bg-white focus:bg-white",
                                        timelineSearch.trim() ? "pr-10 pl-9" : "pl-9",
                                    )}
                                    autoComplete="off"
                                />
                                {timelineSearch.trim() ? (
                                    <button
                                        type="button"
                                        className="absolute right-2 top-1/2 flex size-8 -translate-y-1/2 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-gray-100 hover:text-foreground"
                                        onClick={() => setTimelineSearch("")}
                                        aria-label="Clear search"
                                    >
                                        <X size={15} aria-hidden />
                                    </button>
                                ) : null}
                            </div>
                        </div>
                        <div className="grid w-full gap-1 sm:w-[min(100%,200px)] sm:shrink-0">
                            <Label
                                htmlFor="deal-tracker-date"
                                className="text-[10px] font-bold uppercase tracking-wide text-muted-foreground"
                            >
                                Date
                            </Label>
                            <DatePicker
                                value={timelineDate}
                                onChange={(date) => setTimelineDate(date || "")}
                                placeholder="Pick date"
                                className="h-10 rounded-xl"
                            />
                        </div>
                    </div>
                </div>

                <ActivityTimelinePanel
                    className="min-h-0 flex-1"
                    fillHeight
                    events={filteredTimelineEvents}
                    isLoading={activitiesLoading}
                    countLabel={
                        timelineFiltersActive
                            ? `${filteredTimelineEvents.length} of ${timelineEvents.length}`
                            : undefined
                    }
                    emptyTitle={
                        timelineFiltersActive && timelineEvents.length > 0
                            ? "No matching events"
                            : undefined
                    }
                    emptyDescription={
                        timelineFiltersActive && timelineEvents.length > 0
                            ? "Try a different search term or pick another date."
                            : undefined
                    }
                />
            </div>

            {/* Stats — KPI cards */}
            <div className="grid shrink-0 grid-cols-2 gap-3 md:grid-cols-4">
                {trackerKpiItems.map((item) => (
                    <KPICard
                        key={item.key}
                        label={item.label}
                        value={item.value}
                        icon={item.icon}
                        className="border-white/40 bg-white/50 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)]"
                    />
                ))}
            </div>
        </div>
    )
}
