import { Head, router, useForm } from '@inertiajs/react';
import {
    AlertTriangle,
    ArrowUpRight,
    CheckCircle2,
    ClipboardCheck,
    Clock3,
    LogOut,
    MapPin,
    MessageSquarePlus,
    Phone,
    RefreshCw,
    Search,
    Send,
    Undo2,
    Wrench,
    X,
} from 'lucide-react';
import { useEffect, useState, type FormEvent } from 'react';
import { NativeSelect, FormField } from '@/components/crm/native-select';
import { EmptyState } from '@/components/crm/page-header';
import { StatusPill } from '@/components/crm/status-badge';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { formatDateTime, formatRelative } from '@/lib/format';
import { cn } from '@/lib/utils';
import type {
    CompletionClaim,
    PublicStatusTicket,
    TicketStatusBoardProps,
    TicketStatusTone,
} from '@/types';

/** The textarea styling the dialogs use, matching the shared Input. */
const textareaClassName =
    'border-input dark:bg-input/30 flex min-h-[90px] w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]';

/**
 * The shared board itself.
 *
 * One status at a time, because the holder came to answer one question: what is
 * waiting on a crew. It refreshes itself quietly so a board left open on a
 * workshop screen stays current, and every row carries the three things that
 * decide who drives where — the suburb, the crew already on it, and how long it
 * has been sitting.
 */
/**
 * A board action waiting on the person reading: a note, a claim that the work
 * is finished, the review that completes it, or the review that sends it back.
 */
type BoardAction = {
    kind: 'note' | 'review' | 'complete' | 'sendBack';
    ticket: PublicStatusTicket;
    claim: CompletionClaim | null;
};

