import React, { useState, useEffect } from 'react';
import { Box, Paper, Typography, FormControlLabel, Switch, Autocomplete, TextField, Fade, Grid } from '@mui/material';
import SaveBar from '../components/SaveBar';

const GlobalSettings = ({ products, categories, nonce }) => {
    const [settings, setSettings] = useState({
        enabled: false,
        selectedProducts: [],
        selectedCategories: []
    });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [status, setStatus] = useState(null);

    useEffect(() => {
        const fetchSettings = async () => {
            try {
                const response = await fetch('/wp-json/srfw/v1/settings/get-saved-data', {
                    headers: { 'X-WP-Nonce': nonce }
                });
                if (response.ok) {
                    const data = await response.json();
                    setSettings({
                        enabled: !!data.enabled,
                        selectedProducts: data.selectedProducts || [],
                        selectedCategories: data.selectedCategories || []
                    });
                }
            } catch (e) {
                console.error(e);
            } finally {
                setLoading(false);
            }
        };
        fetchSettings();
    }, [nonce]);

    const handleSave = async () => {
        setSaving(true);
        setStatus(null);
        try {
            const response = await fetch('/wp-json/srfw/v1/settings/global', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify(settings)
            });

            if (response.ok) {
                setStatus({ type: 'success', message: 'Rules deployed successfully' });
            } else {
                setStatus({ type: 'error', message: 'Deployment failed' });
            }
        } catch (e) {
            setStatus({ type: 'error', message: 'Network connection issue' });
        } finally {
            setSaving(false);
            setTimeout(() => setStatus(null), 4000);
        }
    };

    if (loading) return <Typography sx={{ p: 4, opacity: 0.6 }}>Synchronizing settings...</Typography>;

    return (
        <Fade in={!loading}>
            <Box sx={{ maxWidth: 900, mx: 'auto' }}>
                <Box sx={{ mb: 6 }}>
                    <Typography variant="h5" sx={{ mb: 1, fontWeight: 800 }}>Global Restrictions</Typography>
                    <Typography variant="body2">
                        Control visibility across your entire WooCommerce catalog. Enabled rules apply globally.
                    </Typography>
                </Box>

                <Paper elevation={0} sx={{ p: 5, mb: 12, borderRadius: '20px', border: '1px solid rgba(226, 232, 240, 0.6)' }}>
                    <Box sx={{ mb: 6, pb: 4, borderBottom: '1px solid rgba(226, 232, 240, 0.4)' }}>
                        <FormControlLabel
                            control={
                                <Switch
                                    checked={settings.enabled}
                                    onChange={(e) => setSettings({ ...settings, enabled: e.target.checked })}
                                    color="primary"
                                />
                            }
                            label={
                                <Box sx={{ ml: 2 }}>
                                    <Typography variant="subtitle1" sx={{ color: 'text.primary', fontWeight: 700 }}>Master Toggle</Typography>
                                    <Typography variant="caption" sx={{ display: 'block' }}>Activate or deactivate all global restriction logic at once.</Typography>
                                </Box>
                            }
                            sx={{ alignItems: 'flex-start', m: 0 }}
                        />
                    </Box>

                    <Grid container spacing={5}>
                        <Grid item xs={12}>
                            <Box sx={{ mb: 1 }}>
                                <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Restricted Products</Typography>
                                <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mb: 2 }}>Select items to hide from all non-admin users.</Typography>
                            </Box>
                            <Autocomplete
                                multiple
                                options={products}
                                getOptionLabel={(option) => option.name}
                                value={settings.selectedProducts.map(id => products.find(p => p.id === id) || { id, name: 'Unknown Product' })}
                                onChange={(e, newVal) => setSettings({ ...settings, selectedProducts: newVal.map(p => p.id) })}
                                renderInput={(params) => <TextField {...params} placeholder="Type product name..." />}
                            />
                        </Grid>

                        <Grid item xs={12}>
                            <Box sx={{ mb: 1 }}>
                                <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Restricted Categories</Typography>
                                <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mb: 2 }}>Hide entire categories from the shop and archives.</Typography>
                            </Box>
                            <Autocomplete
                                multiple
                                options={categories}
                                getOptionLabel={(option) => option.name}
                                value={settings.selectedCategories.map(id => categories.find(c => c.id === id) || { id, name: 'Unknown Category' })}
                                onChange={(e, newVal) => setSettings({ ...settings, selectedCategories: newVal.map(c => c.id) })}
                                renderInput={(params) => <TextField {...params} placeholder="Type category name..." />}
                            />
                        </Grid>
                    </Grid>
                </Paper>

                <SaveBar onSave={handleSave} isSaving={saving} status={status} />
            </Box>
        </Fade>
    );
};

export default GlobalSettings;
