import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import { SettingsCard } from '@/routes/Settings/components/SettingsCard';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import {
    ArrowLeft,
    Send,
    Eye,
    TestTube,
    Save,
    Loader2,
} from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface Campaign {
    id: number;
    title: string;
    subject: string;
    content: string;
    status: string;
    scheduled_at: string | null;
}

export default function CampaignEdit() {
    const { id } = useParams<{ id: string }>();
    const isNew = id === 'new';
    const navigate = useNavigate();
    const queryClient = useQueryClient();

    const [title, setTitle] = useState('');
    const [subject, setSubject] = useState('');
    const [content, setContent] = useState('');
    const [showPreview, setShowPreview] = useState(false);
    const [previewHtml, setPreviewHtml] = useState('');
    const [showTestDialog, setShowTestDialog] = useState(false);
    const [testEmail, setTestEmail] = useState('');
    const [showSendConfirm, setShowSendConfirm] = useState(false);
    const [isSaving, setIsSaving] = useState(false);

    // Fetch campaign if editing
    const { data: campaign, isLoading } = useQuery({
        queryKey: ['campaign', id],
        queryFn: async () => {
            const response = await api.get(`/campaigns/${id}`);
            return response.data as Campaign;
        },
        enabled: !isNew && !!id,
    });

    // Populate form when campaign loads
    useEffect(() => {
        if (campaign) {
            setTitle(campaign.title || '');
            setSubject(campaign.subject || '');
            setContent(campaign.content || '');
        }
    }, [campaign]);

    // Save mutation
    const saveMutation = useMutation({
        mutationFn: async (data: { title: string; subject: string; content: string; status?: string }) => {
            if (isNew) {
                return api.post('/campaigns', data);
            } else {
                return api.put(`/campaigns/${id}`, data);
            }
        },
        onSuccess: (response) => {
            queryClient.invalidateQueries({ queryKey: ['campaigns'] });
            toast.success(isNew ? __('Campaign created') : __('Campaign saved'));
            if (isNew && response?.data?.id) {
                navigate(`/marketing/campaigns/${response.data.id}`, { replace: true });
            }
        },
        onError: () => {
            toast.error(__('Failed to save campaign'));
        },
    });

    // Preview mutation
    const previewMutation = useMutation({
        mutationFn: async () => {
            // First save, then preview
            let campaignId = id;
            if (isNew || !id) {
                const saveResponse = await api.post('/campaigns', { title, subject, content, status: 'draft' });
                campaignId = saveResponse?.data?.id;
                if (campaignId) {
                    navigate(`/marketing/campaigns/${campaignId}`, { replace: true });
                }
            } else {
                await api.put(`/campaigns/${id}`, { title, subject, content });
            }

            const response = await api.get(`/campaigns/${campaignId}/preview`);
            return response;
        },
        onSuccess: (response) => {
            setPreviewHtml(response?.html || response?.data?.html || '');
            setShowPreview(true);
        },
        onError: () => {
            toast.error(__('Failed to generate preview'));
        },
    });

    // Test email mutation
    const testMutation = useMutation({
        mutationFn: async (email: string) => {
            // First save
            if (!isNew && id) {
                await api.put(`/campaigns/${id}`, { title, subject, content });
            }
            return api.post(`/campaigns/${id}/test`, { email });
        },
        onSuccess: () => {
            toast.success(__('Test email sent'));
            setShowTestDialog(false);
        },
        onError: () => {
            toast.error(__('Failed to send test email'));
        },
    });

    // Send mutation
    const sendMutation = useMutation({
        mutationFn: async () => {
            // First save
            await api.put(`/campaigns/${id}`, { title, subject, content });
            return api.post(`/campaigns/${id}/send`);
        },
        onSuccess: (response) => {
            queryClient.invalidateQueries({ queryKey: ['campaigns'] });
            queryClient.invalidateQueries({ queryKey: ['campaign', id] });
            toast.success(response?.message || __('Campaign sent successfully'));
            setShowSendConfirm(false);
            navigate('/marketing/campaigns');
        },
        onError: (error: any) => {
            toast.error(error?.response?.data?.error || __('Failed to send campaign'));
        },
    });

    const handleSave = async () => {
        if (!title.trim()) {
            toast.error(__('Please enter a title'));
            return;
        }
        setIsSaving(true);
        try {
            await saveMutation.mutateAsync({ title, subject, content, status: 'draft' });
        } finally {
            setIsSaving(false);
        }
    };

    const canSend = !isNew && id && campaign?.status !== 'sent' && campaign?.status !== 'sending';

    if (!isNew && isLoading) {
        return (
            <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
        );
    }

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-lg font-medium">
                        {isNew ? __('New Campaign') : __('Edit Campaign')}
                    </h2>
                    <p className="text-sm text-muted-foreground">
                        {isNew ? __('Create a new email campaign') : campaign?.title || ''}
                    </p>
                </div>
                <Button variant="ghost" onClick={() => navigate('/marketing/newsletter/campaigns')}>
                    <ArrowLeft className="mr-2 h-4 w-4" />
                    {__('Back to Campaigns')}
                </Button>
            </div>

            <div className="space-y-6">
                {/* Campaign Details */}
                <SettingsCard
                    title={__('Campaign Details')}
                    description={__('Basic information about your campaign')}
                >
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="title">{__('Campaign Title')}</Label>
                            <Input
                                id="title"
                                placeholder={__('e.g., Holiday Sale Announcement')}
                                value={title}
                                onChange={(e) => setTitle(e.target.value)}
                            />
                            <p className="text-xs text-muted-foreground">
                                {__('Internal name for this campaign (not shown to subscribers)')}
                            </p>
                        </div>

                        <div className="space-y-2">
                            <Label htmlFor="subject">{__('Email Subject')}</Label>
                            <Input
                                id="subject"
                                placeholder={__('e.g., 🎄 Exclusive Holiday Deals Inside!')}
                                value={subject}
                                onChange={(e) => setSubject(e.target.value)}
                            />
                            <p className="text-xs text-muted-foreground">
                                {__('The subject line subscribers will see in their inbox')}
                            </p>
                        </div>
                    </div>
                </SettingsCard>

                {/* Campaign Content */}
                <SettingsCard
                    title={__('Campaign Content')}
                    description={__('Write your newsletter content. The design template is configured in Settings > Notifications.')}
                >
                    <div className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="content">{__('Email Content')}</Label>
                            <RichTextEditor
                                content={content}
                                onChange={setContent}
                                placeholder={__('Write your newsletter content here...')}
                                variables={['site_name', 'current_date', 'subscriber_email', 'current_year', 'store_name', 'unsubscribe_url']}
                            />
                            <p className="text-xs text-muted-foreground">
                                {__('Use the toolbar to format text. The design wrapper will be applied from your campaign email template.')}
                            </p>
                        </div>
                    </div>
                </SettingsCard>

                {/* Actions */}
                <div className="flex flex-col sm:flex-row gap-3 sm:justify-between">
                    <div className="flex gap-3">
                        <Button
                            variant="outline"
                            onClick={() => previewMutation.mutate()}
                            disabled={previewMutation.isPending || !title.trim()}
                        >
                            {previewMutation.isPending ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Eye className="mr-2 h-4 w-4" />
                            )}
                            {__('Preview')}
                        </Button>

                        {!isNew && (
                            <Button
                                variant="outline"
                                onClick={() => setShowTestDialog(true)}
                                disabled={!id}
                            >
                                <TestTube className="mr-2 h-4 w-4" />
                                {__('Send Test')}
                            </Button>
                        )}
                    </div>

                    <div className="flex gap-3">
                        <Button
                            variant="outline"
                            onClick={handleSave}
                            disabled={isSaving || !title.trim()}
                        >
                            {isSaving ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Save className="mr-2 h-4 w-4" />
                            )}
                            {__('Save Draft')}
                        </Button>

                        {canSend && (
                            <Button
                                onClick={() => setShowSendConfirm(true)}
                                disabled={sendMutation.isPending}
                            >
                                {sendMutation.isPending ? (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                ) : (
                                    <Send className="mr-2 h-4 w-4" />
                                )}
                                {__('Send Now')}
                            </Button>
                        )}
                    </div>
                </div>
            </div>

            {/* Preview Dialog */}
            <Dialog open={showPreview} onOpenChange={setShowPreview}>
                <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                        <DialogTitle>{__('Email Preview')}</DialogTitle>
                        <DialogDescription>{__('Preview how your email will look to subscribers')}</DialogDescription>
                    </DialogHeader>
                    <div className="border rounded-lg overflow-hidden bg-gray-100 mx-6 mb-6">
                        <iframe
                            srcDoc={previewHtml}
                            className="w-full min-h-[600px] bg-white"
                            title={__('Email Preview')}
                        />
                    </div>
                </DialogContent>
            </Dialog>

            {/* Test Email Dialog */}
            <Dialog open={showTestDialog} onOpenChange={setShowTestDialog}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>{__('Send Test Email')}</DialogTitle>
                        <DialogDescription>{__('Send a test email to verify your campaign before sending to all subscribers')}</DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4 px-6 py-4">
                        <div className="space-y-2">
                            <Label htmlFor="test-email">{__('Email Address')}</Label>
                            <Input
                                id="test-email"
                                type="email"
                                placeholder="your@email.com"
                                value={testEmail}
                                onChange={(e) => setTestEmail(e.target.value)}
                            />
                        </div>
                        <div className="flex justify-end gap-3">
                            <Button variant="outline" onClick={() => setShowTestDialog(false)}>
                                {__('Cancel')}
                            </Button>
                            <Button
                                onClick={() => testMutation.mutate(testEmail)}
                                disabled={!testEmail || testMutation.isPending}
                            >
                                {testMutation.isPending ? (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                ) : (
                                    <Send className="mr-2 h-4 w-4" />
                                )}
                                {__('Send Test')}
                            </Button>
                        </div>
                    </div>
                </DialogContent>
            </Dialog>

            {/* Send Confirmation Dialog */}
            <AlertDialog open={showSendConfirm} onOpenChange={setShowSendConfirm}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Send Campaign')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('Are you sure you want to send this campaign to all newsletter subscribers? This action cannot be undone.')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>{__('Cancel')}</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={() => sendMutation.mutate()}
                            disabled={sendMutation.isPending}
                        >
                            {sendMutation.isPending ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            ) : (
                                <Send className="mr-2 h-4 w-4" />
                            )}
                            {__('Send to All Subscribers')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
