import AdminLayout from '@/Layouts/AdminLayout';
import { Head, useForm, Link } from '@inertiajs/react';
import { Save, ArrowLeft, Image as ImageIcon, Search, Share2, Info, MapPin, Activity, Link as LinkIcon, ExternalLink, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { router } from '@inertiajs/react';
import { toast } from 'sonner';
import MediaPicker from '@/Components/MediaPicker';

interface Props {
    settings: {
        seo_title: string;
        seo_description: string;
        seo_keywords: string;
        seo_og_image: string | null;
        ga4_measurement_id: string | null;
        seo_social_linkedin: string | null;
        seo_social_twitter: string | null;
        seo_social_instagram: string | null;
        contact_nap_name: string | null;
        contact_nap_address: string | null;
        contact_nap_phone: string | null;
    };
    redirects: {
        id: number;
        old_path: string;
        new_path: string;
        type: number;
        created_at: string;
    }[];
}

export default function SEO({ settings, redirects }: Props) {
    const { data, setData, patch, processing } = useForm({
        seo_title: settings.seo_title || '',
        seo_description: settings.seo_description || '',
        seo_keywords: settings.seo_keywords || '',
        seo_og_image: settings.seo_og_image || '',
        ga4_measurement_id: settings.ga4_measurement_id || '',
        seo_social_linkedin: settings.seo_social_linkedin || '',
        seo_social_twitter: settings.seo_social_twitter || '',
        seo_social_instagram: settings.seo_social_instagram || '',
        contact_nap_name: settings.contact_nap_name || '',
        contact_nap_address: settings.contact_nap_address || '',
        contact_nap_phone: settings.contact_nap_phone || '',
    });

    const [pickerOpen, setPickerOpen] = useState(false);
    const [activeTab, setActiveTab] = useState('general');

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        patch(route('admin.settings.seo.update'), {
            onSuccess: () => toast.success('SEO settings updated'),
        });
    };

    const handleMediaSelect = (media: any) => {
        setData('seo_og_image', media.url);
        setPickerOpen(false);
    };

    const [newRedirect, setNewRedirect] = useState({ old_path: '', new_path: '', type: '301' });

    const handleCreateRedirect = (e: React.FormEvent) => {
        e.preventDefault();
        router.post(route('admin.redirects.store'), newRedirect, {
            preserveScroll: true,
            onSuccess: () => {
                setNewRedirect({ old_path: '', new_path: '', type: '301' });
                toast.success('Redirect created');
            },
        });
    };

    const handleDeleteRedirect = (id: number) => {
        if (confirm('Are you sure you want to delete this redirect?')) {
            router.delete(route('admin.redirects.destroy', id), {
                preserveScroll: true,
                onSuccess: () => toast.success('Redirect deleted'),
            });
        }
    };

    return (
        <AdminLayout>
            <Head title="SEO Center" />

            <div className="mb-8">
                <Link 
                    href={route('admin.settings.index')}
                    className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] hover:text-ink transition-colors mb-4"
                >
                    <ArrowLeft className="h-3 w-3" />
                    Back to Settings
                </Link>
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    SEO Center
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    Manage global search engine optimization, social sharing defaults, and tracking.
                </p>
            </div>

            <div className="max-w-4xl">
                {/* Tabs */}
                <div className="flex space-x-4 mb-6 border-b border-[#E8E6DF]">
                    <button
                        onClick={() => setActiveTab('general')}
                        className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${activeTab === 'general' ? 'border-accent text-accent' : 'border-transparent text-[#8C92AC] hover:text-ink'}`}
                    >
                        General Metadata
                    </button>
                    <button
                        onClick={() => setActiveTab('social')}
                        className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${activeTab === 'social' ? 'border-accent text-accent' : 'border-transparent text-[#8C92AC] hover:text-ink'}`}
                    >
                        Social & Integrations
                    </button>
                    <button
                        onClick={() => setActiveTab('local')}
                        className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${activeTab === 'local' ? 'border-accent text-accent' : 'border-transparent text-[#8C92AC] hover:text-ink'}`}
                    >
                        Local SEO (NAP)
                    </button>
                    <button
                        onClick={() => setActiveTab('redirects')}
                        className={`pb-3 px-1 text-sm font-medium border-b-2 transition-colors ${activeTab === 'redirects' ? 'border-accent text-accent' : 'border-transparent text-[#8C92AC] hover:text-ink'}`}
                    >
                        URL Redirects
                    </button>
                </div>

                <form onSubmit={submit} className="space-y-6">
                    <div className="grid gap-6 lg:grid-cols-12">
                        {/* LEFT: Main Settings */}
                        <div className="lg:col-span-8 space-y-6">
                            
                            {activeTab === 'general' && (
                                <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                    <div className="flex items-center gap-2 text-accent">
                                        <Search className="h-5 w-5" />
                                        <h3 className="font-bold text-ink">Search Metadata</h3>
                                    </div>
                                    
                                    <div>
                                        <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Global Meta Title
                                        </label>
                                        <input 
                                            type="text"
                                            value={data.seo_title}
                                            onChange={e => setData('seo_title', e.target.value)}
                                            className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all"
                                            placeholder="Company Name | Tagline"
                                        />
                                        <p className="mt-1.5 text-[11px] text-[#8C92AC]">Recommended: 50-60 characters.</p>
                                    </div>

                                    <div>
                                        <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Global Meta Description
                                        </label>
                                        <textarea 
                                            value={data.seo_description}
                                            onChange={e => setData('seo_description', e.target.value)}
                                            rows={4}
                                            className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all resize-none"
                                            placeholder="Enter a brief summary of your business..."
                                        />
                                        <p className="mt-1.5 text-[11px] text-[#8C92AC]">Recommended: 150-160 characters.</p>
                                    </div>

                                    <div>
                                        <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                            Global Keywords
                                        </label>
                                        <input 
                                            type="text"
                                            value={data.seo_keywords}
                                            onChange={e => setData('seo_keywords', e.target.value)}
                                            className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all"
                                            placeholder="growth, strategy, digital assets..."
                                        />
                                        <p className="mt-1.5 text-[11px] text-[#8C92AC]">Comma-separated list of keywords.</p>
                                    </div>
                                </div>
                            )}

                            {activeTab === 'social' && (
                                <>
                                    <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                        <div className="flex items-center gap-2 text-accent">
                                            <Share2 className="h-5 w-5" />
                                            <h3 className="font-bold text-ink">Social Sharing (OG Image)</h3>
                                        </div>

                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-3">
                                                Default Social Media Image
                                            </label>
                                            <div className="relative group aspect-video rounded-2xl bg-[#FAFAF8] border-2 border-dashed border-[#E8E6DF] flex items-center justify-center overflow-hidden">
                                                {data.seo_og_image ? (
                                                    <img src={data.seo_og_image} alt="SEO" className="w-full h-full object-cover" />
                                                ) : (
                                                    <div className="text-center">
                                                        <ImageIcon className="h-8 w-8 text-[#C0BDBA] mx-auto mb-3" />
                                                        <span className="text-[12px] text-[#8C92AC]">1200 x 630px recommended</span>
                                                    </div>
                                                )}
                                                <button 
                                                    type="button"
                                                    onClick={() => setPickerOpen(true)}
                                                    className="absolute inset-0 bg-ink/60 text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2 text-[14px] font-medium"
                                                >
                                                    <ImageIcon className="h-4 w-4" />
                                                    Choose Image
                                                </button>
                                            </div>
                                            <p className="mt-3 text-[11px] text-[#8C92AC]">This image will appear when you share links on WhatsApp, Twitter, and LinkedIn.</p>
                                        </div>
                                    </div>

                                    <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                        <div className="flex items-center gap-2 text-accent">
                                            <LinkIcon className="h-5 w-5" />
                                            <h3 className="font-bold text-ink">Organization Social Profiles</h3>
                                        </div>
                                        <p className="text-sm text-muted-foreground mb-4">
                                            These are injected into your site's JSON-LD schema to build brand authority (E-E-A-T).
                                        </p>

                                        <div className="space-y-4">
                                            <div>
                                                <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">LinkedIn URL</label>
                                                <input type="url" value={data.seo_social_linkedin} onChange={e => setData('seo_social_linkedin', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none" placeholder="https://linkedin.com/company/altivate" />
                                            </div>
                                            <div>
                                                <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">Twitter/X URL</label>
                                                <input type="url" value={data.seo_social_twitter} onChange={e => setData('seo_social_twitter', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none" placeholder="https://twitter.com/altivate" />
                                            </div>
                                            <div>
                                                <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">Instagram URL</label>
                                                <input type="url" value={data.seo_social_instagram} onChange={e => setData('seo_social_instagram', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none" placeholder="https://instagram.com/altivate" />
                                            </div>
                                        </div>
                                    </div>

                                    <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                        <div className="flex items-center gap-2 text-accent">
                                            <Activity className="h-5 w-5" />
                                            <h3 className="font-bold text-ink">Analytics Integration</h3>
                                        </div>

                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">
                                                GA4 Measurement ID
                                            </label>
                                            <input 
                                                type="text"
                                                value={data.ga4_measurement_id}
                                                onChange={e => setData('ga4_measurement_id', e.target.value)}
                                                className="w-full px-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none transition-all"
                                                placeholder="G-XXXXXXXXXX"
                                            />
                                            <p className="mt-1.5 text-[11px] text-[#8C92AC]">Adding this will automatically enable Google Analytics 4 tracking.</p>
                                        </div>
                                    </div>
                                </>
                            )}

                            {activeTab === 'local' && (
                                <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                    <div className="flex items-center gap-2 text-accent">
                                        <MapPin className="h-5 w-5" />
                                        <h3 className="font-bold text-ink">Business NAP (Name, Address, Phone)</h3>
                                    </div>
                                    <p className="text-sm text-muted-foreground mb-4">
                                        Ensure these match your Google Business Profile exactly to improve local SEO trust signals.
                                    </p>

                                    <div className="space-y-4">
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">Business Name</label>
                                            <input type="text" value={data.contact_nap_name} onChange={e => setData('contact_nap_name', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none" placeholder="Altivate Solutions" />
                                        </div>
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">Address</label>
                                            <textarea rows={3} value={data.contact_nap_address} onChange={e => setData('contact_nap_address', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none resize-none" placeholder="Full physical address..." />
                                        </div>
                                        <div>
                                            <label className="text-[12px] font-bold text-[#8C92AC] uppercase tracking-wider block mb-2">Phone Number</label>
                                            <input type="text" value={data.contact_nap_phone} onChange={e => setData('contact_nap_phone', e.target.value)} className="w-full px-4 py-2 bg-white border border-[#E8E6DF] rounded-xl text-[14px] focus:border-accent outline-none" placeholder="+234..." />
                                        </div>
                                    </div>
                                </div>
                            )}

                            {activeTab === 'redirects' && (
                                <div className="bg-white rounded-2xl border border-[#E8E6DF] overflow-hidden p-6 space-y-6">
                                    <div className="flex items-center gap-2 text-accent">
                                        <ExternalLink className="h-5 w-5" />
                                        <h3 className="font-bold text-ink">Redirect Manager</h3>
                                    </div>
                                    <p className="text-sm text-muted-foreground mb-4">
                                        Create 301 (Permanent) or 302 (Temporary) redirects to preserve SEO rankings when paths change.
                                    </p>

                                    {/* Add Redirect Form */}
                                    <div className="bg-[#FAFAF8] border border-[#E8E6DF] rounded-xl p-4 mb-6">
                                        <h4 className="text-sm font-bold mb-3">Add New Redirect</h4>
                                        <div className="grid grid-cols-1 md:grid-cols-12 gap-3">
                                            <div className="md:col-span-4">
                                                <input 
                                                    type="text" 
                                                    placeholder="Old Path (e.g. /old-blog)" 
                                                    value={newRedirect.old_path}
                                                    onChange={e => setNewRedirect({...newRedirect, old_path: e.target.value})}
                                                    className="w-full px-3 py-2 bg-white border border-[#E8E6DF] rounded-lg text-sm focus:border-accent outline-none"
                                                />
                                            </div>
                                            <div className="md:col-span-4">
                                                <input 
                                                    type="text" 
                                                    placeholder="New Path (e.g. /new-blog)" 
                                                    value={newRedirect.new_path}
                                                    onChange={e => setNewRedirect({...newRedirect, new_path: e.target.value})}
                                                    className="w-full px-3 py-2 bg-white border border-[#E8E6DF] rounded-lg text-sm focus:border-accent outline-none"
                                                />
                                            </div>
                                            <div className="md:col-span-2">
                                                <select
                                                    value={newRedirect.type}
                                                    onChange={e => setNewRedirect({...newRedirect, type: e.target.value})}
                                                    className="w-full px-3 py-2 bg-white border border-[#E8E6DF] rounded-lg text-sm focus:border-accent outline-none"
                                                >
                                                    <option value="301">301 (Permanent)</option>
                                                    <option value="302">302 (Temporary)</option>
                                                </select>
                                            </div>
                                            <div className="md:col-span-2">
                                                <button 
                                                    type="button"
                                                    onClick={handleCreateRedirect}
                                                    className="w-full px-3 py-2 bg-ink text-white rounded-lg text-sm font-semibold hover:bg-accent transition-colors"
                                                >
                                                    Add
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Redirects List */}
                                    <div className="border border-[#E8E6DF] rounded-xl overflow-hidden">
                                        <table className="w-full text-sm text-left">
                                            <thead className="bg-[#FAFAF8] text-[#8C92AC] font-medium border-b border-[#E8E6DF]">
                                                <tr>
                                                    <th className="px-4 py-3">Old Path</th>
                                                    <th className="px-4 py-3">New Path</th>
                                                    <th className="px-4 py-3 w-20 text-center">Type</th>
                                                    <th className="px-4 py-3 w-16"></th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {redirects.length === 0 ? (
                                                    <tr>
                                                        <td colSpan={4} className="px-4 py-8 text-center text-muted-foreground italic">No redirects found.</td>
                                                    </tr>
                                                ) : (
                                                    redirects.map((redirect) => (
                                                        <tr key={redirect.id} className="border-b border-[#E8E6DF] last:border-0 hover:bg-[#FAFAF8] transition-colors">
                                                            <td className="px-4 py-3 font-medium text-ink">{redirect.old_path}</td>
                                                            <td className="px-4 py-3 text-[#8C92AC]">{redirect.new_path}</td>
                                                            <td className="px-4 py-3 text-center">
                                                                <span className="bg-secondary text-ink px-2 py-0.5 rounded text-xs font-bold">{redirect.type}</span>
                                                            </td>
                                                            <td className="px-4 py-3 text-right">
                                                                <button 
                                                                    type="button"
                                                                    onClick={() => handleDeleteRedirect(redirect.id)}
                                                                    className="text-red-500 hover:bg-red-50 p-1.5 rounded transition-colors"
                                                                >
                                                                    <Trash2 className="h-4 w-4" />
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    ))
                                                )}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            )}

                        </div>

                        {/* RIGHT: Preview & Tips */}
                        <div className="lg:col-span-4 space-y-6">
                            {activeTab === 'general' && (
                                <div className="bg-ink text-white rounded-2xl p-6 shadow-xl">
                                    <div className="flex items-center gap-2 mb-6">
                                        <Info className="h-5 w-5 text-accent" />
                                        <h3 className="font-bold">Google Preview</h3>
                                    </div>
                                    
                                    <div className="space-y-1">
                                        <div className="text-[14px] text-accent truncate">altivatesolutions.com</div>
                                        <div className="text-[18px] font-medium text-blue-400 line-clamp-2 hover:underline cursor-pointer">
                                            {data.seo_title || 'Your SEO Title'}
                                        </div>
                                        <div className="text-[13px] text-gray-300 line-clamp-3">
                                            {data.seo_description || 'Your meta description will appear here to attract visitors from search results.'}
                                        </div>
                                    </div>
                                </div>
                            )}

                            <div className="bg-white rounded-2xl border border-[#E8E6DF] p-6">
                                <h4 className="text-[13px] font-bold text-ink uppercase tracking-wider mb-4">SEO Tips</h4>
                                <ul className="space-y-4">
                                    <li className="flex gap-3 text-[13px] text-[#8C92AC]">
                                        <span className="h-1.5 w-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                                        Keep titles descriptive and unique.
                                    </li>
                                    <li className="flex gap-3 text-[13px] text-[#8C92AC]">
                                        <span className="h-1.5 w-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                                        Include your primary keywords naturally.
                                    </li>
                                    <li className="flex gap-3 text-[13px] text-[#8C92AC]">
                                        <span className="h-1.5 w-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                                        Use a high-quality OG image for social credibility.
                                    </li>
                                    <li className="flex gap-3 text-[13px] text-[#8C92AC]">
                                        <span className="h-1.5 w-1.5 rounded-full bg-accent mt-1.5 shrink-0" />
                                        Consistent NAP data builds local search authority.
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div className="flex justify-end pt-4">
                        <button 
                            type="submit" 
                            disabled={processing}
                            className="w-full sm:w-auto px-12 py-4 bg-ink text-white rounded-2xl text-[15px] font-semibold flex items-center justify-center gap-2 hover:bg-accent transition-all shadow-lg active:scale-[0.98] disabled:opacity-50"
                        >
                            <Save className="h-4 w-4" />
                            {processing ? 'Saving...' : 'Publish SEO Settings'}
                        </button>
                    </div>
                </form>
            </div>

            <MediaPicker 
                open={pickerOpen}
                onClose={() => setPickerOpen(false)}
                onSelect={handleMediaSelect}
                title="Select Social Sharing Image"
            />
        </AdminLayout>
    );
}
