import { useEffect, useState } from 'react';
import { Head, router } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Button } from '@/Components/ui/button';
import { Textarea } from '@/Components/ui/textarea';
import { Separator } from '@/Components/ui/separator';
import { Loader2, Upload, Globe, Share2, ImageIcon } from 'lucide-react';

export default function SeoSettings() {
    const [loading, setLoading] = useState(false);
    const[initialLoading, setInitialLoading] = useState(true);
    
    const [data, setData] = useState({
        site_name: '',
        meta_description: '',
        meta_keywords: '',
        og_title: '',
        og_description: '',
        site_logo_light: null, // Replaced single logo with light
        site_logo_dark: null,  // Added dark logo
        site_favicon: null,
        og_image: null,
    });

    // Preview URLs for existing images
    const[previews, setPreviews] = useState({
        site_logo_light: null,
        site_logo_dark: null,
        site_favicon: null,
        og_image: null
    });

    useEffect(() => {
        axios.get('/api/admin/settings/seo')
            .then(res => {
                const settings = res.data;
                setData(prev => ({
                    ...prev,
                    site_name: settings.site_name || '',
                    meta_description: settings.meta_description || '',
                    meta_keywords: settings.meta_keywords || '',
                    og_title: settings.og_title || '',
                    og_description: settings.og_description || '',
                }));
                setPreviews({
                    // Fallback to legacy `site_logo` if the new specific ones aren't set yet
                    site_logo_light: settings.site_logo_light || settings.site_logo,
                    site_logo_dark: settings.site_logo_dark || settings.site_logo,
                    site_favicon: settings.site_favicon,
                    og_image: settings.og_image
                });
            })
            .catch(error => {
                console.error(error);
                toast.error("Failed to load settings.");
            })
            .finally(() => setInitialLoading(false));
    },[]);

    const handleFileChange = (e, key) => {
        const file = e.target.files[0];
        if (file) {
            setData(prev => ({ ...prev, [key]: file }));
            setPreviews(prev => ({ ...prev, [key]: URL.createObjectURL(file) }));
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);

        const formData = new FormData();
        // Append all text fields
        Object.keys(data).forEach(key => {
            if (data[key] !== null && typeof data[key] !== 'object') {
                formData.append(key, data[key]);
            }
        });
        
        // Append files only if they are new File objects
        if (data.site_logo_light instanceof File) formData.append('site_logo_light', data.site_logo_light);
        if (data.site_logo_dark instanceof File) formData.append('site_logo_dark', data.site_logo_dark);
        if (data.site_favicon instanceof File) formData.append('site_favicon', data.site_favicon);
        if (data.og_image instanceof File) formData.append('og_image', data.og_image);

        try {
            await axios.post('/api/admin/settings/seo', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            toast.success("SEO Settings Updated", {
                description: "Changes have been saved and applied to the site."
            });
            
            // SPA Friendly Reload: Only fetches the updated 'site_settings' prop 
            // from the middleware without a full page refresh
            router.reload({ only: ['site_settings'], preserveScroll: true });
            
        } catch (error) {
            toast.error("Failed to update settings");
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    if (initialLoading) {
        return (
            <div className="flex flex-col items-center justify-center py-24 text-muted-foreground">
                <Loader2 className="h-8 w-8 animate-spin mb-4" />
                <p>Loading SEO Settings...</p>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <Head title="SEO Settings" />
            
            <form onSubmit={handleSubmit} className="space-y-8">
                
                {/* 1. General SEO */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Globe className="w-5 h-5 text-primary" /> General Identity
                        </CardTitle>
                        <CardDescription>Basic site information used by search engines and browser tabs.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="site_name">Site Name</Label>
                            <Input 
                                id="site_name" 
                                value={data.site_name} 
                                onChange={e => setData({...data, site_name: e.target.value})} 
                                placeholder="My Awesome App" 
                            />
                        </div>
                        
                        {/* Dual Logo Uploaders */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                            <ImageUploadField 
                                label="Logo (Light Mode)" 
                                id="site_logo_light" 
                                preview={previews.site_logo_light}
                                onChange={(e) => handleFileChange(e, 'site_logo_light')}
                                className="w-full h-32 bg-white border-gray-300"
                                helpText="Displayed when the user is using the Light theme."
                            />
                            <ImageUploadField 
                                label="Logo (Dark Mode)" 
                                id="site_logo_dark" 
                                preview={previews.site_logo_dark}
                                onChange={(e) => handleFileChange(e, 'site_logo_dark')}
                                className="w-full h-32 bg-zinc-950 border-zinc-800"
                                helpText="Displayed when the user is using the Dark theme."
                            />
                        </div>
                        
                        <div className="pt-2">
                            <ImageUploadField 
                                label="Favicon (Icon)" 
                                id="site_favicon" 
                                preview={previews.site_favicon}
                                onChange={(e) => handleFileChange(e, 'site_favicon')}
                                className="w-16 h-16" // Smaller preview for favicon
                            />
                        </div>
                    </CardContent>
                </Card>

                {/* 2. Meta Tags */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <SearchIcon className="w-5 h-5 text-primary" /> Meta Tags
                        </CardTitle>
                        <CardDescription>Control how your site appears in Google search results.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="meta_description">Meta Description</Label>
                            <Textarea 
                                id="meta_description" 
                                value={data.meta_description} 
                                onChange={e => setData({...data, meta_description: e.target.value})} 
                                placeholder="A brief description of your website..."
                                rows={3}
                            />
                            <p className="text-xs text-muted-foreground">Recommended length: 150-160 characters.</p>
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="meta_keywords">Keywords</Label>
                            <Input 
                                id="meta_keywords" 
                                value={data.meta_keywords} 
                                onChange={e => setData({...data, meta_keywords: e.target.value})} 
                                placeholder="news, blog, tech, react, laravel" 
                            />
                            <p className="text-xs text-muted-foreground">Separate keywords with commas.</p>
                        </div>
                    </CardContent>
                </Card>

                {/* 3. Social Media (Open Graph) */}
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Share2 className="w-5 h-5 text-primary" /> Social Media Sharing
                        </CardTitle>
                        <CardDescription>Customize how links look when shared on Facebook, Twitter/X, and LinkedIn.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="og_title">Social Title (OG:Title)</Label>
                            <Input 
                                id="og_title" 
                                value={data.og_title} 
                                onChange={e => setData({...data, og_title: e.target.value})} 
                                placeholder="Defaults to Site Name if empty" 
                            />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="og_description">Social Description (OG:Description)</Label>
                            <Textarea 
                                id="og_description" 
                                value={data.og_description} 
                                onChange={e => setData({...data, og_description: e.target.value})} 
                                placeholder="Defaults to Meta Description if empty" 
                            />
                        </div>
                        <ImageUploadField 
                            label="Social Share Image (OG:Image)" 
                            id="og_image" 
                            preview={previews.og_image}
                            onChange={(e) => handleFileChange(e, 'og_image')}
                            className="w-full h-48"
                            helpText="Recommended size: 1200x630 pixels."
                        />
                    </CardContent>
                </Card>

                <div className="sticky bottom-4 flex justify-end">
                    <Button type="submit" size="lg" disabled={loading} className="shadow-xl">
                        {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                        Save Changes
                    </Button>
                </div>

            </form>
        </div>
    );
}

// Helper Component for Image Inputs
function ImageUploadField({ label, id, preview, onChange, className = "w-full h-48", helpText }) {
    return (
        <div className="space-y-2">
            <Label htmlFor={id}>{label}</Label>
            <div className={`relative ${className} border-2 border-dashed rounded-md flex flex-col items-center justify-center bg-muted/30 overflow-hidden group`}>
                {preview ? (
                    <>
                        <img src={preview} alt="Preview" className="w-full h-full object-contain p-2" />
                        <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                            <span className="text-white font-medium text-sm">Click to Change</span>
                        </div>
                    </>
                ) : (
                    <div className="text-center text-muted-foreground">
                        <ImageIcon className="w-8 h-8 mx-auto mb-2 opacity-50" />
                        <span className="text-sm">Upload Image</span>
                    </div>
                )}
                <input 
                    type="file" 
                    id={id} 
                    onChange={onChange} 
                    accept="image/*"
                    className="absolute inset-0 opacity-0 cursor-pointer" 
                />
            </div>
            {helpText && <p className="text-xs text-muted-foreground">{helpText}</p>}
        </div>
    );
}

// Icon Helper
function SearchIcon(props) {
    return (
        <svg
          {...props}
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <circle cx="11" cy="11" r="8" />
          <path d="m21 21-4.3-4.3" />
        </svg>
    )
}

// Attach Layout
SeoSettings.layout = (page) => (
    <AdminLayout>
        <SettingsLayout children={page} />
    </AdminLayout>
);