"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover"
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/components/ui/command"
import { ChevronsUpDown, Loader2, X } from "lucide-react"
import { cn } from "@/lib/utils"
import { fetchLeadsListPageClient } from "@/features/leads/api/fetch-leads-list-page-client"
import { useLazySearchCustomersQuery } from "@/api/rtk"
import type { Deal } from "@/api/rtk/deals-api"
import type { CustomerBackend } from "@/api/rtk/customers-api"

export function formatLeadPickLabel(d: Pick<Deal, "customerName" | "companyName" | "email" | "id">) {
    const name =
        d.customerName?.trim() ||
        d.companyName?.trim() ||
        d.email?.trim() ||
        d.id
    return name
}

export function LeadSearchCombobox({
    value,
    onChange,
    disabled,
    selectedDeal,
    loadingSelected,
}: {
    value: string
    onChange: (id: string) => void
    disabled?: boolean
    selectedDeal?: Deal | null
    loadingSelected?: boolean
}) {
    const [open, setOpen] = React.useState(false)
    const [query, setQuery] = React.useState("")
    const [results, setResults] = React.useState<Deal[]>([])
    const [searching, setSearching] = React.useState(false)

    React.useEffect(() => {
        if (!open) return
        const q = query.trim()
        if (q.length < 2) {
            setResults([])
            setSearching(false)
            return
        }
        let cancelled = false
        const t = window.setTimeout(() => {
            void (async () => {
                setSearching(true)
                try {
                    const page = await fetchLeadsListPageClient({
                        search: q,
                        stageType: "Lead",
                        limit: 25,
                        cursor: null,
                    })
                    if (!cancelled) setResults(page.items)
                } catch {
                    if (!cancelled) setResults([])
                } finally {
                    if (!cancelled) setSearching(false)
                }
            })()
        }, 300)
        return () => {
            cancelled = true
            window.clearTimeout(t)
        }
    }, [query, open])

    const hasSelection = Boolean(value?.trim())
    const triggerLabel = hasSelection
        ? loadingSelected
            ? "Loading…"
            : formatLeadPickLabel(selectedDeal ?? { id: value })
        : "Search leads…"

    return (
        <div className="flex gap-2">
            <Popover
                open={open}
                onOpenChange={(next) => {
                    setOpen(next)
                    if (!next) setQuery("")
                }}
            >
                <PopoverTrigger asChild>
                    <Button
                        id="bd-lead-search"
                        type="button"
                        variant="outline"
                        disabled={disabled}
                        className={cn(
                            "h-10 flex-1 justify-between px-3 font-normal",
                            !hasSelection && "text-muted-foreground",
                        )}
                    >
                        <span className="truncate text-left">{triggerLabel}</span>
                        <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
                    </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[min(100vw-2rem,400px)] p-0" align="start">
                    <Command shouldFilter={false}>
                        <CommandInput
                            placeholder="Name, email, company…"
                            value={query}
                            onValueChange={setQuery}
                        />
                        <CommandList>
                            {searching ? (
                                <div className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground">
                                    <Loader2 className="size-4 animate-spin" />
                                    Searching…
                                </div>
                            ) : null}
                            <CommandEmpty>
                                {query.trim().length < 2
                                    ? "Type at least 2 characters"
                                    : "No leads found."}
                            </CommandEmpty>
                            <CommandGroup>
                                {results.map((d) => (
                                    <CommandItem
                                        key={d.id}
                                        value={d.id}
                                        onSelect={() => {
                                            onChange(d.id)
                                            setOpen(false)
                                            setQuery("")
                                        }}
                                    >
                                        <div className="flex min-w-0 flex-col">
                                            <span className="truncate font-medium">
                                                {formatLeadPickLabel(d)}
                                            </span>
                                            {d.email ? (
                                                <span className="truncate text-xs text-muted-foreground">
                                                    {d.email}
                                                </span>
                                            ) : null}
                                        </div>
                                    </CommandItem>
                                ))}
                            </CommandGroup>
                        </CommandList>
                    </Command>
                </PopoverContent>
            </Popover>
            {hasSelection && !disabled ? (
                <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    className="size-10 shrink-0"
                    aria-label="Clear lead"
                    onClick={() => onChange("")}
                >
                    <X className="size-4" />
                </Button>
            ) : null}
        </div>
    )
}

