"use client"

import * as React from "react"
import { Controller, type Control } from "react-hook-form"
import { UserCheck } from "lucide-react"

import { Label } from "@/components/ui/label"
import { useGetAllUsersQuery, useGetRolesQuery } from "@/api/rtk"
import type { TeamUser } from "@/api/rtk/teams-api"
import {
    ContributorUserPicker,
    pickRoleIdFromOrgRoles,
} from "@/components/deals/contributor-user-picker"
import { DetailItemAssigneeChips } from "@/components/deals/deal-detail-assignee-chips"
import type { FormValues } from "@/components/deals/business-deal-form-types"

function isAeRole(user: TeamUser): boolean {
    const roleName = (user.role?.name ?? "").trim().toUpperCase()
    return roleName === "AE" || roleName === "ACCOUNT EXECUTIVE"
}

/** Org users with AE role (picker + inheritance; not scoped to CRM team). */
export function useTeamAePool(_teamSlug: string | null | undefined, skip: boolean) {
    const { data: allUsers = [] } = useGetAllUsersQuery(undefined, { skip })
    const { data: orgRoles = [] } = useGetRolesQuery(undefined, { skip })

    const aeRoleId = React.useMemo(
        () => pickRoleIdFromOrgRoles(orgRoles, ["ae", "account executive"]),
        [orgRoles],
    )

    const usersArray = React.useMemo(
        () => (Array.isArray(allUsers) ? allUsers : []),
        [allUsers],
    )

    const aeUsers = React.useMemo(
        () => usersArray.filter(isAeRole),
        [usersArray],
    )

    const teamAeIds = React.useMemo(() => aeUsers.map((u) => u.id), [aeUsers])

    const labelById = React.useMemo(() => {
        const m: Record<string, string> = {}
        for (const u of Array.isArray(allUsers) ? allUsers : []) {
            m[u.id] = u.name || u.email || u.id
        }
        return m
    }, [allUsers])

    return {
        aeRoleId,
        aeUsers,
        teamAeIds,
        labelById,
    }
}

/** Keeps valid AE ids when org AE list is loaded; otherwise passes through. */
export function filterIdsToTeamAes(ids: string[], orgAeIds: string[]): string[] {
    const cleaned = ids.map((id) => id?.trim()).filter(Boolean) as string[]
    if (!orgAeIds.length) return cleaned
    const set = new Set(orgAeIds)
    return cleaned.filter((id) => set.has(id))
}

type BusinessDealAeFieldProps = {
    control: Control<FormValues>
    disabled?: boolean
    helperText?: string | null
    skipQueries?: boolean
}

export function BusinessDealAeField({
    control,
    disabled,
    helperText,
    skipQueries = false,
}: BusinessDealAeFieldProps) {
    const { aeRoleId, aeUsers, labelById } = useTeamAePool(null, skipQueries)

    return (
        <div className="space-y-2 col-span-2">
            <Label>Assign AE</Label>
            <Controller
                name="aeIds"
                control={control}
                render={({ field }) => (
                    <ContributorUserPicker
                        value={field.value ?? []}
                        onChange={field.onChange}
                        disabled={disabled}
                        labelById={labelById}
                        placeholder="Select AEs"
                        className="border-gray-200 bg-gray-50"
                        roleId={aeRoleId}
                        staticUserPool={aeRoleId ? undefined : aeUsers}
                        emptyListMessage="No account executives found."
                    />
                )}
            />
            {helperText?.trim() ? (
                <p className="text-sm text-muted-foreground">{helperText}</p>
            ) : null}
        </div>
    )
}

type BusinessDealAeReadOnlyProps = {
    aeIds?: string[]
    aes?: Array<{ id: string; name: string; email?: string | null }>
    labelById: Record<string, string | undefined>
}

export function BusinessDealAeReadOnly({
    aeIds = [],
    aes,
    labelById,
}: BusinessDealAeReadOnlyProps) {
    const names = React.useMemo(() => {
        if (aes?.length) {
            return aes.map((u) => u.name?.trim() || u.email?.trim() || u.id)
        }
        return aeIds.map((id) => labelById[id]?.trim() || id).filter(Boolean)
    }, [aeIds, aes, labelById])

    return (
        <div className="col-span-2">
            <DetailItemAssigneeChips
                label="Assign AE"
                names={names}
                icon={<UserCheck size={14} />}
            />
        </div>
    )
}
