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, Star, SquarePen, Trash2, X } from 'lucide-react';

interface TestimonialsIndexProps {
    testimonials: any;
    projects: any[];
}

export default function Index({ testimonials, projects }: TestimonialsIndexProps) {
    const [editingItem, setEditingItem] = useState<any | null>(null);
    const [deleteId, setDeleteId] = useState<number | null>(null);

    const { data, setData, post, put, processing, reset } = useForm({
        customer_name: '',
        designation: '',
        company: '',
        rating: 5,
        testimonial: '',
        featured: true,
        status: 'published',
    });

    const testimonialsList = testimonials.data ? testimonials.data : testimonials;

    const startEdit = (t: any) => {
        setEditingItem(t);
        setData({
            customer_name: t.customer_name,
            designation: t.designation,
            company: t.company || '',
            rating: t.rating || 5,
            testimonial: t.testimonial,
            featured: t.featured ?? true,
            status: t.status || 'published',
        });
    };

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

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

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

    return (
        <AdminLayout title="Testimonials Management">
            <SEOHead title="Testimonials Management | Tech in Soul Admin" description="Manage client reviews, quotes, ratings, and featured testimonials." />

            <div className="space-y-8">
                {/* Form to Add or Edit Testimonial */}
                <form onSubmit={handleSubmit} className="glass-card rounded-2xl p-8 space-y-6">
                    <div className="flex items-center justify-between">
                        <h3 className="text-base 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 Review: ${editingItem.customer_name}` : 'Add Client Review / Testimonial'}
                        </h3>
                        {editingItem && (
                            <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 Editing
                            </button>
                        )}
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Customer Name *</label>
                            <input
                                type="text"
                                value={data.customer_name}
                                onChange={(e) => setData('customer_name', 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]"
                            />
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Designation *</label>
                            <input
                                type="text"
                                value={data.designation}
                                onChange={(e) => setData('designation', 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]"
                            />
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Company Name</label>
                            <input
                                type="text"
                                value={data.company}
                                onChange={(e) => setData('company', 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]"
                            />
                        </div>
                    </div>

                    <div>
                        <label className="text-xs font-bold text-slate-300 uppercase block mb-1">Testimonial Quote *</label>
                        <textarea
                            rows={3}
                            value={data.testimonial}
                            onChange={(e) => setData('testimonial', 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]"
                        />
                    </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 Testimonial' : 'Save Testimonial'}
                        </button>
                    </div>
                </form>

                {/* List */}
                {testimonialsList.length === 0 ? (
                    <div className="glass-card rounded-2xl p-12 text-center text-slate-500 border border-slate-800">
                        <div className="flex flex-col items-center gap-2">
                            <p className="text-sm font-semibold text-slate-400">No client testimonials added yet</p>
                            <p className="text-xs text-slate-500">Use the form above to add your first client review.</p>
                        </div>
                    </div>
                ) : (
                    <div className="space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {testimonialsList.map((t: any) => (
                                <div key={t.id} className="glass-card rounded-2xl p-6 relative flex flex-col justify-between border border-slate-800">
                                    <div>
                                        <div className="flex items-center justify-between mb-3">
                                            <div className="flex items-center gap-1 text-amber-400">
                                                {[...Array(t.rating)].map((_, i) => (
                                                    <Star key={i} className="w-3.5 h-3.5 fill-amber-400" />
                                                ))}
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <button
                                                    onClick={() => startEdit(t)}
                                                    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 Testimonial"
                                                >
                                                    <SquarePen className="w-4 h-4" />
                                                </button>
                                                <button
                                                    onClick={() => setDeleteId(t.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 Testimonial"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </div>
                                        </div>
                                        <p className="text-xs text-slate-300 italic mb-4">"{t.testimonial}"</p>
                                    </div>
                                    <div className="pt-3 border-t border-slate-800 flex items-center justify-between">
                                        <div>
                                            <h4 className="text-xs font-bold text-white">{t.customer_name}</h4>
                                            <p className="text-[11px] text-[#00F2FE]">{t.designation} • {t.company}</p>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>

                        {testimonials.links && (
                            <div className="glass-card rounded-2xl overflow-hidden border border-slate-800">
                                <Pagination links={testimonials.links} from={testimonials.from} to={testimonials.to} total={testimonials.total} />
                            </div>
                        )}
                    </div>
                )}
            </div>

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