import { useState } from 'react';
import { useForm } from '@inertiajs/react';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';
import { Button } from '@/Components/ui/button';
import { useToast } from '@/Components/Toast';

/**
 * Approve / Reject for the Finance, SM and CEO stages of a rebate invoice.
 *
 * The comment is entered in the CONFIRM DIALOG, never in the pill — the pill carries the
 * summary and the buttons only, and Approve is leftmost with the heavier action to its right.
 *
 * Legacy also had a Bill button here (status → 7) and Cancel (→ 6) on the detail screens. Both
 * are omitted: `salesrebateinvoice` has a foreign key to `salesrebateinvoicegeneratestatus`,
 * which defines only ids 1-5, so either write is rejected by the database. Rendering them would
 * be rendering a button that always fails. See issue #260.
 */
export function InvoiceDecisionBar({ scope, invoice }) {
    const { show: showToast } = useToast();
    const [action, setAction] = useState(null);
    const form = useForm({ comment: '' });

    const submit = () => {
        form.post(route(`generate-company-rebates.${scope}.act`, { invoice: invoice.id, action }), {
            preserveScroll: true,
            // A side effect beyond the toast (closing the dialog), which is what makes an
            // onSuccess legitimate here — the success toast itself comes from the server.
            onSuccess: () => { setAction(null); form.reset('comment'); },
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    return (
        <>
            <DecisionBar>
                <span className="text-[12px] text-muted-foreground">
                    Rebate invoice <strong className="text-foreground">#{invoice.id}</strong> · {invoice.status}
                </span>
                {/* Approve leftmost, getting heavier to the right — locked UI ruling. */}
                <div className="flex items-center gap-2.5">
                    <Button onClick={() => setAction('approve')} disabled={form.processing}>Approve</Button>
                    <Button variant="destructive" onClick={() => setAction('reject')} disabled={form.processing}>Reject</Button>
                </div>
            </DecisionBar>

            <DecisionConfirmDialog
                action={action}
                onCancel={() => setAction(null)}
                onConfirm={submit}
                comment={form.data.comment}
                onCommentChange={(v) => form.setData('comment', v)}
                processing={form.processing}
                error={form.errors.comment}
                errors={form.errors}
                commentRequired={action === 'reject'}
            />
        </>
    );
}
