import { Head, router } from '@inertiajs/react';
import {
    Calendar,
    Car,
    CircleDollarSign,
    CreditCard,
    Mail,
    MapPin,
    MoreHorizontal,
    Phone,
    Search,
    Users,
} from 'lucide-react';
import type { ReactNode } from 'react';
import { useMemo, useState } from 'react';
import { EmptyState } from '@/components/layout/empty-state';
import { PageHeader } from '@/components/layout/page-header';
import { ResourceActionsMenu } from '@/components/resource-actions-menu';
import { StatusBadge } from '@/components/status-badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import AppLayout from '@/layouts/app-layout';
import adminCustomers from '@/routes/admin/customers';

type CustomerRow = {
    id: number;
    name: string;
    email: string;
    phone: string | null;
    bookings_count: number;
    vehicles_count: number;
    last_booking_at: string | null;
    last_location_label: string | null;
    lifetime_spend: number;
    created_at: string | null;
    last_vehicle: {
        id: number;
        label: string;
        size: string;
    } | null;
    active_membership: {
        id: number;
        status: string;
        plan_name: string | null;
    } | null;
};

type Props = {
    customers: CustomerRow[];
};

function formatMoney(cents: number): string {
    return `$${(cents / 100).toFixed(2)}`;
}

function formatDateShort(value: string | null): string {
    if (!value) return '—';
    return new Date(value).toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
    });
}

function getInitials(name: string): string {
    return name
        .split(' ')
        .slice(0, 2)
        .map((n) => n[0])
        .join('')
        .toUpperCase();
}

function CustomerCard({
    customer,
    onOpen,
    onDelete,
}: {
    customer: CustomerRow;
    onOpen: () => void;
    onDelete: () => void;
}) {
    return (
        <div className="group relative flex flex-col rounded-xl border bg-card shadow-sm transition-shadow hover:shadow-md">
            {/* Header */}
            <div className="flex items-start gap-3 p-4">
                <button
                    type="button"
                    onClick={onOpen}
                    className="flex-shrink-0 focus:outline-none"
                    tabIndex={-1}
                    aria-label={`Open ${customer.name}`}
                >
                    <Avatar className="size-11 rounded-lg">
                        <AvatarFallback className="rounded-lg bg-primary/10 text-sm font-semibold text-primary">
                            {getInitials(customer.name)}
                        </AvatarFallback>
                    </Avatar>
                </button>

                <div className="min-w-0 flex-1">
                    <button
                        type="button"
                        onClick={onOpen}
                        className="block truncate text-left text-sm font-semibold text-foreground hover:underline"
                    >
                        {customer.name}
                    </button>
                    <div className="mt-0.5 flex items-center gap-1 truncate text-xs text-muted-foreground">
                        <Mail className="size-3 shrink-0" />
                        <span className="truncate">{customer.email}</span>
                    </div>
                    {customer.phone ? (
                        <div className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">
                            <Phone className="size-3 shrink-0" />
                            <span>{customer.phone}</span>
                        </div>
                    ) : null}
                </div>

                <ResourceActionsMenu
                    onEdit={onOpen}
                    onDelete={onDelete}
                    editLabel="View customer"
                    deleteLabel="Delete customer"
                    deleteTitle="Delete customer?"
                    deleteDescription="This permanently removes the customer and related records."
                    confirmLabel="Delete customer"
                />
            </div>

            <Separator />

            {/* Stats row */}
            <div className="grid grid-cols-3 divide-x">
                <div className="flex flex-col items-center py-3 px-2">
                    <span className="text-base font-bold text-foreground">
                        {customer.bookings_count}
                    </span>
                    <span className="mt-0.5 text-[11px] text-muted-foreground">
                        Bookings
                    </span>
                </div>
                <div className="flex flex-col items-center py-3 px-2">
                    <span className="text-base font-bold text-foreground">
                        {customer.vehicles_count}
                    </span>
                    <span className="mt-0.5 text-[11px] text-muted-foreground">
                        Vehicles
                    </span>
                </div>
                <div className="flex flex-col items-center py-3 px-2">
                    <span className="text-base font-bold text-emerald-600">
                        {formatMoney(customer.lifetime_spend)}
                    </span>
                    <span className="mt-0.5 text-[11px] text-muted-foreground">
                        Lifetime
                    </span>
                </div>
            </div>

            <Separator />

            {/* Details */}
            <div className="flex flex-col gap-2 p-4 text-xs text-muted-foreground">
                {customer.last_vehicle ? (
                    <div className="flex items-center gap-2">
                        <Car className="size-3.5 shrink-0" />
                        <span className="truncate text-foreground">
                            {customer.last_vehicle.label}
                        </span>
                        <span className="capitalize">
                            · {customer.last_vehicle.size}
                        </span>
                    </div>
                ) : null}

                {customer.last_location_label ? (
                    <div className="flex items-center gap-2">
                        <MapPin className="size-3.5 shrink-0" />
                        <span className="truncate">
                            {customer.last_location_label}
                        </span>
                    </div>
                ) : null}

                {customer.last_booking_at ? (
                    <div className="flex items-center gap-2">
                        <Calendar className="size-3.5 shrink-0" />
                        <span>Last visit {formatDateShort(customer.last_booking_at)}</span>
                    </div>
                ) : null}
            </div>

            {/* Footer: membership */}
            <div className="mt-auto border-t px-4 py-3">
                {customer.active_membership ? (
                    <div className="flex items-center gap-2">
                        <StatusBadge status={customer.active_membership.status} />
                        {customer.active_membership.plan_name ? (
                            <span className="text-xs text-muted-foreground">
                                {customer.active_membership.plan_name}
                            </span>
                        ) : null}
                    </div>
                ) : (
                    <span className="text-xs text-muted-foreground">
                        No membership
                    </span>
                )}
            </div>
        </div>
    );
}

