import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Plus,
    Search,
    Send,
    Clock,
    CheckCircle2,
    AlertCircle,
    Trash2,
    Edit,
    MoreHorizontal,
    Copy
} from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface Campaign {
    id: number;
    title: string;
    subject: string;
    status: 'draft' | 'scheduled' | 'sending' | 'sent' | 'failed';
    recipient_count: number;
    sent_count: number;
    failed_count: number;
    scheduled_at: string | null;
    sent_at: string | null;
    created_at: string;
}

const statusConfig = {
    draft: { label: 'Draft', icon: Edit, className: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300' },
    scheduled: { label: 'Scheduled', icon: Clock, className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300' },
    sending: { label: 'Sending', icon: Send, className: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300' },
    sent: { label: 'Sent', icon: CheckCircle2, className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300' },
    failed: { label: 'Failed', icon: AlertCircle, className: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300' },
};

export default function Campaigns() {
    const [searchQuery, setSearchQuery] = useState('');
    const [deleteId, setDeleteId] = useState<number | null>(null);
    const navigate = useNavigate();
    const queryClient = useQueryClient();

    const { data, isLoading } = useQuery({
        queryKey: ['campaigns'],
        queryFn: async () => {
            const response: any = await api.get('/newsletter/campaigns');
            return Array.isArray(response) ? (response as Campaign[]) : ((response?.data || []) as Campaign[]);
        },
    });

    const deleteMutation = useMutation({
        mutationFn: async (id: number) => {
            await api.del(`/campaigns/${id}`);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['campaigns'] });
            toast.success(__('Campaign deleted'));
            setDeleteId(null);
        },
        onError: () => {
            toast.error(__('Failed to delete campaign'));
        },
    });

    const duplicateMutation = useMutation({
        mutationFn: async (campaign: Campaign) => {
            const response = await api.post('/campaigns', {
                title: `${campaign.title} (Copy)`,
                subject: campaign.subject,
                content: '',
                status: 'draft',
            });
            return response;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['campaigns'] });
            toast.success(__('Campaign duplicated'));
        },
        onError: () => {
            toast.error(__('Failed to duplicate campaign'));
        },
    });

    const campaigns = data || [];
    const filteredCampaigns = campaigns.filter((c) =>
        c.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        c.subject?.toLowerCase().includes(searchQuery.toLowerCase())
    );

    const formatDate = (dateStr: string | null) => {
        if (!dateStr) return '-';
        return new Date(dateStr).toLocaleDateString(undefined, {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    return (
        <div className="space-y-6">
            {/* Actions Bar */}
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div className="relative flex-1 max-w-sm">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
                    <Input
                        placeholder={__('Search campaigns...')}
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="!pl-9"
                    />
                </div>
                <Button onClick={() => navigate('/marketing/newsletter/campaigns/new')}>
                    <Plus className="mr-2 h-4 w-4" />
                    {__('New Campaign')}
                </Button>
            </div>

            {/* Campaigns Table */}
            {isLoading ? (
                <div className="text-center py-8 text-muted-foreground">
                    {__('Loading campaigns...')}
                </div>
            ) : filteredCampaigns.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                    {searchQuery ? __('No campaigns found matching your search') : (
                        <div className="space-y-4">
                            <Send className="h-12 w-12 mx-auto opacity-50" />
                            <p>{__('No campaigns yet')}</p>
                            <Button onClick={() => navigate('/marketing/newsletter/campaigns/new')}>
                                <Plus className="mr-2 h-4 w-4" />
                                {__('Create your first campaign')}
                            </Button>
                        </div>
                    )}
                </div>
            ) : (
                <div className="border rounded-lg">
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>{__('Title')}</TableHead>
                                <TableHead>{__('Status')}</TableHead>
                                <TableHead className="hidden md:table-cell">{__('Recipients')}</TableHead>
                                <TableHead className="hidden md:table-cell">{__('Date')}</TableHead>
                                <TableHead className="text-right">{__('Actions')}</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {filteredCampaigns.map((campaign) => {
                                const status = statusConfig[campaign.status] || statusConfig.draft;
                                const StatusIcon = status.icon;

                                return (
                                    <TableRow key={campaign.id}>
                                        <TableCell>
                                            <div>
                                                <div className="font-medium">{campaign.title}</div>
                                                {campaign.subject && (
                                                    <div className="text-sm text-muted-foreground truncate max-w-[200px]">
                                                        {campaign.subject}
                                                    </div>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${status.className}`}>
                                                <StatusIcon className="h-3 w-3" />
                                                {__(status.label)}
                                            </span>
                                        </TableCell>
                                        <TableCell className="hidden md:table-cell">
                                            {campaign.status === 'sent' ? (
                                                <span>
                                                    {campaign.sent_count}/{campaign.recipient_count}
                                                    {campaign.failed_count > 0 && (
                                                        <span className="text-red-500 ml-1">
                                                            ({campaign.failed_count} {__('failed')})
                                                        </span>
                                                    )}
                                                </span>
                                            ) : (
                                                '-'
                                            )}
                                        </TableCell>
                                        <TableCell className="hidden md:table-cell text-muted-foreground">
                                            {campaign.sent_at
                                                ? formatDate(campaign.sent_at)
                                                : campaign.scheduled_at
                                                    ? `${__('Scheduled')}: ${formatDate(campaign.scheduled_at)}`
                                                    : formatDate(campaign.created_at)
                                            }
                                        </TableCell>
                                        <TableCell className="text-right">
                                            <DropdownMenu>
                                                <DropdownMenuTrigger asChild>
                                                    <Button variant="ghost" size="sm">
                                                        <MoreHorizontal className="h-4 w-4" />
                                                    </Button>
                                                </DropdownMenuTrigger>
                                                <DropdownMenuContent align="end">
                                                    <DropdownMenuItem onClick={() => navigate(`/marketing/newsletter/campaigns/${campaign.id}`)}>
                                                        <Edit className="mr-2 h-4 w-4" />
                                                        {__('Edit')}
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem onClick={() => duplicateMutation.mutate(campaign)}>
                                                        <Copy className="mr-2 h-4 w-4" />
                                                        {__('Duplicate')}
                                                    </DropdownMenuItem>
                                                    <DropdownMenuItem
                                                        onClick={() => setDeleteId(campaign.id)}
                                                        className="text-red-600"
                                                    >
                                                        <Trash2 className="mr-2 h-4 w-4" />
                                                        {__('Delete')}
                                                    </DropdownMenuItem>
                                                </DropdownMenuContent>
                                            </DropdownMenu>
                                        </TableCell>
                                    </TableRow>
                                );
                            })}
                        </TableBody>
                    </Table>
                </div>
            )}

            {/* Delete Confirmation Dialog */}
            <AlertDialog open={deleteId !== null} onOpenChange={() => setDeleteId(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Delete Campaign')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('Are you sure you want to delete this campaign? This action cannot be undone.')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>{__('Cancel')}</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={() => deleteId && deleteMutation.mutate(deleteId)}
                            className="bg-red-600 hover:bg-red-700"
                        >
                            {__('Delete')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