export default function TicketStatusBoard({
    viewer,
    statuses,
    current,
    filters,
    tickets,
    totals,
    can,
    reviews,
    resolutionOptions,
}: TicketStatusBoardProps) {
    const [search, setSearch] = useState(filters.search);
    const [refreshing, setRefreshing] = useState(false);
    const [action, setAction] = useState<BoardAction | null>(null);

    useEffect(() => {
        setSearch(filters.search);
    }, [filters.search]);

    const visit = (params: Record<string, string | null>) => {
        router.get(
            '/ticket-status/board',
            { ...filters, ...params },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            },
        );
    };

    // A silent poll: the board is often the second screen on a desk, and a page
    // that went stale an hour ago is worse than no page at all.
    useEffect(() => {
        const timer = window.setInterval(() => {
            // The review queue is part of what a board left open must keep
            // current: a claim arriving is the reason an admin is watching it.
            router.reload({
                only: ['tickets', 'statuses', 'totals', 'reviews'],
            });
        }, 60000);

        return () => window.clearInterval(timer);
    }, []);

    const refresh = () => {
        setRefreshing(true);

        router.reload({
            only: ['tickets', 'statuses', 'totals', 'reviews'],
            onFinish: () => setRefreshing(false),
        });
    };

    const overdue = (ticket: PublicStatusTicket) =>
        ticket.days_waiting >= 3 || ticket.priority.value === 'urgent';

    return (
        <>
            <Head title="Ticket status board">
                <meta name="robots" content="noindex,nofollow" />
            </Head>

            <div className="flex flex-col gap-4">
                <section className="ring-hairline bg-card shadow-card overflow-hidden rounded-xl ring-1">
                    <div className="border-hairline flex flex-col gap-3 border-b px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
                        <div className="min-w-0">
                            <p className="text-muted-foreground text-[11px] font-medium tracking-wide uppercase">
                                {viewer.name}
                                {viewer.is_staff
                                    ? viewer.role
                                        ? ` · ${viewer.role}`
                                        : ' · staff access'
                                    : ' · shared link'}
                            </p>
                            <h1 className="mt-1 flex flex-wrap items-baseline gap-x-2.5 gap-y-1 text-xl font-semibold tracking-tight">
                                {current.label}
                                <span className="crm-num text-muted-foreground text-sm font-normal">
                                    {totals.waiting_on_installer} waiting on a
                                    crew
                                    {statuses.find(
                                        (status) =>
                                            status.value === 'waiting_on_installer',
                                    )
                                        ? `
                                        · ${statuses.find((status) => status.value === 'waiting_on_installer')?.count ?? 0}
                                        on this queue`
                                        : ''}
                                </span>
                            </h1>
                            <p className="text-muted-foreground mt-1 max-w-2xl text-xs leading-relaxed">
                                {current.description}
                            </p>
                        </div>

                        <div className="flex shrink-0 items-center gap-4">
                            <div className="text-right">
                                <p className="text-muted-foreground text-[10px] font-medium tracking-wide uppercase">
                                    Oldest
                                </p>
                                <p
                                    className={cn(
                                        'crm-num text-sm font-semibold',
                                        totals.oldest_days >= 7
                                            ? 'text-danger'
                                            : totals.oldest_days >= 3
                                              ? 'text-warning'
                                              : 'text-foreground',
                                    )}
                                >
                                    {totals.oldest_days === 0
                                        ? 'Today'
                                        : `${totals.oldest_days} days`}
                                </p>
                            </div>

                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={refresh}
                                disabled={refreshing}
                            >
                                <RefreshCw
                                    className={cn(refreshing && 'animate-spin')}
                                />
                                <span className="hidden sm:inline">Refresh</span>
                            </Button>

                            <Button
                                type="button"
                                variant="ghost"
                                size="sm"
                                onClick={() => router.post('/ticket-status/logout')}
                                aria-label="Sign out of the status board"
                            >
                                <LogOut />
                                <span className="hidden sm:inline">
                                    Sign out
                                </span>
                            </Button>
                        </div>
                    </div>

                    <div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
                        <div className="flex flex-wrap gap-1">
                            {statuses.map((status) => (
                                <button
                                    key={status.value}
                                    type="button"
                                    onClick={() => visit({ status: status.value })}
                                    aria-pressed={status.value === filters.status}
                                    className={cn(
                                        'inline-flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors',
                                        status.value === filters.status
                                            ? 'bg-muted text-foreground ring-hairline ring-1'
                                            : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground',
                                    )}
                                >
                                    {status.label}
                                    <span className="crm-num bg-background/70 ring-hairline rounded-full px-1.5 text-[10px] ring-1">
                                        {status.count}
                                    </span>
                                </button>
                            ))}
                        </div>

                        <form
                            className="relative w-full sm:max-w-xs"
                            onSubmit={(event) => {
                                event.preventDefault();
                                visit({ search: search.trim() || null });
                            }}
                        >
                            <Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2" />
                            <Input
                                value={search}
                                onChange={(event) => setSearch(event.target.value)}
                                placeholder="Ticket, issue, customer or suburb"
                                className="h-9 pr-8 pl-8 text-sm"
                                aria-label="Search this queue"
                            />
                            {filters.search ? (
                                <button
                                    type="button"
                                    onClick={() => visit({ search: null })}
                                    aria-label="Clear the search"
                                    className="text-muted-foreground hover:text-foreground absolute top-1/2 right-2 -translate-y-1/2 rounded p-0.5"
                                >
                                    <X className="size-3.5" />
                                </button>
                            ) : null}
                        </form>
                    </div>
                </section>

                {reviews.length > 0 ? (
                    <section className="ring-hairline bg-card shadow-card rounded-xl ring-1">
                        <header className="border-hairline flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3 sm:px-5">
                            <div className="flex items-center gap-3">
                                <span className="bg-warning-soft text-warning flex size-8 shrink-0 items-center justify-center rounded-lg">
                                    <ClipboardCheck className="size-4" />
                                </span>
                                <div>
                                    <h2 className="text-sm font-semibold tracking-tight">
                                        Waiting on completion review
                                    </h2>
                                    <p className="text-muted-foreground text-xs leading-relaxed">
                                        A crew has said the work is done.
                                        Completing it records the outcome, so
                                        it is an Admin's call.
                                    </p>
                                </div>
                            </div>
                            <span className="crm-num bg-warning-soft text-warning rounded-full px-2 py-0.5 text-xs font-semibold">
                                {reviews.length}
                            </span>
                        </header>

                        <ul className="divide-hairline divide-y">
                            {reviews.map((row) => (
                                <li
                                    key={row.id}
                                    className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-start sm:justify-between sm:px-5"
                                >
                                    <div className="min-w-0 space-y-1">
                                        <div className="flex flex-wrap items-center gap-2">
                                            <span className="crm-num text-xs font-semibold">
                                                {row.ticket.number}
                                            </span>
                                            <StatusPill
                                                tone={row.ticket.status.color}
                                            >
                                                {row.ticket.status.label}
                                            </StatusPill>
                                            {row.ticket.suburb ? (
                                                <span className="text-muted-foreground inline-flex items-center gap-1 text-[11px]">
                                                    <MapPin className="size-3" />
                                                    {row.ticket.suburb}
                                                </span>
                                            ) : null}
                                            {row.ticket.installer ? (
                                                <span className="text-muted-foreground inline-flex items-center gap-1 text-[11px]">
                                                    <Wrench className="size-3" />
                                                    {row.ticket.installer}
                                                </span>
                                            ) : null}
                                        </div>
                                        <p className="text-sm font-medium">
                                            {row.ticket.issue}
                                        </p>
                                        <p className="text-muted-foreground text-[11px]">
                                            {row.claim.requested_by}
                                            {row.claim.requested_at
                                                ? ` · sent ${formatRelative(row.claim.requested_at)}`
                                                : ''}
                                            {row.waiting_days > 0
                                                ? ` · waiting ${row.waiting_days}d`
                                                : ' · today'}
                                        </p>
                                        <p className="border-hairline mt-1 border-l-2 pl-2 text-xs leading-relaxed whitespace-pre-line">
                                            {row.claim.note}
                                        </p>
                                    </div>

                                    <div className="flex shrink-0 flex-wrap gap-2">
                                        <Button
                                            size="sm"
                                            onClick={() =>
                                                setAction({
                                                    kind: 'complete',
                                                    ticket: row.ticket,
                                                    claim: row.claim,
                                                })
                                            }
                                        >
                                            <CheckCircle2 />
                                            Completed
                                        </Button>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() =>
                                                setAction({
                                                    kind: 'sendBack',
                                                    ticket: row.ticket,
                                                    claim: row.claim,
                                                })
                                            }
                                        >
                                            <Undo2 />
                                            Send back
                                        </Button>
                                    </div>
                                </li>
                            ))}
                        </ul>
                    </section>
                ) : null}

                {tickets.length === 0 ? (
                    <section className="ring-hairline bg-card shadow-card rounded-xl ring-1">
                        <EmptyState
                            icon={
                                filters.search
                                    ? Search
                                    : current.label === 'Waiting on installer'
                                      ? CheckCircle2
                                      : Clock3
                            }
                            title={
                                filters.search
                                    ? 'Nothing matches that search'
                                    : 'Nothing in this queue'
                            }
                            description={
                                filters.search
                                    ? 'Try a ticket number, a suburb, or part of the issue.'
                                    : current.value === 'waiting_on_installer'
                                      ? 'Every ticket on this board has been picked up. The office will put the next one here.'
                                      : `No tickets are sitting in "${current.label}" right now.`
                            }
                        />
                    </section>
                ) : (
                    <ul className="grid gap-2.5">
                        {tickets.map((ticket) => (
                            <li key={ticket.id}>
                                <article
                                    className={cn(
                                        'ring-hairline bg-card shadow-card rounded-xl px-4 py-3 ring-1',
                                        overdue(ticket) &&
                                            'ring-warning/40 bg-warning/[0.04]',
                                    )}
                                >
                                    <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
                                        <div className="min-w-0 flex-1">
                                            <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                                                <span className="crm-num text-xs font-semibold">
                                                    {ticket.number}
                                                </span>
                                                <StatusPill tone={ticket.priority.color}>
                                                    {ticket.priority.label}
                                                </StatusPill>
                                                <StatusPill tone={ticket.status.color}>
                                                    {ticket.status.label}
                                                </StatusPill>
                                                {ticket.job_number ? (
                                                    <span className="crm-num text-muted-foreground text-[11px]">
                                                        Job {ticket.job_number}
                                                    </span>
                                                ) : null}
                                            </div>

                                            <p className="mt-1.5 text-sm leading-snug font-medium">
                                                {ticket.issue}
                                            </p>

                                            <div className="text-muted-foreground mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px]">
                                                {ticket.customer ? (
                                                    <span className="text-foreground/80 font-medium">
                                                        {ticket.customer}
                                                    </span>
                                                ) : null}
                                                {ticket.suburb ? (
                                                    <span className="inline-flex items-center gap-1">
                                                        <MapPin className="size-3" />
                                                        {ticket.suburb}
                                                    </span>
                                                ) : null}
                                                {ticket.installer ? (
                                                    <span className="inline-flex items-center gap-1">
                                                        <Wrench className="size-3" />
                                                        {ticket.installer}
                                                    </span>
                                                ) : (
                                                    <span className="text-warning inline-flex items-center gap-1 font-medium">
                                                        <AlertTriangle className="size-3" />
                                                        No crew assigned
                                                    </span>
                                                )}
                                                {ticket.owner ? (
                                                    <span>
                                                        Desk: {ticket.owner}
                                                    </span>
                                                ) : null}
                                            </div>
                                        </div>

                                        <div className="flex shrink-0 items-center gap-4 sm:flex-col sm:items-end sm:gap-1.5">
                                            <span
                                                className={cn(
                                                    'crm-num rounded-md px-2 py-0.5 text-xs font-semibold',
                                                    overdue(ticket)
                                                        ? 'bg-warning-soft text-warning'
                                                        : 'bg-muted text-muted-foreground',
                                                )}
                                            >
                                                {ticket.days_waiting === 0
                                                    ? 'Today'
                                                    : `${ticket.days_waiting}d`}
                                            </span>

                                            {ticket.phone ? (
                                                <a
                                                    href={`tel:${ticket.phone.replace(/\s+/g, '')}`}
                                                    className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-[11px] font-medium"
                                                >
                                                    <Phone className="size-3" />
                                                    {ticket.phone}
                                                </a>
                                            ) : null}
                                        </div>
                                    </div>

                                    <p className="text-muted-foreground/70 mt-2 flex flex-wrap items-center gap-x-2 border-t border-hairline pt-1.5 text-[10px]">
                                        <Clock3 className="size-3" />
                                        {ticket.status.waiting_on}
                                        {ticket.status_changed_at
                                            ? ` since ${formatRelative(ticket.status_changed_at)}`
                                            : ''}
                                        {ticket.reported_at
                                            ? ` · reported ${formatDateTime(ticket.reported_at)}`
                                            : ''}
                                    </p>

                                    {ticket.completion?.state.is_pending ? (
                                        <p className="text-warning mt-2 flex items-start gap-1.5 text-[11px] font-medium">
                                            <ClipboardCheck className="mt-0.5 size-3 shrink-0" />
                                            <span>
                                                Sent for review by{' '}
                                                {ticket.completion.requested_by}
                                                {ticket.completion.requested_at
                                                    ? ` ${formatRelative(ticket.completion.requested_at)}`
                                                    : ''}
                                                {' — '}an Admin or Super
                                                Admin completes it.
                                            </span>
                                        </p>
                                    ) : null}

                                    {ticket.completion?.state.value ===
                                    'sent_back' ? (
                                        <p className="bg-danger-soft text-danger mt-2 rounded-lg px-2.5 py-1.5 text-[11px] leading-relaxed">
                                            Sent back
                                            {ticket.completion.reviewed_by
                                                ? ` by ${ticket.completion.reviewed_by}`
                                                : ''}
                                            :{' '}
                                            {ticket.completion.review_note ??
                                                'ring the office for what is still missing'}
                                        </p>
                                    ) : null}

                                    {can.note ||
                                    (can.review &&
                                        !ticket.completion?.state.is_pending) ||
                                    (can.complete &&
                                        ticket.completion?.state.is_pending) ? (
                                        <div className="border-hairline mt-2 flex flex-wrap items-center gap-2 border-t pt-2">
                                            {can.note ? (
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() =>
                                                        setAction({
                                                            kind: 'note',
                                                            ticket,
                                                            claim: ticket.completion,
                                                        })
                                                    }
                                                >
                                                    <MessageSquarePlus />
                                                    Add note
                                                </Button>
                                            ) : null}

                                            {can.review &&
                                            !ticket.completion?.state
                                                .is_pending ? (
                                                <Button
                                                    variant="outline"
                                                    size="sm"
                                                    onClick={() =>
                                                        setAction({
                                                            kind: 'review',
                                                            ticket,
                                                            claim: ticket.completion,
                                                        })
                                                    }
                                                >
                                                    <Send />
                                                    Ready for review
                                                </Button>
                                            ) : null}

                                            {can.complete &&
                                            ticket.completion?.state
                                                .is_pending ? (
                                                <>
                                                    <Button
                                                        size="sm"
                                                        onClick={() =>
                                                            setAction({
                                                                kind: 'complete',
                                                                ticket,
                                                                claim: ticket.completion,
                                                            })
                                                        }
                                                    >
                                                        <CheckCircle2 />
                                                        Completed
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() =>
                                                            setAction({
                                                                kind: 'sendBack',
                                                                ticket,
                                                                claim: ticket.completion,
                                                            })
                                                        }
                                                    >
                                                        <Undo2 />
                                                        Send back
                                                    </Button>
                                                </>
                                            ) : null}
                                        </div>
                                    ) : null}
                                </article>
                            </li>
                        ))}
                    </ul>
                )}

                <p className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-[11px]">
                    <span className="inline-flex items-center gap-1">
                        <ArrowUpRight className="size-3" />
                        Showing {totals.shown} of this queue
                    </span>
                    <span aria-hidden>·</span>
                    <span>
                        {can.complete
                            ? 'You can add a note, send a ticket for review, and complete it once it has been reviewed'
                            : can.note
                              ? 'You can add a note and send a ticket for review; an Admin or Super Admin completes it'
                              : 'Read-only: nothing here can be changed'}
                    </span>
                    {viewer.expires_at ? (
                        <>
                            <span aria-hidden>·</span>
                            <span>
                                This link stops working on{' '}
                                {formatDateTime(viewer.expires_at)}
                            </span>
                        </>
                    ) : null}
                </p>
            </div>

            {action ? (
                <BoardActionDialog
                    action={action}
                    resolutionOptions={resolutionOptions}
                    onClose={() => setAction(null)}
                />
            ) : null}
        </>
    );
}

