"use client"

import * as React from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useUrlPagination } from "@/hooks/use-url-pagination"
import { Customer, CustomerStatus } from "./types"
import { CustomerListView } from "./customer-list-view"
import { Search, Download, Plus, Users, Wallet, Briefcase, CircleDollarSign, CalendarDays } from "lucide-react"
import { format } from "date-fns"
import { toast } from "sonner"
import { Loading } from "@/components/ui/loading"
import { NoDataFound } from "@/components/ui/no-data-found"
import { KPICard } from "@/components/ui/kpi-card"
import { Button } from "@/components/ui/button"
import { MonthPicker } from "@/components/ui/month-picker"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { ReactSelect } from "@/components/ui/react-select"
import { cn } from "@/lib/utils"
import { useAuthToken } from "@/hooks/use-auth-token"
import { useLazyGetExportCustomersExcelQuery } from "@/api/rtk/contacts-api"
import { useGetCustomerPaymentKpisQuery, useDeleteCustomerMutation } from "@/api/rtk/customers-api"
import { getFileUrl } from "@/api/client"
import { useGetTeamsQuery } from "@/api/rtk/teams-api"
import { EditCustomerModal } from "./edit-customer-modal"
import { AddCustomerModal } from "./add-customer-modal"
import { CustomerDetailModal } from "./customer-detail-modal"
import { hasPermission, isAdminUser, type PermissionSource } from "@/lib/permissions"
import { formatTeamLabelForUi } from "@/lib/deal-display"
import { useSession } from "next-auth/react"
import { DeleteDialog } from "@/components/ui/delete-dialog"
import { useCustomersQuery } from "@/features/customers/hooks/use-customers-query"
import { customersKeys } from "@/features/customers/api/query-keys"
import { useDebounce } from "@/hooks/use-debounce"
import { useQueryClient } from "@tanstack/react-query"

const CUSTOMER_PAGE_SIZE = 10
const PAGE_SIZE_OPTIONS = [10, 25, 50, 100]

