import { useState, useEffect, useCallback } from '@wordpress/element';
import AgentCard from '../components/AgentCard';
import AgentForm from '../components/AgentForm';
import { useAgents } from '../stores/agents';

const { __ } = wp.i18n;

export default function Dashboard() {
    const {
        agents,
        loading,
        error,
        fetchAgents,
        createAgent,
        updateAgent,
        deleteAgent,
        toggleAgent,
        runAgent,
        duplicateAgent,
    } = useAgents();

    const [showForm, setShowForm] = useState(false);
    const [editingAgent, setEditingAgent] = useState(null);
    const [notification, setNotification] = useState(null);
    const [search, setSearch] = useState('');
    const [filterProvider, setFilterProvider] = useState('all');

    useEffect(() => {
        fetchAgents();
    }, [fetchAgents]);

    const showNotification = (message, type = 'success') => {
        setNotification({ message, type });
        setTimeout(() => setNotification(null), 3000);
    };

    const handleCreate = () => {
        setEditingAgent(null);
        setShowForm(true);
    };

    const handleEdit = (agent) => {
        setEditingAgent(agent);
        setShowForm(true);
    };

    const handleSave = async (data) => {
        try {
            if (editingAgent) {
                await updateAgent(editingAgent.id, data);
                showNotification(__('Agent updated.', 'ai-bulk-post'));
            } else {
                await createAgent(data);
                showNotification(__('Agent created.', 'ai-bulk-post'));
            }
            setShowForm(false);
            setEditingAgent(null);
        } catch (err) {
            showNotification(err.message, 'error');
        }
    };

    const handleDelete = async (id) => {
        if (!confirm(AIBulkPost.i18n.confirmDelete)) return;
        try {
            await deleteAgent(id);
            showNotification(__('Agent deleted.', 'ai-bulk-post'));
        } catch (err) {
            showNotification(err.message, 'error');
        }
    };

    const handleToggle = async (id) => {
        try {
            const result = await toggleAgent(id);
            showNotification(
                result.active
                    ? AIBulkPost.i18n.activated
                    : AIBulkPost.i18n.deactivated
            );
        } catch (err) {
            showNotification(err.message, 'error');
        }
    };

    const handleRun = async (id) => {
        try {
            const result = await runAgent(id);
            showNotification(
                __('Post generated: #%s', 'ai-bulk-post').replace('%s', result.post_id)
            );
            fetchAgents();
        } catch (err) {
            showNotification(err.message, 'error');
        }
    };

    const handleDuplicate = async (id) => {
        try {
            await duplicateAgent(id);
            showNotification(AIBulkPost.i18n.duplicated);
        } catch (err) {
            showNotification(err.message, 'error');
        }
    };

    const filteredAgents = agents.filter((agent) => {
        const matchesSearch =
            !search ||
            agent.title.toLowerCase().includes(search.toLowerCase()) ||
            agent.subject.toLowerCase().includes(search.toLowerCase());
        const matchesProvider =
            filterProvider === 'all' || agent.provider === filterProvider;
        return matchesSearch && matchesProvider;
    });

    const providers = [...new Set(agents.map((a) => a.provider))];

    return (
        <div className="aibp-dashboard">
            {notification && (
                <div className={`aibp-notice aibp-notice-${notification.type}`}>
                    {notification.message}
                </div>
            )}

            <div className="aibp-header">
                <h1 className="wp-heading-inline">
                    {__('AI Bulk Post', 'ai-bulk-post')}
                </h1>
                <button
                    className="page-title-action aibp-btn-primary"
                    onClick={handleCreate}
                >
                    {AIBulkPost.i18n.addAgent}
                </button>
                <hr className="wp-header-end" />
            </div>

            <div className="aibp-toolbar">
                <input
                    type="search"
                    placeholder={__('Search agents...', 'ai-bulk-post')}
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="aibp-search"
                />
                <select
                    value={filterProvider}
                    onChange={(e) => setFilterProvider(e.target.value)}
                    className="aibp-filter-select"
                >
                    <option value="all">{__('All Providers', 'ai-bulk-post')}</option>
                    {providers.map((p) => (
                        <option key={p} value={p}>
                            {p}
                        </option>
                    ))}
                </select>
            </div>

            {loading && agents.length === 0 && (
                <div className="aibp-loading">
                    <span className="spinner is-active"></span>
                    {__('Loading agents...', 'ai-bulk-post')}
                </div>
            )}

            {!loading && agents.length === 0 && (
                <div className="aibp-empty-state">
                    <h2>{__('No agents yet', 'ai-bulk-post')}</h2>
                    <p>{AIBulkPost.i18n.noAgents}</p>
                    <button
                        className="aibp-btn-primary"
                        onClick={handleCreate}
                    >
                        {AIBulkPost.i18n.addAgent}
                    </button>
                </div>
            )}

            {filteredAgents.length > 0 && (
                <div className="aibp-agents-grid">
                    {filteredAgents.map((agent) => (
                        <AgentCard
                            key={agent.id}
                            agent={agent}
                            onEdit={() => handleEdit(agent)}
                            onDelete={() => handleDelete(agent.id)}
                            onToggle={() => handleToggle(agent.id)}
                            onRun={() => handleRun(agent.id)}
                            onDuplicate={() => handleDuplicate(agent.id)}
                        />
                    ))}
                </div>
            )}

            {!loading &&
                agents.length > 0 &&
                filteredAgents.length === 0 && (
                    <div className="aibp-empty-state">
                        <p>{__('No agents match your search.', 'ai-bulk-post')}</p>
                    </div>
                )}

            {showForm && (
                <AgentForm
                    agent={editingAgent}
                    onSave={handleSave}
                    onClose={() => {
                        setShowForm(false);
                        setEditingAgent(null);
                    }}
                />
            )}
        </div>
    );
}
