/**
 * 14 - useReducer Example
 * 
 * דוגמאות לשימוש ב-useReducer
 * לניהול state מורכב.
 */

import React, { useReducer, useState } from 'react';

// ============================================
// 1. Counter עם useReducer
// ============================================

function counterReducer(state, action) {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        case 'DECREMENT':
            return { count: state.count - 1 };
        case 'INCREMENT_BY':
            return { count: state.count + action.payload };
        case 'RESET':
            return { count: 0 };
        default:
            throw new Error(`Unknown action: ${action.type}`);
    }
}

function CounterExample() {
    const [state, dispatch] = useReducer(counterReducer, { count: 0 });

    return (
        <div>
            <h3>Counter עם useReducer</h3>
            <p style={{ fontSize: '2rem' }}>{state.count}</p>

            <div style={{ display: 'flex', gap: '10px' }}>
                <button onClick={() => dispatch({ type: 'DECREMENT' })}> ➖ </button>
                <button onClick={() => dispatch({ type: 'INCREMENT' })}> ➕ </button>
                <button onClick={() => dispatch({ type: 'INCREMENT_BY', payload: 10 })}> +10 </button>
                <button onClick={() => dispatch({ type: 'RESET' })}> 🔄     </button>
            </div>
        </div>
    );
}

// ============================================
// 2. Todo List עם useReducer
// ============================================

const ACTIONS = {
    ADD: 'ADD_TODO',
    TOGGLE: 'TOGGLE_TODO',
    DELETE: 'DELETE_TODO',
    EDIT: 'EDIT_TODO',
    CLEAR: 'CLEAR_COMPLETED'
};

function todoReducer(state, action) {
    switch (action.type) {
        case ACTIONS.ADD:
            return [
                ...state,
                { id: Date.now(), text: action.payload, completed: false }
            ];

        case ACTIONS.TOGGLE:
            return state.map(todo =>
                todo.id === action.payload
                    ? { ...todo, completed: !todo.completed }
                    : todo
            );

        case ACTIONS.DELETE:
            return state.filter(todo => todo.id !== action.payload);

        case ACTIONS.EDIT:
            return state.map(todo =>
                todo.id === action.payload.id
                    ? { ...todo, text: action.payload.text }
                    : todo
            );

        case ACTIONS.CLEAR:
            return state.filter(todo => !todo.completed);

        default:
            return state;
    }
}

function TodoExample() {
    const [todos, dispatch] = useReducer(todoReducer, [
        { id: 1, text: 'ללמוד React', completed: true },
        { id: 2, text: 'לתרגל useReducer', completed: false },
    ]);
    const [text, setText] = useState('');

    const handleAdd = () => {
        if (text.trim()) {
            dispatch({ type: ACTIONS.ADD, payload: text });
            setText('');
        }
    };

    const activeCount = todos.filter(t => !t.completed).length;

    return (
        <div>
            <h3>Todo List עם useReducer</h3>

            <div style={{ marginBottom: '15px' }}>
                <input
                    value={text}
                    onChange={(e) => setText(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleAdd()}
                    placeholder="הוסף משימה..."
                    style={{ padding: '8px', marginLeft: '10px' }}
                />
                <button onClick={handleAdd}>➕</button>
            </div>

            <ul style={{ listStyle: 'none', padding: 0 }}>
                {todos.map(todo => (
                    <li key={todo.id} style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '10px',
                        padding: '8px',
                        backgroundColor: todo.completed ? '#f5f5f5' : 'white',
                        marginBottom: '5px'
                    }}>
                        <input
                            type="checkbox"
                            checked={todo.completed}
                            onChange={() => dispatch({
                                type: ACTIONS.TOGGLE,
                                payload: todo.id
                            })}
                        />
                        <span style={{
                            flex: 1,
                            textDecoration: todo.completed ? 'line-through' : 'none',
                            color: todo.completed ? '#999' : 'inherit'
                        }}>
                            {todo.text}
                        </span>
                        <button onClick={() => dispatch({
                            type: ACTIONS.DELETE,
                            payload: todo.id
                        })}>
                            ❌
                        </button>
                    </li>
                ))}
            </ul>

            <p>נותרו: {activeCount} משימות</p>

            <button onClick={() => dispatch({ type: ACTIONS.CLEAR })}>
                🗑️ נקה הושלמו
            </button>
        </div>
    );
}

// ============================================
// 3. Form State עם useReducer
// ============================================