export default function AdminCustomersIndex({ customers }: Props) {
    const [search, setSearch] = useState('');

    const openCustomerPage = (customerId: number) => {
        router.get(adminCustomers.show.url({ user: customerId }));
    };

    const deleteCustomer = (customerId: number) => {
        router.delete(adminCustomers.destroy.url({ user: customerId }));
    };

    const stats = useMemo(() => {
        return customers.reduce(
            (acc, customer) => {
                acc.totalCustomers += 1;
                acc.totalBookings += customer.bookings_count;
                acc.totalVehicles += customer.vehicles_count;
                acc.totalLifetimeSpend += customer.lifetime_spend;
                if (customer.active_membership?.status === 'active') {
                    acc.activeMemberships += 1;
                }
                return acc;
            },
            {
                totalCustomers: 0,
                totalBookings: 0,
                totalVehicles: 0,
                totalLifetimeSpend: 0,
                activeMemberships: 0,
            },
        );
    }, [customers]);

    const filtered = useMemo(() => {
        const q = search.trim().toLowerCase();
        if (!q) return customers;
        return customers.filter(
            (c) =>
                c.name.toLowerCase().includes(q) ||
                c.email.toLowerCase().includes(q) ||
                c.phone?.toLowerCase().includes(q) ||
                c.last_location_label?.toLowerCase().includes(q),
        );
    }, [customers, search]);

    return (
        <>
            <Head title="Admin customers" />
            <div className="flex h-full flex-1 flex-col gap-6">
                <PageHeader title="Customers" />

                {/* Summary stats */}
                <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Total customers</CardDescription>
                            <CardTitle>{stats.totalCustomers}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <Users className="size-4" />
                            <span>Customer records</span>
                        </CardContent>
                    </Card>

                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Total bookings</CardDescription>
                            <CardTitle>{stats.totalBookings}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <Car className="size-4" />
                            <span>All customer bookings</span>
                        </CardContent>
                    </Card>

                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Lifetime spend</CardDescription>
                            <CardTitle>
                                {formatMoney(stats.totalLifetimeSpend)}
                            </CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <CircleDollarSign className="size-4" />
                            <span>Across all customers</span>
                        </CardContent>
                    </Card>

                    <Card size="sm">
                        <CardHeader>
                            <CardDescription>Active memberships</CardDescription>
                            <CardTitle>{stats.activeMemberships}</CardTitle>
                        </CardHeader>
                        <CardContent className="flex items-center gap-2 text-muted-foreground">
                            <CreditCard className="size-4" />
                            <span>
                                {stats.totalVehicles} saved vehicles total
                            </span>
                        </CardContent>
                    </Card>
                </div>

                {/* Search + card grid */}
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between gap-3">
                        <h2 className="text-base font-semibold">
                            Customer list
                        </h2>
                        <div className="relative w-full max-w-xs">
                            <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                            <Input
                                className="pl-9"
                                placeholder="Search customers…"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                        </div>
                    </div>

                    {filtered.length === 0 ? (
                        customers.length === 0 ? (
                            <EmptyState
                                title="No customers yet"
                                description="Customers will appear here after their first booking."
                            />
                        ) : (
                            <EmptyState
                                title="No results"
                                description="Try a different name, email, or location."
                            />
                        )
                    ) : (
                        <>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                {filtered.map((customer) => (
                                    <CustomerCard
                                        key={customer.id}
                                        customer={customer}
                                        onOpen={() =>
                                            openCustomerPage(customer.id)
                                        }
                                        onDelete={() =>
                                            deleteCustomer(customer.id)
                                        }
                                    />
                                ))}
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Showing {filtered.length} of {customers.length}{' '}
                                {customers.length === 1 ? 'customer' : 'customers'}
                            </p>
                        </>
                    )}
                </div>
            </div>
        </>
    );
}

AdminCustomersIndex.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            {
                title: 'Admin customers',
                href: '/admin/customers',
            },
        ]}
    >
        {page}
    </AppLayout>
);
