import React, { useState, useEffect, useRef } 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 } from '@/Components/ui/card';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { Button } from '@/Components/ui/button';
import { Switch } from '@/Components/ui/switch';
import { Loader2, Smartphone, ImageIcon } from 'lucide-react';

export default function PwaSettings() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    
    const [data, setData] = useState({
        pwa_enabled: false,
        pwa_name: '',
        pwa_short_name: '',
        pwa_theme_color: '#ffffff',
        pwa_background_color: '#ffffff',
        pwa_icon: null
    });

    const [preview, setPreview] = useState(null);
    const fileInputRef = useRef(null);

    useEffect(() => {
        axios.get('/api/admin/settings/pwa')
            .then(res => {
                setData({
                    pwa_enabled: res.data.pwa_enabled,
                    pwa_name: res.data.pwa_name || '',
                    pwa_short_name: res.data.pwa_short_name || '',
                    pwa_theme_color: res.data.pwa_theme_color || '#ffffff',
                    pwa_background_color: res.data.pwa_background_color || '#ffffff',
                    pwa_icon: null
                });
                setPreview(res.data.pwa_icon);
            })
            .catch(() => toast.error("Failed to load settings."))
            .finally(() => setLoading(false));
    }, []);

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

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);

        const formData = new FormData();
        formData.append('pwa_enabled', data.pwa_enabled ? 'true' : 'false');
        formData.append('pwa_name', data.pwa_name);
        formData.append('pwa_short_name', data.pwa_short_name);
        formData.append('pwa_theme_color', data.pwa_theme_color);
        formData.append('pwa_background_color', data.pwa_background_color);
        
        if (data.pwa_icon instanceof File) {
            formData.append('pwa_icon', data.pwa_icon);
        }

        try {
            await axios.post('/api/admin/settings/pwa', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            toast.success("PWA settings updated successfully!");
        } catch (error) {
            toast.error("Failed to update settings.");
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminLayout header="Settings">
            <Head title="PWA Settings" />
            <SettingsLayout>
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Smartphone className="w-5 h-5 text-primary" /> PWA (Progressive Web App)
                        </CardTitle>
                        <CardDescription>
                            Allow users to install your website as an app on their Mobile or Desktop.
                        </CardDescription>
                    </CardHeader>
                    
                    <CardContent className="space-y-6 pt-4">
                        {loading ? (
                            <div className="flex justify-center py-8">
                                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                            </div>
                        ) : (
                            <form onSubmit={handleSave} className="space-y-6">
                                
                                <div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm bg-card">
                                    <div className="space-y-0.5">
                                        <Label className="text-base">Enable PWA Feature</Label>
                                        <p className="text-sm text-muted-foreground">
                                            Turn on to generate the Manifest file and enable "Add to Homescreen".
                                        </p>
                                    </div>
                                    <Switch 
                                        checked={data.pwa_enabled}
                                        onCheckedChange={(c) => setData({...data, pwa_enabled: c})}
                                    />
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>App Full Name</Label>
                                        <Input 
                                            value={data.pwa_name} 
                                            onChange={e => setData({...data, pwa_name: e.target.value})} 
                                            placeholder="Titan News - The Best Portal" required
                                        />
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Short Name (Homescreen Name)</Label>
                                        <Input 
                                            value={data.pwa_short_name} 
                                            onChange={e => setData({...data, pwa_short_name: e.target.value})} 
                                            placeholder="Titan News" required
                                        />
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Theme Color</Label>
                                        <div className="flex gap-2">
                                            <Input 
                                                type="color" 
                                                className="w-14 h-10 p-1 cursor-pointer" 
                                                value={data.pwa_theme_color} 
                                                onChange={e => setData({...data, pwa_theme_color: e.target.value})}
                                            />
                                            <Input value={data.pwa_theme_color} onChange={e => setData({...data, pwa_theme_color: e.target.value})} />
                                        </div>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>Background Color (Splash Screen)</Label>
                                        <div className="flex gap-2">
                                            <Input 
                                                type="color" 
                                                className="w-14 h-10 p-1 cursor-pointer" 
                                                value={data.pwa_background_color} 
                                                onChange={e => setData({...data, pwa_background_color: e.target.value})}
                                            />
                                            <Input value={data.pwa_background_color} onChange={e => setData({...data, pwa_background_color: e.target.value})} />
                                        </div>
                                    </div>
                                </div>

                                <div className="space-y-2 border p-4 rounded-lg bg-muted/20">
                                    <Label>PWA App Icon (512x512 PNG recommended)</Label>
                                    <div className="flex items-center gap-4 mt-2">
                                        <div className="w-24 h-24 shrink-0 rounded-xl border-2 border-dashed bg-background flex items-center justify-center overflow-hidden">
                                            {preview ? (
                                                <img src={preview} alt="Icon" className="w-full h-full object-contain" />
                                            ) : (
                                                <ImageIcon className="text-muted-foreground w-8 h-8 opacity-50" />
                                            )}
                                        </div>
                                        <div className="space-y-2">
                                            <Button type="button" variant="secondary" onClick={() => fileInputRef.current.click()}>
                                                Upload Icon
                                            </Button>
                                            <input 
                                                type="file" 
                                                ref={fileInputRef} 
                                                className="hidden" 
                                                accept="image/png, image/jpeg" 
                                                onChange={handleFileChange} 
                                            />
                                            <p className="text-xs text-muted-foreground">This icon will show on the user's mobile home screen.</p>
                                        </div>
                                    </div>
                                </div>

                                <div className="flex justify-end pt-4 border-t">
                                    <Button type="submit" disabled={saving} className="min-w-[150px]">
                                        {saving ? <Loader2 className="me-2 h-4 w-4 animate-spin" /> : <Smartphone className="me-2 h-4 w-4" />}
                                        Save PWA Settings
                                    </Button>
                                </div>

                            </form>
                        )}
                    </CardContent>
                </Card>
            </SettingsLayout>
        </AdminLayout>
    );
}