/**
 * The one dialog the board needs, switched by whatever was pressed.
 *
 * The copy differs because the four actions are different jobs: a note is
 * something to say, a claim is a question asked of the office, completing is
 * the answer to it, and sending back is the answer that is not yet a yes.
 */
const ACTION_COPY: Record<
    BoardAction['kind'],
    { title: string; description: string; submit: string; path: string }
> = {
    note: {
        title: 'Add a note',
        description:
            'Everyone who can see this ticket reads it, including the office and the next crew on it.',
        submit: 'Add note',
        path: 'note',
    },
    review: {
        title: 'Ready for review',
        description:
            'Say how the work was completed. An Admin or Super Admin approves it before the ticket is completed.',
        submit: 'Send for review',
        path: 'review',
    },
    complete: {
        title: 'Complete this ticket',
        description:
            'Approving records the outcome and moves the ticket to Resolved, signed by you.',
        submit: 'Complete ticket',
        path: 'complete',
    },
    sendBack: {
        title: 'Send it back',
        description:
            'The ticket stays where it is and the crew is told what is still needing doing.',
        submit: 'Send back',
        path: 'send-back',
    },
};

function BoardActionDialog({
    action,
    resolutionOptions,
    onClose,
}: {
    action: BoardAction;
    resolutionOptions: Array<TicketStatusTone & { description: string }>;
    onClose: () => void;
}) {
    const copy = ACTION_COPY[action.kind];

    const form = useForm({
        body: '',
        note: '',
        resolution: action.claim?.note ?? '',
        resolution_code: '',
        review_note: '',
    });

    const submit = (event: FormEvent) => {
        event.preventDefault();

        form.post(
            `/ticket-status/board/tickets/${action.ticket.id}/${copy.path}`,
            {
                preserveScroll: true,
                onSuccess: () => onClose(),
            },
        );
    };

    return (
        <Dialog open onOpenChange={(open) => (open ? null : onClose())}>
            <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle>{copy.title}</DialogTitle>
                    <DialogDescription>
                        <span className="crm-num">{action.ticket.number}</span>
                        {' · '}
                        {action.ticket.issue}
                        <span className="mt-1 block">{copy.description}</span>
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-3">
                    {action.claim && action.kind !== 'review' ? (
                        <div className="bg-muted/60 ring-hairline rounded-lg px-3 py-2 ring-1">
                            <p className="text-muted-foreground text-[11px]">
                                Sent for review by {action.claim.requested_by}
                                {action.claim.requested_at
                                    ? ` ${formatRelative(action.claim.requested_at)}`
                                    : ''}
                            </p>
                            <p className="mt-1 text-xs leading-relaxed whitespace-pre-line">
                                {action.claim.note}
                            </p>
                        </div>
                    ) : null}

                    {action.kind === 'note' ? (
                        <FormField
                            label="The note"
                            htmlFor="board-note"
                            error={form.errors.body}
                            required
                        >
                            <textarea
                                id="board-note"
                                className={textareaClassName}
                                value={form.data.body}
                                onChange={(event) =>
                                    form.setData('body', event.target.value)
                                }
                                placeholder="What was done, what is still needed, who to ring…"
                                required
                            />
                        </FormField>
                    ) : null}

                    {action.kind === 'review' ? (
                        <FormField
                            label="How was the work completed?"
                            htmlFor="board-review-note"
                            error={form.errors.note}
                            hint="This becomes the ticket's resolution once it is approved."
                            required
                        >
                            <textarea
                                id="board-review-note"
                                className={textareaClassName}
                                value={form.data.note}
                                onChange={(event) =>
                                    form.setData('note', event.target.value)
                                }
                                placeholder="Replaced the inverter fan, tested the system, export limit restored…"
                                required
                            />
                        </FormField>
                    ) : null}

                    {action.kind === 'complete' ? (
                        <>
                            <FormField
                                label="How it was completed"
                                htmlFor="board-complete-resolution"
                                error={form.errors.resolution}
                                hint="Change the crew's words if they need tightening; they are what the ticket records."
                            >
                                <textarea
                                    id="board-complete-resolution"
                                    className={textareaClassName}
                                    value={form.data.resolution}
                                    onChange={(event) =>
                                        form.setData(
                                            'resolution',
                                            event.target.value,
                                        )
                                    }
                                />
                            </FormField>

                            <FormField
                                label="Kind of outcome"
                                htmlFor="board-complete-code"
                                error={form.errors.resolution_code}
                                required
                            >
                                <NativeSelect
                                    id="board-complete-code"
                                    value={form.data.resolution_code}
                                    onChange={(event) =>
                                        form.setData(
                                            'resolution_code',
                                            event.target.value,
                                        )
                                    }
                                    required
                                >
                                    <option value="">
                                        Choose what kind of outcome this was
                                    </option>
                                    {resolutionOptions.map((option) => (
                                        <option
                                            key={option.value}
                                            value={option.value}
                                        >
                                            {option.label}
                                        </option>
                                    ))}
                                </NativeSelect>
                            </FormField>

                            <FormField
                                label="Review note (optional)"
                                htmlFor="board-complete-note"
                                error={form.errors.note}
                                hint="Anything the crew or the desk should know about the decision."
                            >
                                <Input
                                    id="board-complete-note"
                                    value={form.data.note}
                                    onChange={(event) =>
                                        form.setData('note', event.target.value)
                                    }
                                    placeholder="Checked the photos against the job sheet"
                                />
                            </FormField>
                        </>
                    ) : null}

                    {action.kind === 'sendBack' ? (
                        <FormField
                            label="What still needs doing?"
                            htmlFor="board-send-back"
                            error={form.errors.review_note}
                            hint="The crew sees this on the ticket, so be specific."
                            required
                        >
                            <textarea
                                id="board-send-back"
                                className={textareaClassName}
                                value={form.data.review_note}
                                onChange={(event) =>
                                    form.setData(
                                        'review_note',
                                        event.target.value,
                                    )
                                }
                                placeholder="No photo of the isolator, and the export limit was not confirmed"
                                required
                            />
                        </FormField>
                    ) : null}

                    <div className="flex items-center justify-end gap-2 pt-1">
                        <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={onClose}
                        >
                            Cancel
                        </Button>
                        <Button
                            type="submit"
                            size="sm"
                            disabled={form.processing}
                        >
                            {form.processing ? 'Saving…' : copy.submit}
                        </Button>
                    </div>
                </form>
            </DialogContent>
        </Dialog>
    );
}
