import React, { useState } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { SEOHead } from '@/Components/SEOHead';
import { Pagination } from '@/Components/Pagination';
import { ConfirmDeleteModal } from '@/Components/ConfirmDeleteModal';
import { Plus, SquarePen, Trash2, X, Search, ChevronDown, ChevronUp } from 'lucide-react';

interface FaqsIndexProps {
    faqs: any;
    categories: any[];
    filters?: {
        search?: string;
        category?: string;
    };
}

export default function Index({ faqs, categories, filters = {} }: FaqsIndexProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [categoryFilter, setCategoryFilter] = useState(filters.category || 'all');
    const [editingItem, setEditingItem] = useState<any | null>(null);
    const [formOpen, setFormOpen] = useState(false);
    const [deleteId, setDeleteId] = useState<number | null>(null);

    const { data, setData, post, put, processing, reset } = useForm({
        category_id: categories[0]?.id || '',
        question: '',
        answer: '',
        status: 'published',
        featured: true,
    });

    const faqsList = faqs.data ? faqs.data : faqs;

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

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

    const startEdit = (faq: any) => {
        setEditingItem(faq);
        setFormOpen(true);
        setData({
            category_id: faq.category_id || (categories[0]?.id || ''),
            question: faq.question,
            answer: faq.answer,
            status: faq.status || 'published',
            featured: faq.featured ?? true,
        });
    };

    const cancelEdit = () => {
        setEditingItem(null);
        setFormOpen(false);
        reset();
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (editingItem) {
            put(`/admin/faqs/${editingItem.id}`, {
                preserveScroll: true,
                onSuccess: () => cancelEdit(),
            });
        } else {
            post('/admin/faqs', {
                preserveScroll: true,
                onSuccess: () => {
                    reset();
                    setFormOpen(false);
                },
            });
        }
    };

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

    return (
        <AdminLayout title="FAQs & Help Center Management">
            <SEOHead title="FAQs & Help Center | Tech in Soul Admin" description="Manage frequently asked questions, answers, and categories." />

            <div className="w-full 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">Frequently Asked Questions</h2>
                        <p className="text-xs text-slate-400">Manage client FAQs, help center queries, and technical answers.</p>
                    </div>
                    <button
                        type="button"
                        onClick={() => {
                            if (formOpen && !editingItem) {
                                setFormOpen(false);
                            } else {
                                setEditingItem(null);
                                reset();
                                setFormOpen(true);
                            }
                        }}
                        className="btn-aqua px-4 py-2 rounded-xl text-xs font-bold flex items-center gap-1.5 self-start sm:self-auto"
                    >
                        <Plus className="w-4 h-4" /> {formOpen && !editingItem ? 'Close Form' : 'Add FAQ Question'}
                    </button>
                </div>

                {/* Form to Add or Edit FAQ */}
                {formOpen && (
                    <form onSubmit={handleSubmit} className="glass-card rounded-2xl p-6 sm:p-8 space-y-6 border border-slate-800 animate-in fade-in">
                        <div className="flex items-center justify-between pb-3 border-b border-slate-800">
                            <h3 className="text-sm font-bold text-white flex items-center gap-2">
                                {editingItem ? <SquarePen className="w-4 h-4 text-[#00F2FE]" /> : <Plus className="w-4 h-4 text-[#00F2FE]" />}
                                {editingItem ? 'Edit FAQ Item' : 'New FAQ Question & Answer'}
                            </h3>
                            <button type="button" onClick={cancelEdit} className="text-xs text-rose-400 hover:underline flex items-center gap-1">
                                <X className="w-3.5 h-3.5" /> Cancel
                            </button>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Category</label>
                                <select
                                    value={data.category_id}
                                    onChange={(e) => setData('category_id', e.target.value)}
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                >
                                    {categories.map((c) => (
                                        <option key={c.id} value={c.id}>{c.name}</option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Question *</label>
                                <input
                                    type="text"
                                    value={data.question}
                                    onChange={(e) => setData('question', e.target.value)}
                                    required
                                    className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                    placeholder="e.g. How does Tech in Soul scale cloud infrastructure?"
                                />
                            </div>
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Answer *</label>
                            <textarea
                                rows={3}
                                value={data.answer}
                                onChange={(e) => setData('answer', e.target.value)}
                                required
                                className="w-full bg-[#060B18] border border-slate-800 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#00F2FE]"
                                placeholder="Write the complete answer..."
                            />
                        </div>

                        <div className="flex items-center gap-3">
                            <button
                                type="submit"
                                disabled={processing}
                                className="btn-aqua px-5 py-2.5 rounded-xl font-bold text-xs flex items-center gap-1.5"
                            >
                                {editingItem ? <SquarePen className="w-4 h-4" /> : <Plus className="w-4 h-4" />}
                                {editingItem ? 'Update FAQ Item' : 'Save FAQ Item'}
                            </button>
                            <button
                                type="button"
                                onClick={cancelEdit}
                                className="px-4 py-2.5 rounded-xl text-xs font-bold bg-slate-800/80 hover:bg-slate-800 text-slate-300"
                            >
                                Cancel
                            </button>
                        </div>
                    </form>
                )}

                {/* 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 questions or answers..."
                                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={categoryFilter}
                                onChange={(e) => setCategoryFilter(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 Categories</option>
                                {categories.map((c: any) => (
                                    <option key={c.id} value={c.id}>{c.name}</option>
                                ))}
                            </select>

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

                            {(search || categoryFilter !== '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">Question</th>
                                <th className="px-6 py-4">Category</th>
                                <th className="px-6 py-4 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-800/80">
                            {faqsList.length === 0 ? (
                                <tr>
                                    <td colSpan={3} 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 FAQ items found</p>
                                            <p className="text-xs text-slate-500">Use the form above to add your first FAQ question and answer.</p>
                                        </div>
                                    </td>
                                </tr>
                            ) : (
                                faqsList.map((faq: any) => (
                                    <tr key={faq.id} className="hover:bg-[#060B18]/40 transition-colors">
                                        <td className="px-6 py-4 font-bold text-white max-w-md">{faq.question}</td>
                                        <td className="px-6 py-4 text-xs text-slate-400">{faq.category?.name || 'General'}</td>
                                        <td className="px-6 py-4 text-right">
                                            <div className="flex items-center justify-end gap-2">
                                                <button
                                                    onClick={() => startEdit(faq)}
                                                    className="inline-flex items-center justify-center p-1.5 rounded-lg text-slate-400 hover:text-[#00F2FE] hover:bg-[#00F2FE]/10 transition-colors"
                                                    title="Edit FAQ"
                                                >
                                                    <SquarePen className="w-4 h-4" />
                                                </button>
                                                <button
                                                    onClick={() => setDeleteId(faq.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="Delete FAQ"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>

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

            <ConfirmDeleteModal
                isOpen={deleteId !== null}
                title="Delete FAQ Question?"
                message="Are you sure you want to delete this FAQ entry? It will be removed from your Help Center."
                onConfirm={handleDelete}
                onClose={() => setDeleteId(null)}
            />
        </AdminLayout>
    );
}