export default function CustomerPage() {
    const queryClient = useQueryClient()
    const router = useRouter()
    const { token } = useAuthToken()
    const { data: session } = useSession()
    const searchParams = useSearchParams()
    const { page, setPage, limit: pageSize, setLimit: setPageSize } = useUrlPagination(CUSTOMER_PAGE_SIZE)

    const [search, setSearch] = React.useState(searchParams.get("search") || "")
    const [teamFilter, setTeamFilter] = React.useState(searchParams.get("team") || "all")
    const [statusFilter, setStatusFilter] = React.useState(searchParams.get("status") || "all")
    const [monthFilter, setMonthFilter] = React.useState(
        searchParams.get("month") || "all",
    )
    const [sortCol, setSortCol] = React.useState(searchParams.get("sort") || "name")
    const [sortDir, setSortDir] = React.useState(parseInt(searchParams.get("dir") || "1", 10))
    const [add, setAdd] = React.useState(searchParams.get("add") === "true")
    const [edit, setEdit] = React.useState<string | null>(searchParams.get("edit"))
    const [detail, setDetail] = React.useState<string | null>(searchParams.get("detail"))
    const [selectedCustomerId, setSelectedCustomerId] = React.useState<string | null>(null)
    const [customerToDelete, setCustomerToDelete] = React.useState<Customer | null>(null)
    const [monthPickerOpen, setMonthPickerOpen] = React.useState(false)
    const [deleteCustomer, { isLoading: isDeletingCustomer }] = useDeleteCustomerMutation()

    const selectedMonthDate = React.useMemo(() => {
        if (monthFilter === "all" || !monthFilter) return undefined
        const match = monthFilter.match(/^(\d{4})-(\d{2})$/)
        if (!match) return undefined
        return new Date(Number(match[1]), Number(match[2]) - 1, 1)
    }, [monthFilter])

    const isSearchActive = (search ?? "").trim().length > 0
    const debouncedSearch = useDebounce(search ?? "", 300)

    // TanStack Query — server-side filtering + pagination
    const { data: customersResult, isLoading: customersLoading, isFetching } = useCustomersQuery(
        {
            page,
            limit: pageSize,
            search: debouncedSearch || undefined,
            status: statusFilter !== "all" ? statusFilter : undefined,
            team: teamFilter !== "all" ? teamFilter : undefined,
            month: monthFilter !== "all" ? monthFilter : undefined,
        },
        { enabled: !!token, refetchOnWindowFocus: true }
    )
    const backendCustomers = customersResult?.data ?? []
    const backendMeta = customersResult?.meta
    const { data: teams } = useGetTeamsQuery(undefined, { skip: !token })
    const permissionSource = (session as { backendUser?: PermissionSource } | null)?.backendUser
    const isAdmin = isAdminUser(permissionSource)
    const canReadCustomers = isAdmin || hasPermission(permissionSource, ["READ", "UPDATE"], "CUSTOMER")

    const { data: paymentKpis, isFetching: paymentKpisLoading } = useGetCustomerPaymentKpisQuery(
        { team: teamFilter ?? "all", status: statusFilter ?? "all", month: monthFilter ?? "all" },
        { skip: !token || !canReadCustomers, refetchOnReconnect: true }
    )



    const canCreateCustomers = isAdmin || hasPermission(permissionSource, ["CREATE", "UPDATE"], "CUSTOMER")
    const canUpdateCustomers = isAdmin || hasPermission(permissionSource, "UPDATE", "CUSTOMER")
    const canDeleteCustomers =
        isAdmin ||
        hasPermission(permissionSource, "UPDATE", "CUSTOMER")

    const filterTriggerClass =
        "h-10 px-3.5 rounded-xl w-full text-[13px] font-bold font-['Lexend_Deca'] border-border/80 bg-white shadow-sm hover:border-accent transition-all ring-0 focus:ring-0"
    const filterContentClass = "rounded-2xl border-border/40 shadow-premium"

    const teamFilterOptions = React.useMemo(
        () => [
            { value: "all", label: "All Teams" },
            ...(teams?.map((t) => ({
                value: t.name.toLowerCase().split(" ")[1] || t.name.toLowerCase(),
                label: formatTeamLabelForUi(t.name),
            })) ?? []),
        ],
        [teams],
    )

    const statusFilterOptions = React.useMemo(
        () => [
            { value: "all", label: "All Status" },
            { value: "Active", label: "Active" },
            { value: "Premium", label: "Premium" },
            { value: "Inactive", label: "Inactive" },
            { value: "Churned", label: "Churned" },
        ],
        [],
    )

    const pageSizeOptions = React.useMemo(
        () =>
            PAGE_SIZE_OPTIONS.map((size) => ({
                value: size.toString(),
                label: String(size),
            })),
        [],
    )

    const customers: Customer[] = React.useMemo(() => {
        return backendCustomers.map(c => {
            const name = c.fullName ?? c.customerName ?? c.companyName ?? ""
            const initials = name.split(/\s+/).map(w => w[0]).join("").slice(0, 2).toUpperCase() || "—"
            return {
                id: c.id,
                name,
                initials,
                company: c.companyName ?? c.company ?? "",
                email: c.email ?? "",
                phone: c.phone ?? "",
                dealValue: Number(c.totalLifetimeValue) || 0,
                rep: c.assignedAm?.name ?? c.owner?.name ?? "",
                repAv: getFileUrl(c.assignedAm?.avatar?.url) ?? "",
                avatarUrl: getFileUrl(c.avatar?.url) ?? "",
                team: c.team ?? "",
                lastPurchase: "N/A",
                status: (c.customerStatus as CustomerStatus) ?? "Active",
                color: "#6C63FF",
                // Additional fields
                addressUsa: c.addressUsa ?? "",
                addressIntl: c.addressIntl ?? "",
                postalCode: c.postalCode ?? "",
                country: c.country ?? "",
                website: c.website ?? "",
                brand: c.brand ?? "",
                assignedAmId: c.assignedAmId ?? "",
                assignedAm: c.assignedAm ?? undefined,
                accountTier: c.accountTier ?? "",
                contractExpiryDate: c.contractExpiryDate ?? "",
                npsScore: c.npsScore ?? undefined,
                npsDate: c.npsDate ?? "",
                notes: c.notes ?? "",
                signalType: c.signalType ?? "",
                urgency: c.urgency ?? "",
                clientLanguage: c.clientLanguage ?? "",
                briefingPackage: c.briefingPackage ?? "",
                accountContext: c.accountContext ?? "",
                signalSummary: c.signalSummary ?? "",
                createdAt: c.createdAt,
                updatedAt: c.updatedAt,
                totalDealsValue: Number(c.totalDealsValue) || 0,
            }
        })
    }, [backendCustomers])

    const editingCustomer = React.useMemo(() =>
        edit ? (customers.find(c => c.id === edit) ?? null) : null
        , [edit, customers])

    const editingCustomerBackend = React.useMemo(() =>
        edit ? (backendCustomers.find(c => c.id === edit) ?? null) : null
        , [edit, backendCustomers])

    const isLoading = customersLoading

    // Server-side filtering — no client-side filter needed
    const sortedCustomers = [...customers].sort((a, b) => {
        if (sortCol === "updatedAt") {
            const ta =
                new Date(a.updatedAt ?? a.createdAt ?? 0).getTime() || 0
            const tb =
                new Date(b.updatedAt ?? b.createdAt ?? 0).getTime() || 0
            return ta < tb ? -sortDir : ta > tb ? sortDir : 0
        }
        const av = a[sortCol as keyof Customer] ?? ""
        const bv = b[sortCol as keyof Customer] ?? ""
        if (typeof av === "string") {
            const lowA = av.toLowerCase()
            const lowB = typeof bv === "string" ? bv.toLowerCase() : String(bv)
            return lowA < lowB ? -sortDir : lowA > lowB ? sortDir : 0
        }
        return (av as number) < (bv as number)
            ? -sortDir
            : (av as number) > (bv as number)
                ? sortDir
                : 0
    })

    // Use server-side meta for pagination counts
    const totalCustomers = backendMeta?.total ?? customers.length
    const totalPages = backendMeta?.totalPages ?? Math.max(1, Math.ceil(totalCustomers / pageSize))
    // All customers on this page are already paginated by the server
    const paginatedCustomers = sortedCustomers

    const fmtFullUSD = (n: number) =>
        new Intl.NumberFormat("en-US", {
            style: "currency",
            currency: "USD",
            minimumFractionDigits: 0,
            maximumFractionDigits: 2,
        }).format(Number.isFinite(n) ? n : 0)

    const selectedCustomer = selectedCustomerId ? paginatedCustomers.find(c => c.id === selectedCustomerId) : null

    const handleEditCustomer = (customer: Customer) => {
        setEdit(customer.id)
    }

    const handleCloseEditModal = () => {
        setEdit(null)
        setSelectedCustomerId(null)
    }

    const handleCloseAddCustomerModal = () => {
        setAdd(false)
        setEdit(null)
        setSelectedCustomerId(null)
    }

    const handleCustomerSaved = React.useCallback(() => {
        void queryClient.invalidateQueries({ queryKey: customersKeys.all })
    }, [queryClient])

    return (<div className="flex flex-col h-full gap-4 md:gap-6 p-3 sm:p-4 md:p-6 animate-in fade-in duration-500 overflow-y-auto scrollbar-themed pb-20 md:pb-6">
        {/* Header Section - Modern Registry Layout */}
        <div className="flex flex-col gap-5 rounded-2xl border border-white/40 bg-white/50 dark:bg-white/10 backdrop-blur-[15px] shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] p-5">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div className="flex flex-col shrink-0">
                    <h1 className="text-[25px] font-extrabold text-text font-['Lexend'] tracking-tight leading-none">
                        Customers
                    </h1>
                    <p className="text-[12px] text-gray-500 mt-2 font-['Lexend_Deca'] uppercase tracking-wider">
                        <span className="font-bold text-text/80">{totalCustomers} valued customers</span> <span className="mx-1 opacity-20">|</span> <span className="font-bold text-accent/90">Page {page} of {totalPages}</span>
                    </p>
                </div>

                <div className="flex items-center gap-2.5 w-full md:w-auto">
                    {canCreateCustomers && (
                        <Button
                            size="sm"
                            onClick={() => {
                                setEdit(null)
                                setAdd(true)
                            }}
                            className="h-10 px-5 flex-1 md:flex-none rounded-xl text-[13px] font-black font-['Lexend_Deca'] shadow-premium gap-2"
                        >
                            <Plus size={18} className="stroke-[2px]" /> Add Customer
                        </Button>
                    )}
                </div>
            </div>

            <div className="grid grid-cols-2 lg:flex lg:flex-row items-stretch lg:items-center gap-3 w-full pt-1 border-t border-border/10">
                <div className="relative col-span-2 lg:flex-1 group">
                    <Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-accent transition-colors duration-300 pointer-events-none" />
                    <Input
                        type="search"
                        placeholder="Search customers..."
                        className="pl-10 pr-4 h-10 text-[13px] font-bold bg-white border-border/80 rounded-xl w-full font-['Lexend_Deca'] shadow-sm focus:ring-accent/20 focus:border-accent hover:border-accent/40 transition-all placeholder:text-gray-400"
                        value={search || ""}
                        onChange={(e) => {
                            setSearch(e.target.value)
                            setPage(1)
                            setSelectedCustomerId(null)
                        }}
                    />
                </div>

                <div className="col-span-1">
                    <ReactSelect
                        value={teamFilter || "all"}
                        onValueChange={(value) => {
                            setTeamFilter(value)
                            setPage(1)
                            setSelectedCustomerId(null)
                        }}
                        options={teamFilterOptions}
                        placeholder="All Teams"
                        triggerClassName={filterTriggerClass}
                        contentClassName={filterContentClass}
                    />
                </div>

                <div className="col-span-1">
                    <ReactSelect
                        value={statusFilter || "all"}
                        onValueChange={(value) => {
                            setStatusFilter(value)
                            setPage(1)
                            setSelectedCustomerId(null)
                        }}
                        options={statusFilterOptions}
                        placeholder="All Status"
                        triggerClassName={filterTriggerClass}
                        contentClassName={filterContentClass}
                    />
                </div>

                <div className="col-span-2 lg:w-[170px]">
                    <Popover open={monthPickerOpen} onOpenChange={setMonthPickerOpen}>
                        <PopoverTrigger asChild>
                            <Button
                                type="button"
                                variant="outline"
                                className={cn(
                                    filterTriggerClass,
                                    "justify-start gap-2 font-normal",
                                    monthFilter === "all" && "text-muted-foreground",
                                )}
                                aria-label="Filter customers by created month"
                            >
                                <CalendarDays className="size-4 shrink-0 opacity-70" aria-hidden />
                                <span className="truncate">
                                    {selectedMonthDate
                                        ? format(selectedMonthDate, "MMMM yyyy")
                                        : "All Months"}
                                </span>
                            </Button>
                        </PopoverTrigger>
                        <PopoverContent
                            className={cn("w-auto p-0", filterContentClass)}
                            align="start"
                        >
                            <MonthPicker
                                selected={selectedMonthDate}
                                onSelect={(month) => {
                                    setMonthFilter(format(month, "yyyy-MM"))
                                    setPage(1)
                                    setSelectedCustomerId(null)
                                    setMonthPickerOpen(false)
                                }}
                            />
                            {monthFilter !== "all" && (
                                <div className="border-t border-border/40 p-2">
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="sm"
                                        className="h-8 w-full text-[12px] font-bold font-['Lexend_Deca']"
                                        onClick={() => {
                                            setMonthFilter("all")
                                            setPage(1)
                                            setSelectedCustomerId(null)
                                            setMonthPickerOpen(false)
                                        }}
                                    >
                                        Clear month
                                    </Button>
                                </div>
                            )}
                        </PopoverContent>
                    </Popover>
                </div>
            </div>
        </div>

        {/* Stats Strip - Glassmorphism */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-3.5 mb-1.5 h-auto overflow-visible">
            <KPICard label="Total Customers" value={totalCustomers.toString()} subtext="onboarded" icon={<Users size={16} />} className="bg-white/50 dark:bg-white/10 backdrop-blur-[15px] border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] py-4" />
            {/* <KPICard
                    label="Total Overall Project Value"
                    value={paymentKpisLoading ? "…" : fmtFullUSD(paymentKpis?.totalOverallProjectValue ?? 0)}
                    subtext="payment structures"
                    icon={<Briefcase size={16} />}
                    className="bg-white/50 dark:bg-white/10 backdrop-blur-[15px] border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] py-4"
                /> */}
            <KPICard
                label="Total Pipeline Value"
                value={paymentKpisLoading ? "…" : fmtFullUSD(paymentKpis?.totalPipelineValue ?? 0)}
                icon={<CircleDollarSign size={16} />}
                className="bg-white/50 dark:bg-white/10 backdrop-blur-[15px] border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] py-4"
            />
            <KPICard
                label="Total Upfront Paid"
                value={
                    paymentKpisLoading
                        ? "…"
                        : `${fmtFullUSD(paymentKpis?.totalUpfrontPaidValue ?? 0)}`
                }
                subtext={
                    paymentKpisLoading
                        ? "" : ""}
                icon={<Wallet size={16} />}
                className="bg-white/50 dark:bg-white/10 backdrop-blur-[15px] border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] py-4"
            />
            {/* <KPICard
                    label="Total Remaining"
                    value={
                        paymentKpisLoading
                            ? "…"
                            : fmtFullUSD(Number(paymentKpis?.totalOverallProjectValue ?? 0) - (Number(paymentKpis?.totalUpfrontPaidValue ?? 0) + Number(paymentKpis?.totalCustomPaidValue ?? 0)))
                    }
                    subtext={
                        paymentKpisLoading
                            ? "":""}
                    icon={<Wallet size={16} />}
                    className="bg-white/50 dark:bg-white/10 backdrop-blur-[15px] border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] py-4"
                /> */}
        </div>


        {/* Main Content Area */}
        <div className="flex-1 min-h-0">
            <div className="pr-1 pb-4">
                {isLoading ? (
                    <Loading message="Loading customers..." className="h-64" />
                ) : totalCustomers > 0 ? (
                    <>
                        <CustomerListView
                            customers={paginatedCustomers}
                            onOpen={(c) => router.push(`/customers/${c.id}`)}
                            onEdit={handleEditCustomer}
                            onDelete={(id) => {
                                const row = paginatedCustomers.find((c) => c.id === id)
                                if (row) setCustomerToDelete(row)
                            }}
                            canUpdate={canUpdateCustomers}
                            canDelete={canDeleteCustomers}
                            sortCol={sortCol || "name"}
                            sortDir={sortDir as 1 | -1}
                            onSort={(col) => {
                                if (sortCol === col) setSortDir(sortDir === 1 ? -1 : 1)
                                else { setSortCol(col); setSortDir(1); }
                                setPage(1)
                            }}
                            isSearchActive={isSearchActive}
                            selectedId={selectedCustomerId}
                            onSelectId={setSelectedCustomerId}
                        />
                        {totalPages > 1 && (
                            <div className="flex items-center justify-between gap-4 py-3 border-t border-border/40 mt-4">
                                <div className="flex items-center gap-3">
                                    <p className="text-[12px] text-gray-600 font-['Lexend_Deca']">
                                        Showing {(page - 1) * pageSize + 1}–{Math.min(page * pageSize, totalCustomers)} of {totalCustomers}
                                    </p>
                                    <div className="flex items-center gap-2">
                                        <span className="text-[11px] text-gray-500 font-['Lexend_Deca']">Per page:</span>
                                        <ReactSelect
                                            value={pageSize.toString()}
                                            onValueChange={(val) => {
                                                setPageSize(parseInt(val))
                                                setPage(1)
                                            }}
                                            options={pageSizeOptions}
                                            triggerClassName="h-8 w-[70px] text-[12px] border-gray-200"
                                        />
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Button variant="outline" size="pagination" onClick={() => setPage(Math.max(1, page - 1))} disabled={page <= 1}>
                                        Previous
                                    </Button>
                                    <span className="text-[12px] font-semibold px-2">Page {page} of {totalPages}</span>
                                    <Button variant="outline" size="pagination" onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page >= totalPages}>
                                        Next
                                    </Button>
                                </div>
                            </div>
                        )}
                    </>
                ) : (
                    <NoDataFound
                        message="No customers found"
                        description="No customers match your filters. Winning a deal automatically adds a contact here."
                    />
                )}
            </div>
        </div>
        <EditCustomerModal
            customer={editingCustomer}
            isOpen={!!edit}
            onClose={handleCloseEditModal}
            onSuccess={handleCustomerSaved}
            teams={teams}
        />
        {/* Add / Edit Customer: same dialog (backend list uses this for both) */}
        <AddCustomerModal
            isOpen={add ?? false}
            onClose={handleCloseAddCustomerModal}
            onSuccess={handleCustomerSaved}
            editCustomer={editingCustomerBackend ?? undefined}
        />
        <CustomerDetailModal
            customerId={detail}
            isOpen={!!detail}
            onClose={() => setDetail(null)}
            onEdit={(cust) => {
                setDetail(null)
                setEdit(cust.id)
            }}
        />
        <DeleteDialog
            open={!!customerToDelete}
            onOpenChange={(open) => {
                if (!open) setCustomerToDelete(null)
            }}
            title="Remove this customer?"
            description={
                customerToDelete
                    ? `“${customerToDelete.name}” will be removed from the list (soft delete). You can restore from the database if needed.`
                    : undefined
            }
            confirmText="Remove"
            isLoading={isDeletingCustomer}
            onConfirm={async () => {
                if (!customerToDelete) return
                const id = String(customerToDelete.id)
                try {
                    await deleteCustomer(id).unwrap()
                    toast.success("Customer removed")
                    handleCustomerSaved()
                    if (selectedCustomerId === id) setSelectedCustomerId(null)
                    if (edit === id) setEdit(null)
                    if (detail === id) setDetail(null)
                    setCustomerToDelete(null)
                } catch {
                    toast.error("Could not remove customer")
                    throw new Error("delete failed")
                }
            }}
        />
    </div>
    )
}
