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

interface Contact {
    id: number;
    name: string;
    email: string;
    phone: string | null;
    user_id: number | null;
    created_at: string | null;
}

interface ContactSendEmailModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    selectedContact?: Contact | null;
    selectedContacts?: Contact[];
    onSuccess?: () => void;
    isBulk?: boolean;
    selectAll?: boolean;
    currentFilters?: Record<string, any>;
}

export function ContactSendEmailModal({
    open,
    onOpenChange,
    selectedContact = null,
    selectedContacts = [],
    onSuccess,
    isBulk = false,
    selectAll = false,
    currentFilters = {},
}: ContactSendEmailModalProps) {
    const [isLoading, setIsLoading] = useState(false);

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

        setIsLoading(true);
        const contactIds = targets.map((c) => c.id).filter(Boolean);

        try {
            if (isBulk) {
                if (selectAll) {
                    // Send to all contacts matching current filters
                    router.post(
                        route('contacts.bulk-action'),
                        {
                            type: 'email',
                            select_all: true,
                            filters: currentFilters,
                            data: {
                                content: { subject: data.subject, body: data.body },
                            },
                        },
                        {
                            onSuccess: () => {
                                onSuccess?.();
                                onOpenChange(false);
                            },
                            onFinish: () => setIsLoading(false),
                        },
                    );
                } else {
                    // Send to selected contacts
                    router.post(
                        route('contacts.bulk-action'),
                        {
                            type: 'email',
                            ids: contactIds,
                            data: {
                                content: { subject: data.subject, body: data.body },
                            },
                        },
                        {
                            onSuccess: () => {
                                onSuccess?.();
                                onOpenChange(false);
                            },
                            onFinish: () => setIsLoading(false),
                        },
                    );
                }
            } else {
                // Send to individual contact
                router.post(
                    route('contacts.send-email', selectedContact?.id),
                    {
                        subject: data.subject,
                        body: data.body,
                    },
                    {
                        onSuccess: () => {
                            onSuccess?.();
                            onOpenChange(false);
                        },
                        onFinish: () => setIsLoading(false),
                    },
                );
            }
        } catch (error) {
            console.error('Email send error:', 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">
            {selectAll ? 'All contacts matching current filters' : `${selectedContacts.length} recipient(s)`}
            {!selectAll && selectedContacts.length > 0 && (
                <div className="mt-1 line-clamp-2">
                    {selectedContacts
                        .slice(0, 5)
                        .map((c) => c.email)
                        .join(', ')}
                    {selectedContacts.length > 5 && ' …'}
                </div>
            )}
        </div>
    ) : null;

    const description = isBulk
        ? selectAll
            ? 'Send an email to all contacts matching current filters'
            : `Send an email to ${selectedContacts.length} selected contact${selectedContacts.length === 1 ? '' : 's'}`
        : `Send an email to ${selectedContact?.name} (${selectedContact?.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 to Contact{isBulk && selectedContacts.length > 1 ? 's' : ''}
                    </DialogTitle>
                    <DialogDescription>{description}</DialogDescription>
                </DialogHeader>

                <Form defaultValues={{ subject: '', body: '' }} submitHandler={handleSubmit} formClassNames="space-y-4">
                    {bulkSummary}

                    {!isBulk && selectedContact && (
                        <div className="space-y-2">
                            <Label htmlFor="recipient">To:</Label>
                            <Input id="recipient" value={selectedContact.primary_email} disabled className="bg-gray-50" />
                        </div>
                    )}

                    <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 && !selectedContact) || (isBulk && selectedContacts.length === 0)}>
                            {isLoading ? 'Sending...' : 'Send Email'}
                        </Button>
                    </DialogFooter>
                </Form>
            </DialogContent>
        </Dialog>
    );
}
