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

const CountrySettings = ({ countries, products, categories, nonce, initialSummary }) => {
    const [selectedCountry, setSelectedCountry] = useState('');
    const [settings, setSettings] = useState({
        enabled: false,
        selectedProducts: [],
        selectedCategories: []
    });
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);
    const [status, setStatus] = useState(null);
    const [countrySummary, setCountrySummary] = useState(initialSummary || {});

    useEffect(() => {
        if (!selectedCountry) return;

        const fetchCountrySettings = async () => {
            setLoading(true);
            try {
                const response = await fetch(`/wp-json/srfw/v1/settings/country/${selectedCountry}`, {
                    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);
            }
        };
        fetchCountrySettings();
    }, [selectedCountry, nonce]);

    const handleSave = async () => {
        if (!selectedCountry) {
            setStatus({ type: 'error', message: 'Choose a location first' });
            return;
        }
        setSaving(true);
        setStatus(null);
        try {
            const payload = { ...settings, selectedCountry };
            const response = await fetch('/wp-json/srfw/v1/settings/country', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                setStatus({ type: 'success', message: 'Location rules applied' });
                setCountrySummary(prev => ({
                    ...prev,
                    [selectedCountry]: { enabled: settings.enabled, selectedProducts: settings.selectedProducts, selectedCategories: settings.selectedCategories }
                }));
            } else {
                setStatus({ type: 'error', message: 'Application failed' });
            }
        } catch (e) {
            setStatus({ type: 'error', message: 'Network synchronization issue' });
        } finally {
            setSaving(false);
            setTimeout(() => setStatus(null), 4000);
        }
    };

    return (
        <Box sx={{ maxWidth: 900, mx: 'auto' }}>
            <Box sx={{ mb: 6 }}>
                <Typography variant="h5" sx={{ mb: 1, fontWeight: 800 }}>Geo-Targeted Rules</Typography>
                <Typography variant="body2">
                    Restrict access based on the visitor's geographic location. Compliance and regional optimization made simple.
                </Typography>
            </Box>

            <Paper elevation={0} sx={{ p: 5, mb: 12, borderRadius: '20px', border: '1px solid rgba(226, 232, 240, 0.6)' }}>
                {/* Active Countries Summary */}
                <Box sx={{ mb: 6, pb: 4, borderBottom: '1px solid rgba(226, 232, 240, 0.4)' }}>
                    <Typography variant="subtitle2" sx={{ mb: 2.5, fontWeight: 700 }}>Configured Regions</Typography>
                    <Stack direction="row" spacing={1.5} flexWrap="wrap" useFlexGap sx={{ maxHeight: 150, overflowY: 'auto', p: 0.5 }}>
                        {Object.keys(countrySummary).map(code => {
                            const country = countries.find(c => c.code === code);
                            const isActive = countrySummary[code]?.enabled;
                            if (!isActive) return null;
                            return (
                                <Chip
                                    key={code}
                                    label={country ? country.name : code}
                                    onClick={() => setSelectedCountry(code)}
                                    color={selectedCountry === code ? "primary" : "default"}
                                    variant={selectedCountry === code ? "filled" : "outlined"}
                                    clickable
                                    sx={{
                                        borderRadius: '10px',
                                        fontWeight: 600,
                                        height: 32,
                                        bgcolor: selectedCountry === code ? 'primary.main' : 'transparent',
                                        borderColor: selectedRole === code ? 'primary.main' : 'rgba(226, 232, 240, 0.8)',
                                        '&:hover': {
                                            bgcolor: selectedCountry === code ? 'primary.dark' : 'rgba(0,0,0,0.02)'
                                        }
                                    }}
                                />
                            );
                        })}
                        {Object.keys(countrySummary).every(k => !countrySummary[k]?.enabled) && <Typography variant="caption" sx={{ color: 'text.disabled' }}>No active regional rules.</Typography>}
                    </Stack>
                </Box>

                <Box sx={{ mb: 6 }}>
                    <Typography variant="subtitle2" sx={{ mb: 1.5, fontWeight: 700 }}>Select Targeting Location</Typography>
                    <Autocomplete
                        options={countries}
                        getOptionLabel={(option) => option.name}
                        value={countries.find(c => c.code === selectedCountry) || null}
                        onChange={(e, newVal) => setSelectedCountry(newVal ? newVal.code : '')}
                        renderInput={(params) => <TextField {...params} placeholder="Search countries..." />}
                        sx={{
                            '& .MuiOutlinedInput-root': { borderRadius: '10px' }
                        }}
                    />
                </Box>

                {selectedCountry ? (
                    <Fade in={true}>
                        <Box>
                            <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 }}>Enable Enforcements for {countries.find(c => c.code === selectedCountry)?.name}</Typography>
                                            <Typography variant="caption" sx={{ display: 'block' }}>When active, regional users will see the restricted catalog defined below.</Typography>
                                        </Box>
                                    }
                                    sx={{ alignItems: 'flex-start', m: 0 }}
                                />
                            </Box>

                            <Grid container spacing={5}>
                                <Grid item xs={12}>
                                    <Box sx={{ mb: 1.5 }}>
                                        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Restricted Products</Typography>
                                        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>These items will be invisible to users in this location.</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="Product lookup..." />}
                                    />
                                </Grid>

                                <Grid item xs={12}>
                                    <Box sx={{ mb: 1.5 }}>
                                        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Restricted Categories</Typography>
                                        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>Filter out entire categories for this region.</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="Category search..." />}
                                    />
                                </Grid>
                            </Grid>
                        </Box>
                    </Fade>
                ) : (
                    <Box sx={{ py: 10, textAlign: 'center', opacity: 0.5 }}>
                        <Typography variant="body2">Choose a country to start configuring region-specific catalog rules.</Typography>
                    </Box>
                )}
            </Paper>

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

export default CountrySettings;