export function formatCustomerPickLabel(
    c: Pick<
        CustomerBackend,
        "fullName" | "companyName" | "customerName" | "email" | "id"
    >,
) {
    return (
        c.fullName?.trim() ||
        c.companyName?.trim() ||
        c.customerName?.trim() ||
        c.email?.trim() ||
        c.id
    )
}

export function CustomerSearchCombobox({
    value,
    onChange,
    disabled,
    selectedCustomer,
    loadingSelected,
}: {
    value: string
    onChange: (id: string) => void
    disabled?: boolean
    selectedCustomer?: CustomerBackend | null
    loadingSelected?: boolean
}) {
    const [searchCustomers] = useLazySearchCustomersQuery()
    const [open, setOpen] = React.useState(false)
    const [query, setQuery] = React.useState("")
    const [results, setResults] = React.useState<CustomerBackend[]>([])
    const [searching, setSearching] = React.useState(false)

    React.useEffect(() => {
        if (!open) return
        const q = query.trim()
        if (q.length < 2) {
            setResults([])
            setSearching(false)
            return
        }
        let cancelled = false
        const t = window.setTimeout(() => {
            void (async () => {
                setSearching(true)
                try {
                    const rows = await searchCustomers({
                        search: q,
                        limit: 25,
                    }).unwrap()
                    if (!cancelled) setResults(Array.isArray(rows) ? rows : [])
                } catch {
                    if (!cancelled) setResults([])
                } finally {
                    if (!cancelled) setSearching(false)
                }
            })()
        }, 300)
        return () => {
            cancelled = true
            window.clearTimeout(t)
        }
    }, [query, open, searchCustomers])

    const hasSelection = Boolean(value?.trim())
    const triggerLabel = hasSelection
        ? loadingSelected
            ? "Loading…"
            : formatCustomerPickLabel(
                selectedCustomer ?? {
                    id: value,
                    fullName: null,
                    companyName: null,
                    customerName: null,
                    email: null,
                },
            )
        : "Search customers…"

    return (
        <div className="flex gap-2">
            <Popover
                open={open}
                onOpenChange={(next) => {
                    setOpen(next)
                    if (!next) setQuery("")
                }}
            >
                <PopoverTrigger asChild>
                    <Button
                        id="bd-cust-search"
                        type="button"
                        variant="outline"
                        disabled={disabled}
                        className={cn(
                            "h-10 flex-1 justify-between px-3 font-normal",
                            !hasSelection && "text-muted-foreground",
                        )}
                    >
                        <span className="truncate text-left">{triggerLabel}</span>
                        <ChevronsUpDown className="ml-2 size-4 shrink-0 opacity-50" />
                    </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[min(100vw-2rem,400px)] p-0" align="start">
                    <Command shouldFilter={false}>
                        <CommandInput
                            placeholder="Name, email, company…"
                            value={query}
                            onValueChange={setQuery}
                        />
                        <CommandList>
                            {searching ? (
                                <div className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground">
                                    <Loader2 className="size-4 animate-spin" />
                                    Searching…
                                </div>
                            ) : null}
                            <CommandEmpty>
                                {query.trim().length < 2
                                    ? "Type at least 2 characters"
                                    : "No customers found."}
                            </CommandEmpty>
                            <CommandGroup>
                                {results.map((c) => (
                                    <CommandItem
                                        key={c.id}
                                        value={c.id}
                                        onSelect={() => {
                                            onChange(c.id)
                                            setOpen(false)
                                            setQuery("")
                                        }}
                                    >
                                        <div className="flex min-w-0 flex-col">
                                            <span className="truncate font-medium">
                                                {formatCustomerPickLabel(c)}
                                            </span>
                                            {c.email ? (
                                                <span className="truncate text-xs text-muted-foreground">
                                                    {c.email}
                                                </span>
                                            ) : null}
                                        </div>
                                    </CommandItem>
                                ))}
                            </CommandGroup>
                        </CommandList>
                    </Command>
                </PopoverContent>
            </Popover>
            {hasSelection && !disabled ? (
                <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    className="size-10 shrink-0"
                    aria-label="Clear customer"
                    onClick={() => onChange("")}
                >
                    <X className="size-4" />
                </Button>
            ) : null}
        </div>
    )
}
