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, Loader2, Mail } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';

interface SendEmailModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    selectedUser?: any | null;
    selectedUsers?: any[];
    selectAll?: boolean;
    currentFilters?: any;
    isBulk?: boolean;
    onSuccess?: () => void;
}

export function SendEmailModal({
    open,
    onOpenChange,
    selectedUser,
    selectedUsers = [],
    selectAll = false,
    currentFilters = {},
    isBulk = false,
    onSuccess,
}: SendEmailModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    // Access Inertia page props to pull backend validation errors (422)
    const page = usePage<any>();

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

    // Mock email templates - replace with your actual templates
    const emailTemplates = [
        { value: 'welcome', label: 'Welcome Email' },
        { value: 'reminder', label: 'Reminder Email' },
        { value: 'notification', label: 'Notification Email' },
        { value: '', label: 'No Template' },
    ];

    const defaultValues = {
        subject: '',
        message: '',
        template: '',
    };

    const handleSubmit = (data: any) => {
        if (!data.subject || !data.message) return;

        setIsSubmitting(true);

        const payload = {
            subject: data.subject,
            message: data.message,
            template: data.template,
        };

        if (isBulk) {
            const bulkPayload = {
                ...payload,
                ids: selectedUsers.map((user) => user.id),
                all_records: selectAll,
                filters: selectAll ? currentFilters : {},
            };

            router.post(route('items.bulk-action', { type: 'email' }), bulkPayload, {
                onSuccess: () => {
                    toast.success('Email(s) sent 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),
            });
        } else if (selectedUser) {
            router.post(route('items.send-email', selectedUser.id), payload, {
                onSuccess: () => {
                    toast.success('Email sent 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 title = isBulk
        ? `Send Email to ${selectedUsers.length} ${selectedUsers.length === 1 ? 'Item' : 'Items'}`
        : selectedUser
          ? `Send Email to ${selectedUser.name}`
          : 'Send Email';

    const modalDescription = 'Compose your email and select a template if needed';

    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">
                            <Mail className="h-6 w-6" />

                            <div>
                                <DialogTitle className="text-lg sm:text-xl">{title}</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}
                    >
                        {isBulk && 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>Email will be sent to all filtered items</p>
                            </div>
                        )}

                        {/* Email Template */}
                        <FormField type="select" name="template" label="Email Template" placeholder="Select a template" options={emailTemplates} />

                        {/* Subject */}
                        <FormField type="text" name="subject" label="Subject" placeholder="Email subject" required />

                        {/* Message */}
                        <FormField type="textarea" name="message" label="Message" placeholder="Type your message here" rows={6} 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} className="w-full bg-success hover:bg-brand-800 sm:w-auto">
                                {isSubmitting ? (
                                    <>
                                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                        Sending...
                                    </>
                                ) : (
                                    <>Send Email</>
                                )}
                            </Button>
                        </div>
                    </Form>
                </div>
            </DialogContent>
        </Dialog>
    );
}
