import { Head, Link, router, useForm } from '@inertiajs/react';
import { Search } from 'lucide-react';
import { FormEventHandler } from 'react';

import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import AdminLayout from '@/layouts/admin-layout';
import { type Customer, type PaginatedData } from '@/types';

export default function AdminCustomersIndex({ customers, filters }: { customers: PaginatedData<Customer>; filters: Record<string, string> }) {
    const { data, setData, get } = useForm({ search: filters.search ?? '' });

    const applyFilters: FormEventHandler = (e) => {
        e.preventDefault();
        get(route('admin.customers.index'), { preserveState: true });
    };

    const toggleBlock = (customer: Customer) => {
        router.patch(route('admin.customers.toggleBlock', customer.id), {}, { preserveState: true });
    };

    return (
        <AdminLayout title="Customers">
            <Head title="Customers" />
            <div className="mb-4">
                <form onSubmit={applyFilters} className="flex gap-2 max-w-sm">
                    <div className="relative flex-1">
                        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                        <Input placeholder="Search name, phone…" value={data.search} onChange={(e) => setData('search', e.target.value)} className="pl-9" />
                    </div>
                    <Button type="submit" variant="secondary">Search</Button>
                </form>
            </div>

            <Card>
                <CardContent className="p-0">
                    <table className="w-full text-sm">
                        <thead className="border-b bg-slate-50 text-xs uppercase text-slate-500">
                            <tr>
                                <th className="px-4 py-3 text-left">Name</th>
                                <th className="px-4 py-3 text-left">Phone</th>
                                <th className="px-4 py-3 text-right">Orders</th>
                                <th className="px-4 py-3 text-right">Spent</th>
                                <th className="px-4 py-3 text-left">Last Order</th>
                                <th className="px-4 py-3 text-center">Status</th>
                                <th className="px-4 py-3" />
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {customers.data.map((c) => (
                                <tr key={c.id} className="hover:bg-slate-50">
                                    <td className="px-4 py-3 font-medium">{c.name}</td>
                                    <td className="px-4 py-3">{c.phone}</td>
                                    <td className="px-4 py-3 text-right">{c.total_orders}</td>
                                    <td className="px-4 py-3 text-right font-medium">৳{Number(c.total_spent).toLocaleString()}</td>
                                    <td className="px-4 py-3 text-slate-500 text-xs">{c.last_order_at ? new Date(c.last_order_at).toLocaleDateString('en-BD') : '—'}</td>
                                    <td className="px-4 py-3 text-center">
                                        <button onClick={() => toggleBlock(c)} className={`rounded-full px-2 py-0.5 text-xs font-medium ${c.is_blocked ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'}`}>
                                            {c.is_blocked ? 'Blocked' : 'Active'}
                                        </button>
                                    </td>
                                    <td className="px-4 py-3">
                                        <Link href={route('admin.customers.show', c.id)} className="text-xs text-indigo-600 hover:underline">View</Link>
                                    </td>
                                </tr>
                            ))}
                            {customers.data.length === 0 && <tr><td colSpan={7} className="px-4 py-10 text-center text-slate-400">No customers yet</td></tr>}
                        </tbody>
                    </table>

                    {customers.last_page > 1 && (
                        <div className="flex items-center justify-between border-t px-4 py-3 text-sm text-slate-500">
                            <span>Showing {customers.from}–{customers.to} of {customers.total}</span>
                            <div className="flex gap-1">
                                {customers.links.map((link, i) => (
                                    <button key={i} disabled={!link.url} onClick={() => link.url && router.visit(link.url)} className={`rounded px-2 py-1 text-xs ${link.active ? 'bg-indigo-600 text-white' : 'hover:bg-slate-100 disabled:opacity-40'}`} dangerouslySetInnerHTML={{ __html: link.label }} />
                                ))}
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
        </AdminLayout>
    );
}
