import { Head, Link, router } from '@inertiajs/react';
import { Search, Trash2 } from 'lucide-react';
import type { FormEvent } from 'react';
import { useState } from 'react';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { dashboard } from '@/routes/admin';
import { destroy, index } from '@/routes/admin/subscribers';

type Paginated<T> = {
    data: T[];
    current_page: number;
    last_page: number;
    total: number;
    prev_page_url: string | null;
    next_page_url: string | null;
};

type Subscriber = { id: number; email: string; created_at: string };

type Props = {
    subscribers: Paginated<Subscriber>;
    search: string;
};

export default function Subscribers({ subscribers, search }: Props) {
    const [query, setQuery] = useState(search);

    const submit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        router.get(index.url(), query ? { search: query } : {}, {
            preserveState: true,
        });
    };

    const remove = (subscriber: Subscriber) =>
        router.delete(destroy.url(subscriber.id), { preserveScroll: true });

    return (
        <>
            <Head title="Subscribers" />
            <div className="space-y-6 p-4 sm:p-6">
                <Heading
                    title="Newsletter subscribers"
                    description={`${subscribers.total.toLocaleString()} people signed up from the website footer`}
                />

                <form onSubmit={submit} className="flex max-w-md gap-2">
                    <div className="relative flex-1">
                        <Search className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            value={query}
                            onChange={(event) => setQuery(event.target.value)}
                            placeholder="Search by email"
                            className="pl-9"
                        />
                    </div>
                    <Button variant="secondary">Search</Button>
                </form>

                <Card>
                    <CardContent className="overflow-x-auto p-0">
                        <table className="w-full text-sm">
                            <thead className="border-b text-left text-muted-foreground">
                                <tr>
                                    <th className="p-4 font-medium">Email</th>
                                    <th className="p-4 font-medium">
                                        Subscribed
                                    </th>
                                    <th className="p-4" />
                                </tr>
                            </thead>
                            <tbody>
                                {subscribers.data.map((subscriber) => (
                                    <tr
                                        key={subscriber.id}
                                        className="border-b last:border-0"
                                    >
                                        <td className="p-4">
                                            {subscriber.email}
                                        </td>
                                        <td className="p-4 whitespace-nowrap text-muted-foreground">
                                            {new Date(
                                                subscriber.created_at,
                                            ).toLocaleString()}
                                        </td>
                                        <td className="p-4 text-right">
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                aria-label={`Remove ${subscriber.email}`}
                                                onClick={() =>
                                                    remove(subscriber)
                                                }
                                            >
                                                <Trash2 />
                                            </Button>
                                        </td>
                                    </tr>
                                ))}
                                {subscribers.data.length === 0 && (
                                    <tr>
                                        <td
                                            colSpan={3}
                                            className="p-8 text-center text-muted-foreground"
                                        >
                                            No subscribers found.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </CardContent>
                </Card>

                {subscribers.last_page > 1 && (
                    <div className="flex items-center justify-between text-sm">
                        <span className="text-muted-foreground">
                            Page {subscribers.current_page} of{' '}
                            {subscribers.last_page}
                        </span>
                        <div className="flex gap-2">
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={!subscribers.prev_page_url}
                                asChild={Boolean(subscribers.prev_page_url)}
                            >
                                {subscribers.prev_page_url ? (
                                    <Link href={subscribers.prev_page_url}>
                                        Previous
                                    </Link>
                                ) : (
                                    'Previous'
                                )}
                            </Button>
                            <Button
                                variant="outline"
                                size="sm"
                                disabled={!subscribers.next_page_url}
                                asChild={Boolean(subscribers.next_page_url)}
                            >
                                {subscribers.next_page_url ? (
                                    <Link href={subscribers.next_page_url}>
                                        Next
                                    </Link>
                                ) : (
                                    'Next'
                                )}
                            </Button>
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}

Subscribers.layout = {
    breadcrumbs: [
        { title: 'Admin', href: dashboard() },
        { title: 'Subscribers', href: index() },
    ],
};