const initialFormState = {
    name: '',
    email: '',
    message: '',
    errors: {},
    isSubmitting: false,
    isSubmitted: false
};

function formReducer(state, action) {
    switch (action.type) {
        case 'SET_FIELD':
            return {
                ...state,
                [action.field]: action.value,
                errors: { ...state.errors, [action.field]: null }
            };

        case 'SET_ERRORS':
            return { ...state, errors: action.errors };

        case 'SUBMIT_START':
            return { ...state, isSubmitting: true, errors: {} };

        case 'SUBMIT_SUCCESS':
            return { ...initialFormState, isSubmitted: true };

        case 'SUBMIT_ERROR':
            return { ...state, isSubmitting: false, errors: action.errors };

        case 'RESET':
            return initialFormState;

        default:
            return state;
    }
}

function FormExample() {
    const [state, dispatch] = useReducer(formReducer, initialFormState);

    const handleChange = (field) => (e) => {
        dispatch({ type: 'SET_FIELD', field, value: e.target.value });
    };

    const validate = () => {
        const errors = {};
        if (!state.name) errors.name = 'שם נדרש';
        if (!state.email.includes('@')) errors.email = 'אימייל לא תקין';
        if (!state.message) errors.message = 'הודעה נדרשת';
        return errors;
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        const errors = validate();
        if (Object.keys(errors).length > 0) {
            dispatch({ type: 'SET_ERRORS', errors });
            return;
        }

        dispatch({ type: 'SUBMIT_START' });

        // סימולציית שליחה
        setTimeout(() => {
            dispatch({ type: 'SUBMIT_SUCCESS' });
        }, 1000);
    };

    if (state.isSubmitted) {
        return (
            <div style={{ textAlign: 'center', padding: '20px' }}>
                <h3>✅ נשלח בהצלחה!</h3>
                <button onClick={() => dispatch({ type: 'RESET' })}>
                    שלח שוב
                </button>
            </div>
        );
    }

    return (
        <div>
            <h3>Form עם useReducer</h3>

            <form onSubmit={handleSubmit}>
                <div style={{ marginBottom: '15px' }}>
                    <input
                        value={state.name}
                        onChange={handleChange('name')}
                        placeholder="שם"
                        style={{
                            padding: '8px',
                            width: '100%',
                            borderColor: state.errors.name ? 'red' : '#ddd'
                        }}
                    />
                    {state.errors.name && (
                        <span style={{ color: 'red', fontSize: '0.8rem' }}>
                            {state.errors.name}
                        </span>
                    )}
                </div>

                <div style={{ marginBottom: '15px' }}>
                    <input
                        type="email"
                        value={state.email}
                        onChange={handleChange('email')}
                        placeholder="אימייל"
                        style={{
                            padding: '8px',
                            width: '100%',
                            borderColor: state.errors.email ? 'red' : '#ddd'
                        }}
                    />
                    {state.errors.email && (
                        <span style={{ color: 'red', fontSize: '0.8rem' }}>
                            {state.errors.email}
                        </span>
                    )}
                </div>

                <div style={{ marginBottom: '15px' }}>
                    <textarea
                        value={state.message}
                        onChange={handleChange('message')}
                        placeholder="הודעה"
                        rows={4}
                        style={{
                            padding: '8px',
                            width: '100%',
                            borderColor: state.errors.message ? 'red' : '#ddd'
                        }}
                    />
                    {state.errors.message && (
                        <span style={{ color: 'red', fontSize: '0.8rem' }}>
                            {state.errors.message}
                        </span>
                    )}
                </div>

                <button type="submit" disabled={state.isSubmitting}>
                    {state.isSubmitting ? 'שולח...' : 'שלח'}
                </button>
            </form>
        </div>
    );
}

// ============================================
// קומפוננטה ראשית
// ============================================

function App() {
    return (
        <div style={{ padding: '20px' }}>
            <h1>🔀 useReducer Examples</h1>

            <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
                gap: '20px'
            }}>
                <section style={{ padding: '15px', border: '1px solid #ddd', borderRadius: '8px' }}>
                    <CounterExample />
                </section>

                <section style={{ padding: '15px', border: '1px solid #ddd', borderRadius: '8px' }}>
                    <TodoExample />
                </section>

                <section style={{ padding: '15px', border: '1px solid #ddd', borderRadius: '8px' }}>
                    <FormExample />
                </section>
            </div>
        </div>
    );
}

export default App;
