import { useState } from 'react'
import { useForm } from '@inertiajs/react'
import { Loader2, XCircle } from 'lucide-react'
import { Button } from '@/Components/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/Components/ui/dialog'
import { useToast } from '@/Components/Toast'

// Cancel Complaint & Returns (legacy btn-cancel / btn-cannotCancel). Enabled only at header
// status {1,2,3} — outside it the legacy drew a disabled "Cannot Cancel" twin, so this does too.
// Rendered only when capabilities.canCancel, which the server sets on the View Request and View
// All screens alone (ComplainPolicy::CANCEL_VIEWS).
//
// Cancel is DESTRUCTIVE → danger-outline, never the violet primary. Batal stays the FIRST
// child of the footer per the destructive-dialog rule in .claude/rules/ui-conventions.md.
const CANCELLABLE_STATUSES = [1, 2, 3]
const CANCEL_BTN = 'inline-flex h-9 items-center gap-1.5 rounded-lg border border-danger/40 bg-card px-4 text-xs font-bold text-danger-text transition-colors hover:border-danger hover:bg-danger/10'
const DANGER_BTN = 'h-9 rounded-lg border border-danger/40 bg-card px-4 text-xs font-bold text-danger-text opacity-60'
const DANGER_SOLID_BTN = 'h-9 rounded-lg bg-danger px-4 text-xs font-bold text-white shadow-sm transition-colors hover:bg-danger/90'

export function CancelComplaintButton({ complaintId, statusId }) {
    const { show: showToast } = useToast()
    const [open, setOpen] = useState(false)
    const form = useForm({ remark: '' })

    if (!CANCELLABLE_STATUSES.includes(Number(statusId))) {
        return (
            <Button type="button" variant="ghost" disabled className={DANGER_BTN}>
                Cannot Cancel
            </Button>
        )
    }

    const confirm = () => {
        form.post(route('complaints.cancel', complaintId), {
            onError: () => showToast('Please check the form and try again.', 'error'),
            preserveScroll: true,
            onSuccess: () => { setOpen(false); form.reset() },   // side effect only — the toast comes from the server
        })
    }

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button type="button" variant="ghost" className={CANCEL_BTN}>
                    <XCircle className="size-3.5" /> Cancel Complaint &amp; Returns
                </Button>
            </DialogTrigger>
            <DialogContent className="bg-card">
                <DialogHeader>
                    <DialogTitle>Cancel this complaint?</DialogTitle>
                </DialogHeader>
                <p className="m-0 text-xs text-muted-foreground">
                    The report and every product line will be set to <strong>Cancel</strong>. This cannot be undone here.
                </p>
                <label className="block">
                    <span className="mb-1.5 block text-[12px] font-semibold text-muted-foreground">Remark (optional)</span>
                    <textarea
                        value={form.data.remark}
                        onChange={(e) => form.setData('remark', e.target.value)}
                        rows={3}
                        placeholder="Why is this being cancelled…"
                        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"
                    />
                    {form.errors.remark && <p className="m-0 mt-1.5 text-[12px] font-semibold text-danger-text">{form.errors.remark}</p>}
                </label>
                <DialogFooter className="gap-2 sm:justify-start">
                    <Button type="button" variant="outline" disabled={form.processing} onClick={() => setOpen(false)}>
                        Keep Complaint
                    </Button>
                    <Button type="button" disabled={form.processing} onClick={confirm} className={DANGER_SOLID_BTN}>
                        {form.processing ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}Yes, Cancel It
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    )
}
