import { Form, FormField } from '@admin/components/form';
import { Button } from '@admin/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@admin/components/ui/dialog';
import { type User } from '@admin/types';
import { router } from '@inertiajs/react';
import { Send } from 'lucide-react';
import { useState } from 'react';
import TextEditor from '../rich-text-editor';

interface SendEmailModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    /** Single user (non-bulk usage) */
    selectedUser?: User | null;
    /** Multiple users (bulk usage) */
    selectedUsers?: User[];
    onSuccess?: () => void;
    isBulk?: boolean;
    selectAll?: boolean;
    currentFilters?: Record<string, any>;
}

export function SendEmailModal({
    open,
    onOpenChange,
    selectedUser = null,
    selectedUsers = [],
    onSuccess,
    isBulk = false,
    selectAll = false,
    currentFilters = {},
}: SendEmailModalProps) {
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = async (data: { subject: string; body: string }) => {
        const targets = isBulk ? selectedUsers : selectedUser ? [selectedUser] : [];
        if (!targets.length) return;

        setIsLoading(true);
        const uids = targets.map((u) => u.uid).filter(Boolean);
        const mailRouteAndType = isBulk
            ? selectAll
                ? {
                      route: route('users.bulk-action'),
                      payload: {
                          type: 'email',
                          select_all: true,
                          filters: currentFilters,
                          data: {
                              content: { subject: data.subject, body: data.body },
                          },
                      },
                  }
                : {
                      route: route('users.bulk-action'),
                      payload: {
                          type: 'email',
                          ids: targets.map((t) => t.id),
                          data: {
                              ids: targets.map((t) => t.id),
                              content: { subject: data.subject, body: data.body },
                          },
                      },
                  }
            : {
                  route: route('users.send-email', { uid: uids[0] }),
                  payload: { subject: data.subject, body: data.body },
              };

        try {
            router.post(mailRouteAndType.route, mailRouteAndType.payload, {
                onSuccess: () => {
                    onOpenChange(false);
                    onSuccess?.();
                },
                onFinish: () => {
                    setIsLoading(false);
                },
            });
        } catch (error) {
            console.error('Failed to send email:', error);
            setIsLoading(false);
        }
    };

    const handleClose = () => {
        onOpenChange(false);
    };

    const bulkSummary = isBulk ? (
        <div className="mb-2 rounded-md bg-muted p-2 text-xs text-muted-foreground">
            {selectedUsers.length} recipient(s)
            {selectedUsers.length > 0 && (
                <div className="mt-1 line-clamp-2">
                    {selectedUsers
                        .slice(0, 5)
                        .map((u) => u.email)
                        .join(', ')}
                    {selectedUsers.length > 5 && ' …'}
                </div>
            )}
        </div>
    ) : null;

    const description = isBulk
        ? `Send an email to ${selectedUsers.length} selected user${selectedUsers.length === 1 ? '' : 's'}`
        : `Send an email to ${selectedUser?.name} (${selectedUser?.email})`;

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent className="sm:max-w-4xl">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <Send className="h-5 w-5" />
                        Send Email
                    </DialogTitle>
                    <DialogDescription>{description}</DialogDescription>
                </DialogHeader>

                <Form defaultValues={{ subject: '', body: '' }} submitHandler={handleSubmit} formClassNames="space-y-4">
                    {bulkSummary}
                    <div className="space-y-2">
                        <FormField name="subject" label="Subject" type="text" placeholder="Enter email subject" required />
                    </div>

                    <div>
                        <TextEditor name="body" />
                    </div>

                    <DialogFooter className="mt-20">
                        <Button type="button" variant="outline" onClick={handleClose} disabled={isLoading}>
                            Cancel
                        </Button>
                        <Button type="submit" disabled={isLoading || (!isBulk && !selectedUser) || (isBulk && selectedUsers.length === 0)}>
                            {isLoading ? 'Sending...' : 'Send Email'}
                        </Button>
                    </DialogFooter>
                </Form>
            </DialogContent>
        </Dialog>
    );
}
