import Form from '@admin/components/form/Form';
import FormField from '@admin/components/form/FormField';
import { Button } from '@admin/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@admin/components/ui/dialog';
import { router, usePage } from '@inertiajs/react';
import { AlertCircle, ListChecks, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

interface BulkStatusEditModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    selectedItems: any[];
    selectAll?: boolean;
    totalCount?: number;
    currentFilters?: any;
    onSuccess?: () => void;
}

export function BulkStatusEditModal({
    open,
    onOpenChange,
    selectedItems,
    selectAll = false,
    totalCount = 0,
    currentFilters = {},
    onSuccess,
}: BulkStatusEditModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    // Access Inertia page props to pull backend validation errors (422)
    const page = usePage<any>();

    const statusOptions = [
        { value: 'active', label: 'Active' },
        { value: 'inactive', label: 'Inactive' },
        { value: 'pending', label: 'Pending' },
    ];

    const defaultValues = {
        status: 'active',
    };

    const handleSubmit = (data: any) => {
        setIsSubmitting(true);

        const submitData = {
            status: data.status,
            ids: selectedItems.map((item) => item.id),
            all_records: selectAll,
            filters: selectAll ? currentFilters : {},
        };

        router.post(route('items.bulk-action', { type: 'status' }), submitData, {
            onSuccess: () => {
                toast.success('Status updated successfully!');
                onOpenChange(false);
                if (onSuccess) onSuccess();
            },
            onError: (errors) => {
                console.error('Form submission errors:', errors);
                toast.error('Something went wrong. Please try again.');
            },
            onFinish: () => setIsSubmitting(false),
        });
    };

    const modalTitle = `Update Status ${selectedItems.length > 0 ? `for ${selectedItems.length} ${selectedItems.length === 1 ? 'Item' : 'Items'}` : ''}`;
    const modalDescription = 'Select a status to apply to all selected items';

    // Reset form when modal closes
    useEffect(() => {
        if (!open) {
            setIsSubmitting(false);
        }
    }, [open]);

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-h-[95vh] w-[95vw] max-w-2xl overflow-y-auto sm:w-[90vw] md:max-w-xl">
                <DialogHeader className="gap-0 pb-4">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                        <div className="flex items-center gap-3">
                            <ListChecks className="h-6 w-6" />

                            <div>
                                <DialogTitle className="text-lg sm:text-xl">{modalTitle}</DialogTitle>
                            </div>
                        </div>
                    </div>
                    <DialogDescription className="text-sm text-text-gray sm:text-base">{modalDescription}</DialogDescription>
                </DialogHeader>

                <div className="space-y-6 rounded-lg border px-2 py-4 sm:px-4 md:px-6">
                    <Form
                        submitHandler={handleSubmit}
                        defaultValues={defaultValues}
                        formClassNames="space-y-4"
                        externalErrors={(page.props as any)?.errors}
                    >
                        {selectAll && (
                            <div className="flex items-center gap-2 rounded-md border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-800">
                                <AlertCircle className="size-4" />
                                <p>All {totalCount} items will be updated</p>
                            </div>
                        )}

                        <FormField type="radio" name="status" label="Select Status" options={statusOptions} orientation="vertical" required />

                        {/* Actions */}
                        <div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                            <Button type="button" variant="outline" onClick={() => onOpenChange(false)} className="w-full sm:w-auto">
                                Cancel
                            </Button>
                            <Button
                                type="submit"
                                disabled={isSubmitting || selectedItems.length === 0}
                                className="w-full bg-success hover:bg-brand-800 sm:w-auto"
                            >
                                {isSubmitting ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Processing...
                                    </>
                                ) : (
                                    <>Update Status</>
                                )}
                            </Button>
                        </div>
                    </Form>
                </div>
            </DialogContent>
        </Dialog>
    );
}
