/**
 * 16 - Redux Toolkit Example
 * 
 * דוגמה לשימוש ב-Redux Toolkit
 * עם Store, Slice, Actions.
 */

import React from 'react';
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';

// ============================================
// Counter Slice
// ============================================

const counterSlice = createSlice({
    name: 'counter',
    initialState: { value: 0 },
    reducers: {
        increment: (state) => {
            state.value += 1;
        },
        decrement: (state) => {
            state.value -= 1;
        },
        incrementByAmount: (state, action) => {
            state.value += action.payload;
        },
        reset: (state) => {
            state.value = 0;
        }
    }
});

const { increment, decrement, incrementByAmount, reset } = counterSlice.actions;

// ============================================
// Todos Slice
// ============================================

const todosSlice = createSlice({
    name: 'todos',
    initialState: {
        items: [
            { id: 1, text: 'ללמוד Redux', completed: false },
            { id: 2, text: 'לבנות אפליקציה', completed: false }
        ],
        filter: 'all'
    },
    reducers: {
        addTodo: {
            reducer: (state, action) => {
                state.items.push(action.payload);
            },
            prepare: (text) => ({
                payload: {
                    id: Date.now(),
                    text,
                    completed: false
                }
            })
        },
        toggleTodo: (state, action) => {
            const todo = state.items.find(t => t.id === action.payload);
            if (todo) {
                todo.completed = !todo.completed;
            }
        },
        deleteTodo: (state, action) => {
            state.items = state.items.filter(t => t.id !== action.payload);
        },
        setFilter: (state, action) => {
            state.filter = action.payload;
        },
        clearCompleted: (state) => {
            state.items = state.items.filter(t => !t.completed);
        }
    }
});

const { addTodo, toggleTodo, deleteTodo, setFilter, clearCompleted } = todosSlice.actions;

// ============================================
// Store Configuration
// ============================================

const store = configureStore({
    reducer: {
        counter: counterSlice.reducer,
        todos: todosSlice.reducer
    }
});

// ============================================
// Selectors
// ============================================

const selectCount = (state) => state.counter.value;
const selectTodos = (state) => state.todos.items;
const selectFilter = (state) => state.todos.filter;

const selectFilteredTodos = (state) => {
    const { items, filter } = state.todos;
    switch (filter) {
        case 'active': return items.filter(t => !t.completed);
        case 'completed': return items.filter(t => t.completed);
        default: return items;
    }
};

// ============================================
// Counter Component
// ============================================

function Counter() {
    const count = useSelector(selectCount);
    const dispatch = useDispatch();

    return (
        <div style={{
            padding: '20px',
            border: '1px solid #ddd',
            borderRadius: '8px',
            marginBottom: '20px'
        }}>
            <h2>🔢 Counter</h2>
            <p style={{ fontSize: '2rem' }}>{count}</p>

            <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                <button onClick={() => dispatch(decrement())}>➖</button>
                <button onClick={() => dispatch(increment())}>➕</button>
                <button onClick={() => dispatch(incrementByAmount(5))}>+5</button>
                <button onClick={() => dispatch(incrementByAmount(10))}>+10</button>
                <button onClick={() => dispatch(reset())}>🔄</button>
            </div>
        </div>
    );
}

// ============================================
// TodoList Component
// ============================================

function TodoList() {
    const todos = useSelector(selectFilteredTodos);
    const filter = useSelector(selectFilter);
    const allTodos = useSelector(selectTodos);
    const dispatch = useDispatch();
    const [text, setText] = React.useState('');

    const handleAdd = () => {
        if (text.trim()) {
            dispatch(addTodo(text));
            setText('');
        }
    };

    const stats = {
        total: allTodos.length,
        active: allTodos.filter(t => !t.completed).length,
        completed: allTodos.filter(t => t.completed).length
    };

    return (
        <div style={{
            padding: '20px',
            border: '1px solid #ddd',
            borderRadius: '8px'
        }}>
            <h2>✅ Todo List</h2>

            {/* הוספת משימה */}
            <div style={{ display: 'flex', gap: '10px', marginBottom: '15px' }}>
                <input
                    value={text}
                    onChange={(e) => setText(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleAdd()}
                    placeholder="משימה חדשה..."
                    style={{ flex: 1, padding: '8px' }}
                />
                <button onClick={handleAdd}>➕</button>
            </div>

            {/* פילטרים */}
            <div style={{ display: 'flex', gap: '5px', marginBottom: '15px' }}>
                {['all', 'active', 'completed'].map(f => (
                    <button
                        key={f}
                        onClick={() => dispatch(setFilter(f))}
                        style={{
                            padding: '8px 15px',
                            backgroundColor: filter === f ? '#3498db' : '#ecf0f1',
                            color: filter === f ? 'white' : 'black',
                            border: 'none',
                            cursor: 'pointer'
                        }}
                    >
                        {f === 'all' ? `הכל (${stats.total})` :
                            f === 'active' ? `פעילות (${stats.active})` :
                                `הושלמו (${stats.completed})`}
                    </button>
                ))}
            </div>

            {/* רשימת משימות */}
            <ul style={{ listStyle: 'none', padding: 0 }}>
                {todos.map(todo => (
                    <li key={todo.id} style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '10px',
                        padding: '10px',
                        backgroundColor: todo.completed ? '#f5f5f5' : 'white',
                        marginBottom: '5px',
                        borderRadius: '4px',
                        border: '1px solid #eee'
                    }}>
                        <input
                            type="checkbox"
                            checked={todo.completed}
                            onChange={() => dispatch(toggleTodo(todo.id))}
                        />
                        <span style={{
                            flex: 1,
                            textDecoration: todo.completed ? 'line-through' : 'none',
                            color: todo.completed ? '#999' : 'inherit'
                        }}>
                            {todo.text}
                        </span>
                        <button
                            onClick={() => dispatch(deleteTodo(todo.id))}
                            style={{ background: 'none', border: 'none', cursor: 'pointer' }}
                        >
                            ❌
                        </button>
                    </li>
                ))}
            </ul>

            {/* כפתור ניקוי */}
            {stats.completed > 0 && (
                <button
                    onClick={() => dispatch(clearCompleted())}
                    style={{ marginTop: '10px' }}
                >
                    🗑️ נקה הושלמו
                </button>
            )}
        </div>
    );
}

// ============================================
// Main App
// ============================================

function AppContent() {
    return (
        <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
            <h1>🏪 Redux Toolkit Example</h1>
            <Counter />
            <TodoList />
        </div>
    );
}

function App() {
    return (
        <Provider store={store}>
            <AppContent />
        </Provider>
    );
}

export default App;

/*
    הערות:
    
    1. configureStore - יוצר store עם middleware מובנה
    2. createSlice - יוצר reducer + actions ביחד
    3. Immer מובנה - אפשר "לשנות" state ישירות
    4. useSelector - קורא מה-store
    5. useDispatch - שולח actions
    
    להתקנה:
    npm install @reduxjs/toolkit react-redux
*/
