"use client"

import * as React from "react"
import Image from "next/image"
import { formatDistanceToNow } from "date-fns"
import { Customer, CustomerStatus } from "./types"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { ArrowUpDown, Trash2, Pencil } from "lucide-react"
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table"

function formatFromNow(iso: string | undefined): string | null {
    if (!iso) return null
    const t = new Date(iso).getTime()
    if (Number.isNaN(t)) return null
    return formatDistanceToNow(new Date(iso), { addSuffix: true })
}

function RepAvatar({ src, fallback }: { src?: string; fallback: string }) {
    const [failed, setFailed] = React.useState(false)
    const showImage = !!src && !failed
    return (
        <div className="relative size-[22px] rounded-full bg-accent/15 text-accent text-[9px] font-extrabold flex items-center justify-center shrink-0 overflow-hidden">
            {showImage ? (
                <Image
                    src={src}
                    alt={fallback}
                    fill
                    sizes="22px"
                    className="object-cover"
                    onError={() => setFailed(true)}
                    unoptimized={
                        src.startsWith("blob:") || src.startsWith("data:")
                    }
                />
            ) : (
                <span className="leading-none">{fallback}</span>
            )}
        </div>
    )
}

function CustomerAvatar({
    src,
    fallback,
    color,
}: {
    src?: string
    fallback: string
    color?: string
}) {
    const [failed, setFailed] = React.useState(false)
    const showImage = !!src && !failed
    return (
        <div
            className="relative size-8 rounded-full flex items-center justify-center text-[11px] font-extrabold text-white shrink-0 font-['Lexend_Deca'] shadow-sm overflow-hidden"
            style={!showImage ? { backgroundColor: color || "#666" } : undefined}
        >
            {showImage ? (
                <Image
                    src={src}
                    alt={fallback}
                    fill
                    sizes="32px"
                    className="object-cover"
                    onError={() => setFailed(true)}
                    unoptimized={
                        src.startsWith("blob:") || src.startsWith("data:")
                    }
                />
            ) : (
                fallback
            )}
        </div>
    )
}

interface CustomerListViewProps {
    customers: Customer[]
    onOpen: (customer: Customer) => void
    onEdit: (customer: Customer) => void
    onDelete: (id: string | number) => void
    sortCol: string
    sortDir: 1 | -1
    onSort: (col: string) => void
    isSearchActive?: boolean
    selectedId?: string | null
    onSelectId?: (id: string | null) => void
    canUpdate?: boolean
    canDelete?: boolean
}

