"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { useState } from "react";
import { api } from "@/lib/api";
import { Field } from "@/components/Field";
import { formatDate } from "@/lib/format";

export function AccountSearch() {
    const [q, setQ] = useState("");
    const { data, isFetching } = useQuery({
        queryKey: ["staff-accounts", q],
        queryFn: () => api.staff.accounts(q || undefined),
    });

    return (
        <div className="grid gap-4">
            <Field
                label="Search"
                value={q}
                onChange={(e) => setQ(e.target.value)}
                hint="Name, email, Paddle customer ID, or an instance UUID."
            />
            <div className="overflow-x-auto rounded border border-rule bg-panel">
                <table className="w-full border-collapse text-left">
                    <thead>
                        <tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
                            <th className="px-4 py-2.5">Account</th>
                            <th className="px-4 py-2.5">Billing email</th>
                            <th className="px-4 py-2.5">Status</th>
                            <th className="px-4 py-2.5">Created</th>
                        </tr>
                    </thead>
                    <tbody>
                        {(data ?? []).map((a) => (
                            <tr
                                key={a.account_id}
                                className="border-b border-rule-soft last:border-0"
                            >
                                <td className="px-4 py-3">
                                    <Link
                                        href={`/staff/accounts/${a.account_id}`}
                                        className="text-accent underline"
                                    >
                                        {a.name}
                                    </Link>
                                </td>
                                <td className="px-4 py-3 font-mono text-[0.82rem]">
                                    {a.billing_email}
                                </td>
                                <td className="px-4 py-3">{a.status}</td>
                                <td className="px-4 py-3 font-mono tabular-nums">
                                    {formatDate(a.created_at)}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                {!isFetching && (data ?? []).length === 0 && (
                    <p className="px-4 py-6 text-ink-3">
                        No account matches that. Try the instance UUID from the customer&rsquo;s
                        email.
                    </p>
                )}
            </div>
        </div>
    );
}
