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

const RoleSettings = ({ roles, products, categories, nonce, initialSummary }) => {
    const [selectedRole, setSelectedRole] = 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 [roleSummary, setRoleSummary] = useState(initialSummary || {});

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

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

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

            if (response.ok) {
                setStatus({ type: 'success', message: 'Role rules deployed' });
                setRoleSummary(prev => ({
                    ...prev,
                    [selectedRole]: { enabled: settings.enabled, selectedProducts: settings.selectedProducts, selectedCategories: settings.selectedCategories }
                }));
            } else {
                setStatus({ type: 'error', message: 'Save failed' });
            }
        } catch (e) {
            setStatus({ type: 'error', message: 'Network error' });
        } 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 }}>Role-Based Rules</Typography>
                <Typography variant="body2">
                    Define visibility logic for specific user groups. Ideal for wholesale or member-only sections.
                </Typography>
            </Box>

            <Paper elevation={0} sx={{ p: 5, mb: 12, borderRadius: '20px', border: '1px solid rgba(226, 232, 240, 0.6)' }}>
                {/* Active Roles 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 }}>Active Role Rules</Typography>
                    <Stack direction="row" spacing={1.5} flexWrap="wrap" useFlexGap>
                        {Object.keys(roleSummary).map(roleKey => {
                            const role = roles.find(r => r.key === roleKey);
                            const isActive = roleSummary[roleKey]?.enabled;
                            if (!isActive) return null;
                            return (
                                <Chip
                                    key={roleKey}
                                    label={role ? role.name : roleKey}
                                    onClick={() => setSelectedRole(roleKey)}
                                    color={selectedRole === roleKey ? "primary" : "default"}
                                    variant={selectedRole === roleKey ? "filled" : "outlined"}
                                    clickable
                                    sx={{
                                        borderRadius: '10px',
                                        fontWeight: 600,
                                        height: 32,
                                        bgcolor: selectedRole === roleKey ? 'primary.main' : 'transparent',
                                        borderColor: selectedRole === roleKey ? 'primary.main' : 'rgba(226, 232, 240, 0.8)',
                                        '&:hover': {
                                            bgcolor: selectedRole === roleKey ? 'primary.dark' : 'rgba(0,0,0,0.02)'
                                        }
                                    }}
                                />
                            );
                        })}
                        {Object.keys(roleSummary).every(k => !roleSummary[k]?.enabled) && <Typography variant="caption" sx={{ color: 'text.disabled' }}>No specialized rules configured.</Typography>}
                    </Stack>
                </Box>

                <Box sx={{ mb: 6 }}>
                    <Typography variant="subtitle2" sx={{ mb: 1.5, fontWeight: 700 }}>Select Target Role</Typography>
                    <Select
                        fullWidth
                        value={selectedRole}
                        onChange={(e) => setSelectedRole(e.target.value)}
                        displayEmpty
                        renderValue={(selected) => {
                            if (!selected) return <Typography sx={{ color: 'text.disabled', fontSize: '0.875rem' }}>Start typing or choose a role...</Typography>;
                            const role = roles.find(r => r.key === selected);
                            return role ? role.name : selected;
                        }}
                        sx={{
                            borderRadius: '10px',
                            '& .MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(226, 232, 240, 0.8)' }
                        }}
                    >
                        {roles.map((role) => (
                            <MenuItem key={role.key} value={role.key} sx={{ py: 1.5, borderRadius: '8px', m: 0.5 }}>
                                {role.name}
                            </MenuItem>
                        ))}
                    </Select>
                </Box>

                {selectedRole ? (
                    <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 Logic for {roles.find(r => r.key === selectedRole)?.name}</Typography>
                                            <Typography variant="caption" sx={{ display: 'block' }}>When toggled on, the restrictions below will be enforced for this role.</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 }}>Hide specific products</Typography>
                                        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>These items will vanish for users with this role.</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="Search catalog..." />}
                                    />
                                </Grid>

                                <Grid item xs={12}>
                                    <Box sx={{ mb: 1.5 }}>
                                        <Typography variant="subtitle2" sx={{ fontWeight: 700, mb: 0.5 }}>Hide specific categories</Typography>
                                        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>Entire product groups will be hidden from view.</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="Search categories..." />}
                                    />
                                </Grid>
                            </Grid>
                        </Box>
                    </Fade>
                ) : (
                    <Box sx={{ py: 10, textAlign: 'center', opacity: 0.5 }}>
                        <Typography variant="body2">Choose a user role to begin configuring specialized rules.</Typography>
                    </Box>
                )}
            </Paper>

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

export default RoleSettings;