export function CustomerListView({ customers, onOpen, onEdit, onDelete, sortCol, sortDir, onSort, isSearchActive, selectedId, onSelectId, canUpdate, canDelete }: CustomerListViewProps) {
    const statusBadges: Record<CustomerStatus, string> = {
        'Active': 'bg-[#ECFDF5] text-[#22C55E] font-extrabold',
        'Churned': 'bg-[#FEF2F2] text-[#FF6B6B]',
        'Inactive': 'bg-bg text-gray-700',
        'Premium': 'bg-[#EEF2FF] text-[#6C63FF] font-extrabold',
    }

    return (
        <div className="rounded-2xl border border-white/40 shadow-[0px_2px_20px_0px_rgba(0,0,0,0.06)] overflow-auto scrollbar-themed">
            <Table>
                <TableHeader>
                    <TableRow className="bg-white/40 dark:bg-white/5 border-b-2 border-white/30 select-none hover:bg-transparent cursor-default">
                        <TableHead className="cursor-pointer hover:bg-bg transition-colors" onClick={() => onSort('name')}>
                            <div className="flex items-center gap-1.5 transition-colors group">
                                Customer <ArrowUpDown size={10} className={cn("shrink-0 opacity-40 group-hover:text-accent", sortCol === 'name' && "text-accent opacity-100")} style={sortCol === 'name' ? { transform: sortDir === -1 ? 'rotate(180deg)' : undefined } : undefined} />
                            </div>
                        </TableHead>
                        <TableHead className="hidden md:table-cell cursor-pointer hover:bg-bg transition-colors" onClick={() => onSort('company')}>
                            <div className="flex items-center gap-1.5 transition-colors group">
                                Company <ArrowUpDown size={10} className={cn("shrink-0 opacity-40 group-hover:text-accent", sortCol === 'company' && "text-accent opacity-100")} style={sortCol === 'company' ? { transform: sortDir === -1 ? 'rotate(180deg)' : undefined } : undefined} />
                            </div>
                        </TableHead>

                        <TableHead className="cursor-pointer hover:bg-bg transition-colors" onClick={() => onSort('dealValue')}>
                            <div className="flex items-center gap-1.5 transition-colors group">
                                Value <ArrowUpDown size={10} className={cn("shrink-0 opacity-40 group-hover:text-accent", sortCol === 'dealValue' && "text-accent opacity-100")} style={sortCol === 'dealValue' ? { transform: sortDir === -1 ? 'rotate(180deg)' : undefined } : undefined} />
                            </div>
                        </TableHead>
                        <TableHead className="cursor-pointer hover:bg-bg transition-colors min-w-[140px]" onClick={() => onSort('updatedAt')}>
                            <div className="flex items-center gap-1.5 transition-colors group">
                                Activity <ArrowUpDown size={10} className={cn("shrink-0 opacity-40 group-hover:text-accent", sortCol === 'updatedAt' && "text-accent opacity-100")} style={sortCol === 'updatedAt' ? { transform: sortDir === -1 ? 'rotate(180deg)' : undefined } : undefined} />
                            </div>
                        </TableHead>
                        <TableHead className="hidden lg:table-cell">Assigned Rep</TableHead>
                        <TableHead className="hidden sm:table-cell">Status</TableHead>
                        <TableHead className="w-[80px]"></TableHead>
                    </TableRow>
                </TableHeader>
                <TableBody className="font-['Lexend'] divide-y divide-white/20">
                    {customers.map((customer) => {
                        const isSelected = selectedId !== undefined && selectedId === customer.id
                        return (
                            <TableRow
                                key={customer.id}
                                className={cn(
                                    "group transition-colors cursor-pointer border-b border-white/10",
                                    isSearchActive && onSelectId
                                        ? "hover:bg-white/40 dark:hover:bg-white/10"
                                        : "hover:bg-white/40 dark:hover:bg-white/10",
                                    isSelected && "bg-accent/15 ring-1 ring-inset ring-accent/30"
                                )}
                                onClick={() => {
                                    if (isSearchActive && onSelectId) {
                                        onSelectId(isSelected ? null : customer.id)
                                    } else {
                                        onOpen(customer)
                                    }
                                }}
                            >
                                <TableCell>
                                    <div className="flex items-center gap-3">
                                        <CustomerAvatar
                                            src={customer.avatarUrl}
                                            fallback={customer.initials}
                                            color={customer.color}
                                        />
                                        <div className="flex flex-col gap-0.5 max-w-[150px]">
                                            <span className="text-[13px] font-bold text-text truncate font-['Lexend']">{customer.name}</span>
                                            <span className="text-[11px] text-gray-700 truncate">{customer.email}</span>
                                        </div>
                                    </div>
                                </TableCell>
                                <TableCell className="hidden md:table-cell text-[13px] font-bold text-text font-['Lexend']">{customer.company}</TableCell>
                                <TableCell>
                                    <span className="text-[13px] font-bold text-accent font-['Lexend']">
                                        {new Intl.NumberFormat("en-US", {
                                            style: "currency",
                                            currency: "USD",
                                            minimumFractionDigits: 0,
                                            maximumFractionDigits: 0,
                                        }).format(customer.totalDealsValue || 0)}
                                    </span>
                                </TableCell>
                                <TableCell>
                                    <div className="flex flex-col gap-0.5 max-w-[200px]">
                                        {(() => {
                                            const updated = formatFromNow(customer.updatedAt)
                                            const created = formatFromNow(customer.createdAt)
                                            if (!updated && !created) {
                                                return <span className="text-[12px] text-gray-500">—</span>
                                            }
                                            return (
                                                <>
                                                    {updated ? (
                                                        <span className="text-[12px] font-semibold text-gray-800 font-['Lexend_Deca'] leading-tight">
                                                            Updated {updated}
                                                        </span>
                                                    ) : created ? (
                                                        <span className="text-[12px] font-semibold text-gray-800 font-['Lexend_Deca'] leading-tight">
                                                            Created {created}
                                                        </span>
                                                    ) : null}
                                                    {updated && created && customer.updatedAt !== customer.createdAt ? (
                                                        <span className="text-[10px] text-gray-500 font-['Lexend_Deca'] leading-tight">
                                                            Created {created}
                                                        </span>
                                                    ) : null}
                                                </>
                                            )
                                        })()}
                                    </div>
                                </TableCell>
                                <TableCell className="hidden lg:table-cell">
                                    <div className="flex flex-col gap-1.5">
                                        <div className="flex items-center gap-2">
                                            <RepAvatar
                                                src={customer.repAv}
                                                fallback={(customer.rep || "—")
                                                    .split(/\s+/)
                                                    .filter(Boolean)
                                                    .slice(0, 2)
                                                    .map(w => w[0])
                                                    .join("")
                                                    .toUpperCase()}
                                            />
                                            <span className="text-[12px] font-semibold">{customer.rep.split(' ')[0]}</span>
                                        </div>
                                    </div>
                                </TableCell>
                                <TableCell className="hidden sm:table-cell">
                                    <span className={cn("text-[10px] font-bold px-2.5 py-0.5 rounded-full", statusBadges[customer.status])}>
                                        {customer.status}
                                    </span>
                                </TableCell>
                                <TableCell className="text-right">
                                    <div className="flex items-center justify-end gap-1 opacity-100">
                                        {canUpdate && (
                                            <Button
                                                variant="ghost"
                                                size="icon-xs"
                                                onClick={(e) => { e.stopPropagation(); onEdit(customer); }}
                                            >
                                                <Pencil size={13} />
                                            </Button>
                                        )}
                                        {canDelete && (
                                            <Button
                                                variant="ghost"
                                                size="icon-xs"
                                                className="hover:bg-red/10 hover:text-red"
                                                onClick={(e) => { e.stopPropagation(); onDelete(customer.id); }}
                                            >
                                                <Trash2 size={13} />
                                            </Button>
                                        )}
                                    </div>
                                </TableCell>
                            </TableRow>
                        )
                    })}
                </TableBody>
            </Table>
        </div>
    )
}
