import React, { useState } from 'react';
import { useForm, router } from '@inertiajs/react';
import { AdminLayout } from '../AdminLayout';
import { Plus, Trash2, Edit3, MoveUp, MoveDown, Layers, CheckCircle2 } from 'lucide-react';

interface BuilderProps {
    page: any;
}

export default function Builder({ page }: BuilderProps) {
    const [selectedType, setSelectedType] = useState('hero');

    const { data, setData, post, processing, reset } = useForm({
        type: 'hero',
        title: '',
        content: {},
        enabled: true,
        sort_order: (page.sections?.length || 0) + 1,
    });

    const handleAddSection = (e: React.FormEvent) => {
        e.preventDefault();
        post(`/admin/pages/${page.id}/sections`, {
            preserveScroll: true,
            onSuccess: () => reset(),
        });
    };

    const handleDeleteSection = (sectionId: number) => {
        if (confirm('Delete this section?')) {
            router.delete(`/admin/sections/${sectionId}`, { preserveScroll: true });
        }
    };

    return (
        <AdminLayout title={`Page Builder: ${page.title}`}>
            <div className="space-y-8">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-xl font-bold text-white">Visual Section Manager</h2>
                        <p className="text-xs text-slate-400">Configure dynamic blocks rendered on /{page.slug}</p>
                    </div>
                </div>

                {/* Existing Sections List */}
                <div className="space-y-4">
                    <h3 className="text-sm font-bold text-slate-300 uppercase tracking-wider">Active Page Sections</h3>
                    {page.sections && page.sections.length > 0 ? (
                        page.sections.map((section: any, idx: number) => (
                            <div key={section.id} className="glass-card rounded-2xl p-6 flex items-center justify-between border border-slate-800">
                                <div className="flex items-center gap-4">
                                    <div className="w-8 h-8 rounded-lg bg-[#00F2FE]/10 text-[#00F2FE] border border-[#00F2FE]/20 flex items-center justify-center font-bold text-xs">
                                        #{idx + 1}
                                    </div>
                                    <div>
                                        <h4 className="text-base font-bold text-white capitalize">{section.title || section.type}</h4>
                                        <span className="text-xs text-slate-400 font-mono">Type: {section.type}</span>
                                    </div>
                                </div>
                                <button
                                    onClick={() => handleDeleteSection(section.id)}
                                    className="p-2 text-rose-400 hover:bg-rose-500/10 rounded-lg transition-colors"
                                >
                                    <Trash2 className="w-4 h-4" />
                                </button>
                            </div>
                        ))
                    ) : (
                        <div className="glass-card rounded-2xl p-8 text-center text-slate-500">
                            No active sections added to this page yet. Use the block creator below.
                        </div>
                    )}
                </div>

                {/* Section Creator */}
                <form onSubmit={handleAddSection} className="glass-card rounded-2xl p-8 space-y-6">
                    <h3 className="text-base font-bold text-white flex items-center gap-2">
                        <Plus className="w-4 h-4 text-[#00F2FE]" /> Add Section Block
                    </h3>

                    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                            <label className="text-xs font-bold text-slate-400 block mb-2">Section Type</label>
                            <select
                                value={data.type}
                                onChange={(e) => {
                                    setData('type', e.target.value);
                                    setSelectedType(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]"
                            >
                                <option value="hero">Hero Banner</option>
                                <option value="services">Specialized Services</option>
                                <option value="projects">Portfolio Case Studies</option>
                                <option value="team">Team Members</option>
                                <option value="testimonials">Testimonials Slider</option>
                                <option value="statistics">Key Metrics</option>
                                <option value="features">Core Values / Features</option>
                                <option value="cta">Marketing CTA</option>
                                <option value="faq">FAQ Accordion</option>
                            </select>
                        </div>

                        <div>
                            <label className="text-xs font-bold text-slate-400 block mb-2">Section Title Label</label>
                            <input
                                type="text"
                                value={data.title}
                                onChange={(e) => setData('title', e.target.value)}
                                placeholder="Custom heading"
                                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-end">
                            <button
                                type="submit"
                                disabled={processing}
                                className="btn-aqua w-full py-2.5 rounded-xl font-bold text-xs flex items-center justify-center gap-1.5"
                            >
                                <Plus className="w-4 h-4" /> Add Section to Page
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </AdminLayout>
    );
}
