import React from 'react';
import { Head, useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Label } from "@/Components/ui/label";
import { Input } from "@/Components/ui/input";
import { Button } from "@/Components/ui/button";
import { Switch } from "@/Components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/Components/ui/select";
import { Save, Image as ImageIcon, Loader2, Zap, HardDrive, LayoutGrid } from "lucide-react";

export default function ImageOptimization({ settings }) {
    const parseBool = (key, defaultVal) => settings[key] !== undefined ? settings[key] === '1' : defaultVal;

    const { data, setData, post, processing } = useForm({
        image_compression_enabled: parseBool('image_compression_enabled', true),
        image_output_format: settings['image_output_format'] || 'webp',
        image_quality: settings['image_quality'] || '80',
        image_max_width: settings['image_max_width'] || '1200',
    });

    const submit = (e) => {
        e.preventDefault();
        post(route('cp.settings.image.update'), {
            preserveScroll: true,
            onSuccess: () => toast.success('Image optimization settings saved!'),
            onError: () => toast.error('Failed to save settings.')
        });
    };

    return (
        <AdminLayout>
            <Head title="Image Optimization" />

            <div className="max-w-4xl mx-auto space-y-6 pb-10">
                <div className="flex items-center gap-3 mb-6">
                    <ImageIcon className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">Image Compression Engine</h2>
                        <p className="text-muted-foreground text-sm">Automatically compress, resize, and convert uploaded images to save server disk space and improve load times.</p>
                    </div>
                </div>

                <form onSubmit={submit}>
                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="bg-muted/10 border-b pb-4">
                            <CardTitle>Optimization Settings</CardTitle>
                            <CardDescription>Powered by Intervention Image Engine.</CardDescription>
                        </CardHeader>
                        
                        <CardContent className="p-6 space-y-6">

                            {/* Master Toggle */}
                            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-5 border-2 rounded-xl bg-blue-500/5 border-blue-500/20">
                                <div className="flex items-start gap-3">
                                    <div className="p-2 bg-blue-500/20 rounded-md shrink-0">
                                        <Zap className="w-5 h-5 text-blue-600" />
                                    </div>
                                    <div>
                                        <Label className="font-bold text-lg text-blue-700 dark:text-blue-500">Enable Image Optimization</Label>
                                        <p className="text-sm text-blue-600/80 dark:text-blue-400/80 mt-1">
                                            If disabled, images will be uploaded exactly as users submit them (which may drain server storage quickly).
                                        </p>
                                    </div>
                                </div>
                                <Switch 
                                    checked={data.image_compression_enabled} 
                                    onCheckedChange={(v) => setData('image_compression_enabled', v)}
                                    className="data-[state=checked]:bg-blue-600 shrink-0"
                                />
                            </div>

                            {data.image_compression_enabled && (
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 animate-in fade-in slide-in-from-top-4">
                                    
                                    {/* Format */}
                                    <div className="space-y-3 p-5 border rounded-xl bg-card">
                                        <Label className="font-bold flex items-center gap-2"><HardDrive className="w-4 h-4 text-muted-foreground"/> Output Format</Label>
                                        <Select value={data.image_output_format} onValueChange={v => setData('image_output_format', v)}>
                                            <SelectTrigger className="bg-background">
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="webp">WEBP (Highly Recommended)</SelectItem>
                                                <SelectItem value="jpeg">JPEG (Standard)</SelectItem>
                                                <SelectItem value="png">PNG (Lossless - Larger Files)</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <p className="text-xs text-muted-foreground">WebP provides superior compression and quality characteristics compared to their older JPEG and PNG equivalents.</p>
                                    </div>

                                    {/* Quality */}
                                    <div className="space-y-3 p-5 border rounded-xl bg-card">
                                        <div className="flex justify-between items-center">
                                            <Label className="font-bold">Compression Quality (%)</Label>
                                            <span className="font-mono font-bold text-primary bg-primary/10 px-2 py-0.5 rounded">{data.image_quality}%</span>
                                        </div>
                                        <input 
                                            type="range" 
                                            min="10" max="100" 
                                            value={data.image_quality} 
                                            onChange={e => setData('image_quality', e.target.value)}
                                            className="w-full accent-primary"
                                        />
                                        <p className="text-xs text-muted-foreground">80% is the "Sweet Spot". Below 60% may cause visible pixelation.</p>
                                    </div>

                                    {/* Max Width */}
                                    <div className="space-y-3 p-5 border rounded-xl bg-card md:col-span-2">
                                        <Label className="font-bold flex items-center gap-2"><LayoutGrid className="w-4 h-4 text-muted-foreground"/> Maximum Image Width (px)</Label>
                                        <Input 
                                            type="number" 
                                            value={data.image_max_width} 
                                            onChange={e => setData('image_max_width', e.target.value)} 
                                            placeholder="1200"
                                            className="bg-background max-w-xs"
                                        />
                                        <p className="text-xs text-muted-foreground">Any image uploaded wider than this will be proportionally scaled down to this width. Set to 0 to disable resizing entirely.</p>
                                    </div>

                                </div>
                            )}
                            
                        </CardContent>

                        <CardFooter className="bg-muted/10 border-t py-4 justify-end">
                            <Button type="submit" disabled={processing} className="min-w-[140px] shadow-sm">
                                {processing ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
                                Save Preferences
                            </Button>
                        </CardFooter>
                    </Card>
                </form>
            </div>
        </AdminLayout>
    );
}