import { useState } from 'react';
import { useForm } from '@inertiajs/react';
import { Loader2, Check, RotateCcw, X, AlertTriangle, Pencil } from 'lucide-react';
import { Button } from '@/Components/ui/button';
import { useToast } from '@/Components/Toast';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/Components/ui/dialog';
import { DecisionBar } from '@/Components/MenuSampleOrders/DecisionBar';
import { DecisionConfirmDialog } from '@/Components/MenuSampleOrders/DecisionConfirmDialog';

// Approve/Revise/Reject panel for a stage. `routes` = {approve,revise,reject}.
// `initialData` seeds extra stage fields into the form; `renderFields(form)` renders inputs
// bound to that form (Finance PaymentRating, CEO Approved*, AST codes). They submit together
// with the comment. `approveLabel` customises the primary button (e.g. "Input AST").
// `approveWarning` (SM/CEO) — when set, Approve first opens a credit-limit warning modal
// (legacy checkButton: AR over limit / overdue / still outstanding) before submitting.
export function StageActionPanel({ routes, canAct = true, initialData = {}, renderFields = null, approveLabel = 'Approve', approveWarning = null, summary = null }) {
    const { show: showToast } = useToast();
    const form = useForm({ comment: '', ...initialData });
    const [guardOpen, setGuardOpen] = useState(false);
    // Every decision goes through a confirm step that re-shows the comment, so an approver
    // reads back what they are sending instead of firing off whatever was left in the dock.
    const [confirm, setConfirm] = useState(null);   // 'approve' | 'revise' | 'reject'

    const act = (url, okMsg) => {
        form.post(url, {
            preserveScroll: true,
            onError: () => showToast('Please check the form and try again.', 'error'),
        });
    };

    const approve = () => act(routes.approve, 'Berhasil disetujui');
    const revise = () => act(routes.revise, 'Dikembalikan untuk revisi');
    const reject = () => act(routes.reject, 'Pengajuan ditolak');

    // The guard dialog doubles as the confirm step, so it enforces the comment itself.
    const guardBlocked = form.processing || !form.data.comment.trim();

    const runConfirmed = () => {
        const which = confirm;
        setConfirm(null);
        if (which === 'approve') approve();
        else if (which === 'revise') revise();
        else if (which === 'reject') reject();
    };

    // Legacy: the Approve button runs checkButton() — if the customer's AR breaches the credit
    // limit / is overdue / still outstanding, a warning modal appears before approval.
    // The credit-limit guard still comes FIRST when it applies — it is a different question
    // ("your AR is over limit, still approve?") than the confirm step.
    const onApprove = () => {
        if (approveWarning) setGuardOpen(true);
        else setConfirm('approve');
    };

    if (!canAct) {
        return <p className="text-sm text-muted-foreground">Pengajuan ini sudah tidak berada di tahap ini.</p>;
    }

    return (
        <>
            {/* Stage inputs live as a normal card IN THE FLOW — a dock stuffed with five
                fields would swallow half the viewport (the CEO stage). Same form object,
                so everything still submits together. */}
            {/* Heading sits ON THE SAME ROW as the inputs. It used to own a line of its own
                plus a divider, which is right for the CEO stage (five fields) but turned the
                Finance stage — one 256px select — into a full-width card that was mostly title
                and rule. flex-wrap keeps both honest: one field stays inline, five wrap under. */}
            {renderFields && (
                <section className="relative rounded-xl border border-border bg-card px-4 py-3 shadow-sm">
                    <div className="flex flex-wrap items-center gap-x-5 gap-y-3">
                        <h3 className="m-0 flex shrink-0 items-center gap-2 text-xs font-bold uppercase tracking-wide text-foreground">
                            <span className="inline-grid size-6 shrink-0 place-items-center rounded-full border border-primary/50 bg-transparent text-primary" aria-hidden="true">
                                <Pencil className="size-3" strokeWidth={2.5} />
                            </span>
                            Approval Details
                        </h3>
                        <div className="min-w-0 flex-1">{renderFields(form)}</div>
                    </div>
                </section>
            )}

        <DecisionBar>
            {/* Context first — a pill holding nothing but three buttons reads as a stray box. */}
            {summary && (
                <>
                    <span className="hidden text-[12px] font-medium text-muted-foreground sm:inline">{summary}</span>
                    <span className="hidden h-6 w-px bg-border sm:block" />
                </>
            )}
            {/* Button set mirrors the Sample Orders decision bar: Reject · Revise · Approve (rightmost). */}
            <div className="flex w-full items-center gap-2 sm:w-auto sm:gap-2.5">
                <Button type="button" variant="outline" disabled={form.processing} onClick={() => setConfirm('reject')}
                    className="h-9 flex-1 rounded-lg border border-danger/40 bg-card px-4 text-xs font-bold text-danger hover:bg-danger/10 sm:flex-none">
                    Reject
                </Button>
                <Button type="button" variant="outline" disabled={form.processing} onClick={() => setConfirm('revise')}
                    className="h-9 flex-1 rounded-lg border border-primary bg-card px-4 text-xs font-bold text-primary hover:bg-primary/10 sm:flex-none">
                    Revise
                </Button>
                <Button type="button" disabled={form.processing} onClick={onApprove}
                    className="h-9 flex-1 rounded-lg bg-linear-to-br from-violet-500 to-primary px-4 text-xs font-bold text-white shadow-sm transition-[filter] hover:brightness-105 sm:flex-none">
                    {form.processing ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}{approveLabel}
                </Button>
            </div>

            </DecisionBar>

        {/* Credit-limit warning modal (legacy modal-ardetail). This dialog IS the confirm step
            when it applies — the comment lives here, so the approver is not asked for it twice.
            Comment is REQUIRED for all three: acting despite an over-limit AR needs a reason on
            record, including "Approve anyway". */}
            <Dialog open={guardOpen} onOpenChange={(o) => { if (!o) setGuardOpen(false); }}>
                <DialogContent className="bg-card">
                    <DialogHeader>
                        <DialogTitle className="flex items-center gap-2 text-destructive">
                            <AlertTriangle className="size-5" />Credit Limit Warning
                        </DialogTitle>
                        <DialogDescription>{approveWarning}</DialogDescription>
                    </DialogHeader>

                    <label className="block">
                        <span className="mb-1.5 block text-[12px] font-semibold text-muted-foreground">
                            Comment <span className="text-danger-text">*</span>
                        </span>
                        <textarea
                            value={form.data.comment}
                            onChange={(e) => form.setData('comment', e.target.value)}
                            rows={3}
                            autoFocus
                            placeholder="Reason for this decision…"
                            className="w-full resize-y rounded-lg border border-input bg-card px-3 py-2.5 text-[13px] text-foreground outline-none transition-colors focus:border-primary"
                        />
                        <p className="m-0 mt-1.5 text-[11px] text-muted-foreground">Required — you can't continue while it's empty.</p>
                    </label>
                    {form.errors.comment && <p className="m-0 text-[12px] font-semibold text-danger-text">{form.errors.comment}</p>}

                    <DialogFooter className="gap-2 sm:justify-start">
                        <div className="flex flex-wrap gap-2">
                            {/* Comment is OPTIONAL for approve (per the app rule), so "Approve anyway"
                                is only gated by form.processing — it must not be dead on open. */}
                            <Button disabled={form.processing} onClick={() => { setGuardOpen(false); approve(); }}>
                                <Check className="mr-2 size-4" />Approve anyway
                            </Button>
                            <Button variant="outline" disabled={guardBlocked} onClick={() => { setGuardOpen(false); revise(); }}>
                                <RotateCcw className="mr-2 size-4" />Revise
                            </Button>
                            <Button variant="outline" disabled={guardBlocked}
                                className="border-destructive/40 text-destructive hover:bg-destructive/10"
                                onClick={() => { setGuardOpen(false); reject(); }}>
                                <X className="mr-2 size-4" />Reject
                            </Button>
                        </div>
                        <Button variant="outline" disabled={form.processing} onClick={() => setGuardOpen(false)}>Cancel</Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>


        <DecisionConfirmDialog
            action={confirm}
            onCancel={() => setConfirm(null)}
            onConfirm={runConfirmed}
            comment={form.data.comment}
            onCommentChange={(v) => form.setData('comment', v)}
            processing={form.processing}
            error={form.errors.comment}
            label={confirm === 'approve' ? approveLabel : undefined}
        />
        </>
    );
}
