import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { SettingsCard } from '@/routes/Settings/components/SettingsCard';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Download, Trash2, Search } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { useNavigate } from 'react-router-dom';
import { __ } from '@/lib/i18n';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';

export default function Subscribers() {
    const [searchQuery, setSearchQuery] = useState('');
    const queryClient = useQueryClient();
    const navigate = useNavigate();

    const { data: subscribersData, isLoading } = useQuery({
        queryKey: ['newsletter-subscribers'],
        queryFn: async () => {
            const response = await api.get('/newsletter/subscribers');
            return response.data;
        },
    });

    const deleteSubscriber = useMutation({
        mutationFn: async (email: string) => {
            await api.del(`/newsletter/subscribers/${encodeURIComponent(email)}`);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['newsletter-subscribers'] });
            toast.success(__('Subscriber removed successfully'));
        },
        onError: () => {
            toast.error(__('Failed to remove subscriber'));
        },
    });

    const exportSubscribers = () => {
        if (!subscribersData?.subscribers) return;

        const csv = ['Email,Subscribed Date'].concat(
            subscribersData.subscribers.map((sub: any) =>
                `${sub.email},${sub.subscribed_at || 'N/A'}`
            )
        ).join('\n');

        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `newsletter-subscribers-${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
        window.URL.revokeObjectURL(url);
    };

    const subscribers = subscribersData?.subscribers || [];
    const filteredSubscribers = subscribers.filter((sub: any) =>
        sub.email.toLowerCase().includes(searchQuery.toLowerCase())
    );

    return (
        <div className="space-y-6">
            <SettingsCard
                title={__('Subscribers List')}
                description={`${__('Total subscribers')}: ${subscribersData?.count || 0}`}
            >
                <div className="space-y-4">
                    {/* 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={__('Filter subscribers...')}
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="!pl-9"
                            />
                        </div>
                        <Button onClick={exportSubscribers} variant="outline" size="sm">
                            <Download className="mr-2 h-4 w-4" />
                            {__('Export CSV')}
                        </Button>
                    </div>

                    {/* Subscribers Table */}
                    {isLoading ? (
                        <div className="text-center py-8 text-muted-foreground">
                            {__('Loading subscribers...')}
                        </div>
                    ) : filteredSubscribers.length === 0 ? (
                        <div className="text-center py-8 text-muted-foreground">
                            {searchQuery ? __('No subscribers found matching your search') : __('No subscribers yet')}
                        </div>
                    ) : (
                        <div className="border rounded-lg">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>{__('Email')}</TableHead>
                                        <TableHead>{__('Status')}</TableHead>
                                        <TableHead>{__('Subscribed Date')}</TableHead>
                                        <TableHead>{__('WP User')}</TableHead>
                                        <TableHead className="text-right">{__('Actions')}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {filteredSubscribers.map((subscriber: any) => (
                                        <TableRow key={subscriber.email}>
                                            <TableCell className="font-medium">{subscriber.email}</TableCell>
                                            <TableCell>
                                                <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300">
                                                    {subscriber.status || __('Active')}
                                                </span>
                                            </TableCell>
                                            <TableCell className="text-muted-foreground">
                                                {subscriber.subscribed_at
                                                    ? new Date(subscriber.subscribed_at).toLocaleDateString()
                                                    : 'N/A'
                                                }
                                            </TableCell>
                                            <TableCell>
                                                {subscriber.user_id ? (
                                                    <span className="text-xs text-blue-600">{__('Yes')} (ID: {subscriber.user_id})</span>
                                                ) : (
                                                    <span className="text-xs text-muted-foreground">{__('No')}</span>
                                                )}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => deleteSubscriber.mutate(subscriber.email)}
                                                    disabled={deleteSubscriber.isPending}
                                                >
                                                    <Trash2 className="h-4 w-4 text-red-500" />
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </div>
                    )}
                </div>
            </SettingsCard>

            {/* Email Template Settings */}
            <SettingsCard
                title={__('Email Templates')}
                description={__('Customize newsletter email templates using the email builder')}
            >
                <div className="space-y-4">
                    <div className="p-4 border rounded-lg bg-muted/50">
                        <h4 className="font-medium mb-2">{__('Newsletter Welcome Email')}</h4>
                        <p className="text-sm text-muted-foreground mb-4">
                            {__('Welcome email sent when someone subscribes to your newsletter')}
                        </p>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => navigate('/settings/notifications/edit-template?event=newsletter_welcome&channel=email&recipient=customer')}
                        >
                            {__('Edit Template')}
                        </Button>
                    </div>

                    <div className="p-4 border rounded-lg bg-muted/50">
                        <h4 className="font-medium mb-2">{__('New Subscriber Notification (Admin)')}</h4>
                        <p className="text-sm text-muted-foreground mb-4">
                            {__('Admin notification when someone subscribes to newsletter')}
                        </p>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => navigate('/settings/notifications/edit-template?event=newsletter_subscribed_admin&channel=email&recipient=staff')}
                        >
                            {__('Edit Template')}
                        </Button>
                    </div>
                </div>
            </SettingsCard>
        </div>
    );
}
