import React, { useState } from 'react';
import { router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import { Pagination } from '@/Components/Pagination';
import { ConfirmDeleteModal } from '@/Components/ConfirmDeleteModal';
import { formatCustomDate } from '@/lib/utils';
import { Download, Trash2, Search, X } from 'lucide-react';

interface NewsletterIndexProps {
    subscribers: any;
    filters?: {
        search?: string;
        status?: string;
    };
}

export default function Index({ subscribers, filters = {} }: NewsletterIndexProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [statusFilter, setStatusFilter] = useState(filters.status || 'all');
    const [deleteId, setDeleteId] = useState<number | null>(null);

    const handleSearch = (e?: React.FormEvent) => {
        if (e) e.preventDefault();
        router.get('/admin/newsletter', {
            search: search || undefined,
            status: statusFilter !== 'all' ? statusFilter : undefined,
        }, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    const handleClearFilters = () => {
        setSearch('');
        setStatusFilter('all');
        router.get('/admin/newsletter');
    };

    const handleDelete = () => {
        if (deleteId) {
            router.delete(`/admin/newsletter/${deleteId}`);
        }
    };

    const subscribersList = subscribers.data ? subscribers.data : subscribers;

    return (
        <AdminLayout title="Newsletter Subscribers">
            <SEOHead title="Newsletter Subscribers | Tech in Soul Admin" description="View newsletter subscribers and export email contacts as CSV." />

            <div className="space-y-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h2 className="text-xl font-bold text-white">Newsletter List</h2>
                        <p className="text-xs text-slate-400">View active email subscribers and export contacts as CSV.</p>
                    </div>
                    <a href="/admin/newsletter/export" className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5 self-start sm:self-auto">
                        <Download className="w-4 h-4" /> Export CSV
                    </a>
                </div>

                {/* Search & Filter Bar */}
                <div className="glass-card rounded-2xl p-4 border border-slate-800">
                    <form onSubmit={handleSearch} className="flex flex-col sm:flex-row items-center gap-3">
                        <div className="relative flex-grow w-full">
                            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                            <input
                                type="text"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Search subscribers by email address..."
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl pl-10 pr-4 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-[#00F2FE]"
                            />
                        </div>

                        <div className="flex items-center gap-2 w-full sm:w-auto">
                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="bg-[#060B18] border border-slate-800 rounded-xl px-3 py-2 text-xs text-slate-300 focus:outline-none focus:border-[#00F2FE]"
                            >
                                <option value="all">All Statuses</option>
                                <option value="subscribed">Subscribed</option>
                                <option value="unsubscribed">Unsubscribed</option>
                            </select>

                            <button type="submit" className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold shrink-0">
                                Filter
                            </button>

                            {(search || statusFilter !== 'all') && (
                                <button
                                    type="button"
                                    onClick={handleClearFilters}
                                    className="p-2 rounded-xl bg-slate-800/60 hover:bg-slate-800 text-slate-400 hover:text-white text-xs font-semibold shrink-0 transition-colors"
                                    title="Clear filters"
                                >
                                    <X className="w-4 h-4" />
                                </button>
                            )}
                        </div>
                    </form>
                </div>

                <div className="glass-card rounded-2xl overflow-hidden border border-slate-800">

                    <table className="w-full text-left text-sm text-slate-300">
                        <thead className="bg-[#060B18] text-xs font-bold text-slate-400 uppercase border-b border-slate-800">
                            <tr>
                                <th className="px-6 py-4">Subscriber Email</th>
                                <th className="px-6 py-4">Status</th>
                                <th className="px-6 py-4">Subscribed Date</th>
                                <th className="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/80">
                            {subscribersList.length === 0 ? (
                                <tr>
                                    <td colSpan={4} className="px-6 py-12 text-center text-slate-500">
                                        <div className="flex flex-col items-center gap-2">
                                            <p className="text-sm font-semibold text-slate-400">No newsletter subscribers yet</p>
                                            <p className="text-xs text-slate-500">Subscribers signing up via the website footer form will appear here.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                subscribersList.map((sub: any) => (
                                    <tr key={sub.id} className="hover:bg-[#060B18]/40 transition-colors">
                                        <td className="px-6 py-4 font-bold text-white font-mono text-xs">{sub.email}</td>
                                        <td className="px-6 py-4">
                                            <span className="text-[10px] font-semibold px-2.5 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 capitalize">
                                                {sub.status}
                                            </span>
                                        </td>
                                        <td className="px-6 py-4 text-xs font-mono text-slate-400">
                                            {formatCustomDate(sub.subscribed_at || sub.created_at)}
                                        </td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end">
                                                <button
                                                    onClick={() => setDeleteId(sub.id)}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-rose-400 hover:text-rose-300 hover:bg-rose-500/10 transition-colors"
                                                    title="Remove Subscriber"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>

                    {subscribers.links && (
                        <Pagination links={subscribers.links} from={subscribers.from} to={subscribers.to} total={subscribers.total} />
                    )}
                </div>
            </div>

            <ConfirmDeleteModal
                isOpen={deleteId !== null}
                title="Remove Newsletter Subscriber?"
                message="Are you sure you want to remove this subscriber from the mailing list?"
                onConfirm={handleDelete}
                onClose={() => setDeleteId(null)}
            />
        </AdminLayout>
    );
}
