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 fetchDirectories = async (page = 1, search = '') => {
        setLoading(true);
        try {
            const url = `/wp-json/wpuf/v1/user_directory?page=${page}&per_page=${perPage}` + (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);
    };

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

    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 {
            const response = await fetch(`/wp-json/wpuf/v1/user_directory/${deleteModal.dir.ID}`, {
                method: 'DELETE',
                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);
            } else {
                alert(result && result.message ? result.message : 'Failed to delete');
            }
        } catch (e) {
            alert('Failed to delete');
        }
        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]);

    return (
        <>
            {currentView === 'list' && <Header/>}
            {currentView === 'list' && (
                <div className="wpuf-mx-2 wpuf-my-10">
                <div className="wpuf-mb-8">
                    <h1 className="wpuf-text-2xl wpuf-font-bold wpuf-m-0 wpuf-mb-6">{__('User Directories', 'wpuf-pro')}</h1>
                    
                    <div className="wpuf-flex wpuf-justify-between wpuf-items-center">
                        <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>
                        
                        <button
                            className="wpuf-btn-primary wpuf-flex"
                            onClick={() => { setCurrentView('form'); setEditDirectory(null); }}
                        >
                            <span className="dashicons dashicons-plus-alt2"></span>
                            &nbsp;
                            {__('New Directory', 'wpuf-pro')}
                        </button>
                    </div>
                </div>

                {loading ? null : (directories && directories.length === 0 ? (
                    searchTerm ? (
                        <div className="wpuf-bg-white wpuf-border wpuf-border-gray-200 wpuf-shadow wpuf-rounded-[8px] wpuf-p-8 wpuf-text-center wpuf-text-gray-500 wpuf-text-base">
                            {__('No directories found', 'wpuf-pro')}
                        </div>
                    ) : (
                        <Empty onCreateNew={() => { setCurrentView('form'); setEditDirectory(null); }} />
                    )
                ) : (
                    <div
                        className={`wpuf-animate-fadein transition-all duration-700 ${showList ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-4'}`}
                        style={{ willChange: 'opacity, transform' }}
                        aria-live="polite"
                    >
                        <DirectoryList
                            className="wpuf-animate-fadein"
                            directories={directories}
                            currentPage={currentPage}
                            totalPages={totalPages}
                            onPageChange={handlePageChange}
                            fetchDirectories={fetchDirectories}
                            onRequestDelete={handleRequestDelete}
                            deletingId={deletingId}
                            onEdit={dir => { setEditDirectory(dir); setCurrentView('form'); }}
                        />
                    </div>
                ))}
                </div>
            )}
            {currentView === 'form' && (
                <DirectoryWizard 
                    onClose={() => { 
                        setCurrentView('list'); 
                        setEditDirectory(null); 
                        fetchDirectories(currentPage); 
                    }} 
                    initialData={editDirectory} 
                />
            )}
            <DeleteConfirmModal
                isOpen={deleteModal.open}
                onCancel={() => setDeleteModal({ open: false, dir: null })}
                onConfirm={handleDelete}
            />
        </>
    );
};

export default App;
