import React, { useState, useEffect } from 'react';
import Header from './Header';
import Empty from './Empty';
import DirectoryWizard from './directory/DirectoryWizard';
import DirectoryList from './directory/DirectoryList';
import DeleteConfirmModal from './directory/DeleteConfirmModal';

import { __ } from '@wordpress/i18n';

const App = () => {
    const [directories, setDirectories] = useState(null); // null = loading, [] = empty
    const [loading, setLoading] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const perPage = 10;
    const [showList, setShowList] = useState(false);
    const [deleteModal, setDeleteModal] = useState({ open: false, dir: null });
    const [deletingId, setDeletingId] = useState(null);
    const [editDirectory, setEditDirectory] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [pendingSearch, setPendingSearch] = useState('');
    const [currentView, setCurrentView] = useState('list'); // 'list' or 'form'
    const [currentTab, setCurrentTab] = useState('any'); // 'any', 'publish' or 'trash'
    const [selectedItems, setSelectedItems] = useState([]);
    const [selectAll, setSelectAll] = useState(false);
    const [bulkAction, setBulkAction] = useState('');
    const [statusCounts, setStatusCounts] = useState({ all: 0, publish: 0, trash: 0 });

    // Fetch status counts
    const fetchStatusCounts = async () => {
        try {
            const response = await fetch(`${window.wpuf_ud.rest_base}/status_counts`, {
                headers: {
                    'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                },
            });
            const data = await response.json();

            if (data?.success && data?.counts) {
                setStatusCounts({
                    all: data.counts.all || 0,
                    publish: data.counts.publish || 0,
                    trash: data.counts.trash || 0
                });
            }
        } catch (e) {
            console.error('Failed to fetch counts:', e);
        }
    };

    const fetchDirectories = async (page = 1, search = '', status = 'any') => {
        setLoading(true);
        try {
            // For 'any' status, we want to show all non-trashed items
            const apiStatus = status === 'any' ? 'publish' : status;
            const url = `${window.wpuf_ud.rest_base}?page=${page}&per_page=${perPage}&status=${apiStatus}` +
                       (search ? `&s=${encodeURIComponent(search)}` : '');
            const response = await fetch(url, {
                headers: {
                    'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                },
            });
            const data = await response.json();
            if (data && data.success && Array.isArray(data.result)) {
                setDirectories(data.result);
                if (data.pagination && data.pagination.total_pages) {
                    setTotalPages(data.pagination.total_pages);
                } else {
                    setTotalPages(1);
                }
            } else {
                setDirectories([]);
                setTotalPages(1);
            }
        } catch (e) {
            setDirectories([]);
            setTotalPages(1);
        }
        setLoading(false);
        setSelectedItems([]);
        setSelectAll(false);
    };

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

    useEffect(() => {
        fetchDirectories(currentPage, searchTerm, currentTab);
        // eslint-disable-next-line
    }, [currentPage, searchTerm, currentTab]);

    useEffect(() => {
        if (!loading && directories && directories.length > 0) {
            setShowList(false);
            // Trigger animation after render
            setTimeout(() => setShowList(true), 10);
        } else {
            setShowList(false);
        }
    }, [loading, directories]);

    const handlePageChange = (page) => {
        if (page < 1 || page > totalPages) return;
        setCurrentPage(page);
    };

    const handleRequestDelete = (dir) => {
        setDeleteModal({ open: true, dir });
    };

    const handleDelete = async () => {
        if (!deleteModal.dir) return;
        setDeletingId(deleteModal.dir.ID);
        try {
            // Determine the endpoint based on current tab
            const isTrash = currentTab === 'trash';
            const endpoint = isTrash
                ? `${window.wpuf_ud.rest_base}/${deleteModal.dir.ID}` // Permanent delete
                : `${window.wpuf_ud.rest_base}/${deleteModal.dir.ID}/trash`; // Move to trash
            const method = isTrash ? 'DELETE' : 'POST';

            const response = await fetch(endpoint, {
                method: method,
                headers: {
                    'X-WP-Nonce': window.wpuf_ud?.rest_nonce || '',
                },
            });
            if (!response.ok) {
                const text = await response.text();
                alert('Server error: ' + response.status);
                setDeletingId(null);
                setDeleteModal({ open: false, dir: null });
                return;
            }
            const result = await response.json();
            if (result && result.success) {
                fetchDirectories(currentPage, searchTerm, currentTab);
                fetchStatusCounts();
            } else {
                alert(result && result.message ? result.message : 'Failed to ' + (isTrash ? 'delete' : 'trash'));
            }
        } catch (e) {
            alert('Failed to ' + (currentTab === 'trash' ? 'delete' : 'trash'));
        }
        setDeletingId(null);
        setDeleteModal({ open: false, dir: null });
    };

    const handleSearchInput = (e) => {
        setPendingSearch(e.target.value);
    };

    useEffect(() => {
        const handler = setTimeout(() => {
            setCurrentPage(1);
            setSearchTerm(pendingSearch.trim());
        }, 500);
        return () => clearTimeout(handler);
        // eslint-disable-next-line
    }, [pendingSearch]);

    const handleTabChange = (tab) => {
        setCurrentTab(tab);
        setCurrentPage(1);
        setSelectedItems([]);
        setSelectAll(false);
    };

    const handleSelectAll = (checked) => {
        setSelectAll(checked);
        if (checked && directories) {
            setSelectedItems(directories.map(d => d.ID));
        } else {
            setSelectedItems([]);
        }
    };

    const handleSelectItem = (id, checked) => {
        if (checked) {
            setSelectedItems([...selectedItems, id]);
        } else {
            setSelectedItems(selectedItems.filter(item => item !== id));
            setSelectAll(false);
        }
    };

    const handleBulkAction = async () => {
        if (!bulkAction || selectedItems.length === 0) return;

        try {
            const promises = selectedItems.map(id => {
                if (bulkAction === 'trash') {
                    return fetch(`${window.wpuf_ud.rest_base}/${id}/trash`, {
                        method: 'POST',
                        headers: {
                            'X-WP-Nonce': window.wpuf_ud.rest_nonce,
                        },
                    });
                } else if (bulkAction === 'restore') {
                    return fetch(`${window.wpuf_ud.rest_base}/${id}/restore`, {
                        method: 'POST',
                        headers: {
                            'X-WP-Nonce': window.wpuf_ud.rest_nonce,
                        },
                    });
                } else if (bulkAction === 'delete') {
                    return fetch(`${window.wpuf_ud.rest_base}/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-WP-Nonce': window.wpuf_ud.rest_nonce,
                        },
                    });
                }
            });

            await Promise.all(promises);
            fetchDirectories(currentPage, searchTerm, currentTab);
            fetchStatusCounts();
            setSelectedItems([]);
            setSelectAll(false);
            setBulkAction('');
        } catch (e) {
            alert('Bulk action failed');
        }
    };

    return (
        <>
            {currentView === 'list' && <Header/>}
            {currentView === 'list' && (
                <div className="wpuf-w-[calc(100%+40px)] wpuf-ml-[-20px] wpuf-px-[20px] wpuf-my-10">
                <div className="wpuf-mb-8">
                    <div className="wpuf-flex wpuf-justify-between wpuf-items-center wpuf-mb-6">
                        <h1 className="wpuf-text-2xl wpuf-font-bold wpuf-m-0">{__('User Directories', 'wpuf-pro')}</h1>
                        <button
                            className="new-wpuf-form wpuf-rounded-md wpuf-text-center wpuf-bg-primary wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-semibold wpuf-text-white wpuf-shadow-sm hover:wpuf-bg-primaryHover hover:wpuf-text-white focus:wpuf-bg-primaryHover focus:wpuf-text-white focus:wpuf-shadow-none hover:wpuf-cursor-pointer"
                            onClick={() => { setCurrentView('form'); setEditDirectory(null); }}
                        >
                            <span className="dashicons dashicons-plus-alt2"></span>
                            &nbsp;
                            {__('Add New', 'wpuf-pro')}
                        </button>
                    </div>

                    {/* Tabs */}
                    <div className="wpuf-flex wpuf-mb-6">
                        <span
                            onClick={() => handleTabChange('any')}
                            className={`wpuf-flex hover:wpuf-border-primary hover:wpuf-text-primary wpuf-whitespace-nowrap wpuf-py-4 wpuf-px-1 wpuf-border-b-2 wpuf-font-medium wpuf-text-sm wpuf-mr-8 focus:wpuf-outline-none focus:wpuf-shadow-none wpuf-transition-all hover:wpuf-cursor-pointer ${
                                currentTab === 'any'
                                    ? 'wpuf-border-primary wpuf-text-primary'
                                    : 'wpuf-border-transparent wpuf-text-gray-500'
                            }`}
                        >
                            {__('All', 'wpuf-pro')}
                            <span className="wpuf-bg-gray-100 wpuf-text-gray-900 wpuf-ml-3 wpuf-rounded-full wpuf-py-0.5 wpuf-px-2.5 wpuf-text-xs wpuf-font-medium md:wpuf-inline-block">
                                {statusCounts.all}
                            </span>
                        </span>
                        <span
                            onClick={() => handleTabChange('publish')}
                            className={`wpuf-flex hover:wpuf-border-primary hover:wpuf-text-primary wpuf-whitespace-nowrap wpuf-py-4 wpuf-px-1 wpuf-border-b-2 wpuf-font-medium wpuf-text-sm wpuf-mr-8 focus:wpuf-outline-none focus:wpuf-shadow-none wpuf-transition-all hover:wpuf-cursor-pointer ${
                                currentTab === 'publish'
                                    ? 'wpuf-border-primary wpuf-text-primary'
                                    : 'wpuf-border-transparent wpuf-text-gray-500'
                            }`}
                        >
                            {__('Saved', 'wpuf-pro')}
                            <span className="wpuf-bg-gray-100 wpuf-text-gray-900 wpuf-ml-3 wpuf-rounded-full wpuf-py-0.5 wpuf-px-2.5 wpuf-text-xs wpuf-font-medium md:wpuf-inline-block">
                                {statusCounts.publish}
                            </span>
                        </span>
                        <span
                            onClick={() => handleTabChange('trash')}
                            className={`wpuf-flex hover:wpuf-border-primary hover:wpuf-text-primary wpuf-whitespace-nowrap wpuf-py-4 wpuf-px-1 wpuf-border-b-2 wpuf-font-medium wpuf-text-sm wpuf-mr-8 focus:wpuf-outline-none focus:wpuf-shadow-none wpuf-transition-all hover:wpuf-cursor-pointer ${
                                currentTab === 'trash'
                                    ? 'wpuf-border-primary wpuf-text-primary'
                                    : 'wpuf-border-transparent wpuf-text-gray-500'
                            }`}
                        >
                            {__('Trashed', 'wpuf-pro')}
                            <span className="wpuf-bg-gray-100 wpuf-text-gray-900 wpuf-ml-3 wpuf-rounded-full wpuf-py-0.5 wpuf-px-2.5 wpuf-text-xs wpuf-font-medium md:wpuf-inline-block">
                                {statusCounts.trash}
                            </span>
                        </span>
                    </div>

                    <div className="wpuf-flex wpuf-justify-between wpuf-items-center">
                        {/* Bulk Actions */}
                        <div className="wpuf-flex wpuf-items-center">
                            <select
                                value={bulkAction}
                                onChange={(e) => setBulkAction(e.target.value)}
                                className="wpuf-block wpuf-min-w-[180px] !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 wpuf-font-normal !wpuf-leading-none !wpuf-shadow-sm wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                            >
                                <option value="">{__('Bulk actions', 'wpuf-pro')}</option>
                                {(currentTab === 'any' || currentTab === 'publish') && (
                                    <option value="trash">{__('Move to trash', 'wpuf-pro')}</option>
                                )}
                                {currentTab === 'trash' && (
                                    <>
                                        <option value="restore">{__('Restore', 'wpuf-pro')}</option>
                                        <option value="delete">{__('Delete Permanently', 'wpuf-pro')}</option>
                                    </>
                                )}
                            </select>
                            <button
                                onClick={handleBulkAction}
                                disabled={!bulkAction || selectedItems.length === 0}
                                className={`wpuf-ml-4 wpuf-inline-flex wpuf-items-center wpuf-justify-center wpuf-rounded-md wpuf-border wpuf-border-transparent wpuf-bg-primary wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-semibold wpuf-text-white hover:wpuf-bg-primaryHover focus:wpuf-bg-primaryHover ${
                                    (!bulkAction || selectedItems.length === 0) ? 'wpuf-opacity-50 wpuf-cursor-not-allowed' : ''
                                }`}
                            >
                                {__('Apply', 'wpuf-pro')}
                            </button>
                        </div>

                        {/* Search */}
                        <div className="wpuf-form-search-box wpuf-w-[275px]">
                            <div className="wpuf-relative">
                                <input
                                    type="text"
                                    id="wpuf-directory-search"
                                    className="wpuf-block wpuf-min-w-full !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] wpuf-max-w-full focus:!wpuf-ring-transparent"
                                    placeholder={__('Search Directories', 'wpuf-pro')}
                                    value={pendingSearch}
                                    onChange={handleSearchInput}
                                    aria-label={__('Search', 'wpuf-pro')}
                                />
                                <span className="wpuf-absolute wpuf-top-0 wpuf-right-0 wpuf-p-[10px]">
                                    <svg className="wpuf-h-5 wpuf-w-5 wpuf-text-gray-400" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                                        <path fillRule="evenodd" d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z" clipRule="evenodd" />
                                    </svg>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                {loading && (
                    <div className="wpuf-flex wpuf-h-16 wpuf-items-center wpuf-justify-center">
                        <div className="wpuf-loader"></div>
                    </div>
                )}

                {!loading && directories && directories.length === 0 && searchTerm !== '' && (
                    <Empty
                        title={__('No directories found matching your search!', 'wpuf-pro')}
                        type="not-found"
                    />
                )}

                {!loading && directories && directories.length === 0 && searchTerm === '' && currentTab === 'any' && (
                    <Empty
                        title={__('No directories added yet', 'wpuf-pro')}
                        description={__('Create directories to organize users and manage access.', 'wpuf-pro')}
                        buttonText={__('Add New Directory', 'wpuf-pro')}
                        onButtonClick={() => { setCurrentView('form'); setEditDirectory(null); }}
                    />
                )}

                {!loading && directories && directories.length === 0 && searchTerm === '' && currentTab === 'publish' && (
                    <Empty
                        title={__('No Items Here!', 'wpuf-pro')}
                        type="not-found"
                    />
                )}

                {!loading && directories && directories.length === 0 && searchTerm === '' && currentTab === 'trash' && (
                    <Empty
                        title={__('No Items Here!', 'wpuf-pro')}
                        type="not-found"
                    />
                )}

                {!loading && directories && directories.length > 0 && (
                    <DirectoryList
                        directories={directories}
                        currentPage={currentPage}
                        totalPages={totalPages}
                        onPageChange={handlePageChange}
                        fetchDirectories={() => {
                            fetchDirectories(currentPage, searchTerm, currentTab);
                            fetchStatusCounts();
                        }}
                        className={showList ? 'wpuf-opacity-100' : 'wpuf-opacity-0'}
                        onRequestDelete={handleRequestDelete}
                        deletingId={deletingId}
                        onEdit={(dir) => { setCurrentView('form'); setEditDirectory(dir); }}
                        currentTab={currentTab}
                        selectedItems={selectedItems}
                        selectAll={selectAll}
                        onSelectAll={handleSelectAll}
                        onSelectItem={handleSelectItem}
                    />
                )}
                </div>
            )}

            {currentView === 'form' && (
                <DirectoryWizard
                    initialData={editDirectory}
                    onClose={() => {
                        setCurrentView('list');
                        setEditDirectory(null);
                        setCurrentTab('any'); // Reset to All tab
                        fetchDirectories(1, searchTerm, 'any'); // Fetch for All tab
                        fetchStatusCounts();
                    }}
                />
            )}

            <DeleteConfirmModal
                open={deleteModal.open}
                onClose={() => setDeleteModal({ open: false, dir: null })}
                onConfirm={handleDelete}
                title={currentTab === 'trash' ? __('Delete Directory Permanently', 'wpuf-pro') : __('Move to Trash', 'wpuf-pro')}
                message={deleteModal.dir ?
                    currentTab === 'trash'
                        ? `${__('Are you sure you want to permanently delete', 'wpuf-pro')} "${deleteModal.dir.post_title}"? ${__('This action cannot be undone.', 'wpuf-pro')}`
                        : `${__('Are you sure you want to move', 'wpuf-pro')} "${deleteModal.dir.post_title}" ${__('to trash?', 'wpuf-pro')}`
                    : ''
                }
            />
        </>
    );
};

export default App;