/**
 * Dummy Content Remover component.
 */
import { useState, useEffect } from '@wordpress/element';
import { TrashIcon, ArrowPathIcon, ExclamationCircleIcon, DocumentTextIcon, CalendarIcon, EyeIcon, PencilIcon } from '@heroicons/react/24/outline';
import { format } from 'date-fns';

/**
 * Internal dependencies.
 */
import Layout from '../layout/Layout';
import { fetchDummyContent, fetchPostTypes, deletePosts } from '../../api/dummy-content-remover';
import { showPromiseToast, showSuccessToast, showErrorToast } from '../../utils';

const DummyContentRemover = () => {
    const [loading, setLoading] = useState(true);
    const [dummyContent, setDummyContent] = useState([]);
    const [postTypes, setPostTypes] = useState([]);
    const [selectedPostIds, setSelectedPostIds] = useState([]);
    const [isDeleting, setIsDeleting] = useState(false);
    const [error, setError] = useState(null);
    
    // Filter states
    const [selectedPostTypes, setSelectedPostTypes] = useState(['post', 'page']);
    const [maxWordCount, setMaxWordCount] = useState(50);
    const [checkTitles, setCheckTitles] = useState(true);
    const [checkContent, setCheckContent] = useState(true);
    const [checkLorem, setCheckLorem] = useState(true);
    const [dateBefore, setDateBefore] = useState('');
    const [includeTrash, setIncludeTrash] = useState(false);
    const [permanentDelete, setPermanentDelete] = useState(false);

    // Load post types
    const loadPostTypes = async () => {
        try {
            const postTypesData = await fetchPostTypes();
            setPostTypes(postTypesData);
        } catch (err) {
            console.error('Error loading post types:', err);
            setError('Failed to load post types. Please try again.');
        }
    };

    // Load dummy content
    const loadDummyContent = async () => {
        setLoading(true);
        setError(null);
        setSelectedPostIds([]);

        try {
            showPromiseToast(
                fetchDummyContent({
                    post_types: selectedPostTypes,
                    min_word_count: 0,
                    max_word_count: maxWordCount,
                    check_titles: checkTitles,
                    check_content: checkContent,
                    check_lorem: checkLorem,
                    date_before: dateBefore,
                    include_trashed: includeTrash
                }),
                'Scanning for dummy content...',
                'Content scan completed!',
                'Failed to scan content.'
            );

            const dummyContentData = await fetchDummyContent({
                post_types: selectedPostTypes,
                min_word_count: 0,
                max_word_count: maxWordCount,
                check_titles: checkTitles,
                check_content: checkContent,
                check_lorem: checkLorem,
                date_before: dateBefore,
                include_trashed: includeTrash
            });
            
            setDummyContent(dummyContentData);
        } catch (err) {
            console.error('Error loading dummy content:', err);
            setError('Failed to load dummy content. Please try again.');
        } finally {
            setLoading(false);
        }
    };

    // Initial data load
    useEffect(() => {
        loadPostTypes();
        loadDummyContent();
    }, []);

    // Toggle post selection
    const togglePostSelection = (postId) => {
        setSelectedPostIds(prevSelected => {
            if (prevSelected.includes(postId)) {
                return prevSelected.filter(id => id !== postId);
            } else {
                return [...prevSelected, postId];
            }
        });
    };

    // Select all posts
    const selectAllPosts = () => {
        if (selectedPostIds.length === dummyContent.length) {
            setSelectedPostIds([]);
        } else {
            setSelectedPostIds(dummyContent.map(post => post.ID));
        }
    };

    // Handle bulk delete
    const handleBulkDelete = async () => {
        if (selectedPostIds.length === 0) {
            showErrorToast('Please select at least one item to delete.');
            return;
        }

        const actionText = permanentDelete ? 'permanently delete' : 'move to trash';
        if (!window.confirm(`Are you sure you want to ${actionText} the selected content? ${permanentDelete ? 'This action cannot be undone.' : ''}`)) {
            return;
        }

        setIsDeleting(true);

        try {
            const result = await deletePosts(selectedPostIds, permanentDelete);

            // Show success message
            const totalDeleted = result.success.length;
            const totalFailed = result.failed.length;
            
            if (totalDeleted > 0) {
                showSuccessToast(`Successfully ${permanentDelete ? 'deleted' : 'trashed'} ${totalDeleted} item${totalDeleted !== 1 ? 's' : ''}.`);
            }
            
            if (totalFailed > 0) {
                showErrorToast(`Failed to delete ${totalFailed} item${totalFailed !== 1 ? 's' : ''}.`);
            }

            // Reset selections
            setSelectedPostIds([]);
            
            // Reload data
            loadDummyContent();
        } catch (err) {
            console.error('Error deleting items:', err);
            showErrorToast('Failed to delete selected items. Please try again.');
        } finally {
            setIsDeleting(false);
        }
    };

    // Format date
    const formatDate = (dateString) => {
        try {
            const date = new Date(dateString);
            return format(date, 'MMM d, yyyy');
        } catch (e) {
            return dateString;
        }
    };

    // Get post type label
    const getPostTypeLabel = (postType) => {
        const foundPostType = postTypes.find(pt => pt.name === postType);
        return foundPostType ? foundPostType.label : postType;
    };

    return (
        <Layout>
            <div>
            <div className="mb-6">
                <h2 className="text-xl font-bold text-gray-900">🗑️ Bulk Dummy Content Remover</h2>
                <p className="mt-1 text-gray-600">
                    Find and remove placeholder content like "Hello World" posts, sample pages, and lorem ipsum text.
                </p>
            </div>

            {error && (
                <div className="mb-6 bg-red-50 border-l-4 border-red-400 p-4">
                    <div className="flex">
                        <div className="flex-shrink-0">
                            <ExclamationCircleIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                        </div>
                        <div className="ml-3">
                            <p className="text-sm text-red-700">{error}</p>
                        </div>
                    </div>
                </div>
            )}

            {/* Filter Controls */}
            <div className="mb-6 bg-gray-50 p-4 rounded-md">
                <h3 className="text-sm font-medium text-gray-900 mb-3">Filter Options</h3>
                
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label htmlFor="post-types" className="block text-sm font-medium text-gray-700 mb-1">
                            Content Types
                        </label>
                        <div className="flex flex-wrap gap-2">
                            {postTypes.map(postType => (
                                <label key={postType.name} className="inline-flex items-center">
                                    <input
                                        type="checkbox"
                                        checked={selectedPostTypes.includes(postType.name)}
                                        onChange={() => {
                                            if (selectedPostTypes.includes(postType.name)) {
                                                setSelectedPostTypes(selectedPostTypes.filter(pt => pt !== postType.name));
                                            } else {
                                                setSelectedPostTypes([...selectedPostTypes, postType.name]);
                                            }
                                        }}
                                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                    />
                                    <span className="ml-1 mr-3 text-sm text-gray-700">{postType.label}</span>
                                </label>
                            ))}
                        </div>
                    </div>
                    
                    <div>
                        <label htmlFor="max-word-count" className="block text-sm font-medium text-gray-700 mb-1">
                            Max Word Count: {maxWordCount}
                        </label>
                        <input
                            type="range"
                            id="max-word-count"
                            min="10"
                            max="200"
                            step="10"
                            value={maxWordCount}
                            onChange={(e) => setMaxWordCount(parseInt(e.target.value))}
                            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                        />
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label htmlFor="date-before" className="block text-sm font-medium text-gray-700 mb-1">
                            Created Before (optional)
                        </label>
                        <input
                            type="date"
                            id="date-before"
                            value={dateBefore}
                            onChange={(e) => setDateBefore(e.target.value)}
                            className="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                        />
                    </div>
                    
                    <div className="flex flex-col justify-end">
                        <div className="flex items-center space-x-4">
                            <label className="inline-flex items-center">
                                <input
                                    type="checkbox"
                                    checked={checkTitles}
                                    onChange={() => setCheckTitles(!checkTitles)}
                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                />
                                <span className="ml-2 text-sm text-gray-700">Check Titles</span>
                            </label>
                            
                            <label className="inline-flex items-center">
                                <input
                                    type="checkbox"
                                    checked={checkContent}
                                    onChange={() => setCheckContent(!checkContent)}
                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                />
                                <span className="ml-2 text-sm text-gray-700">Check Word Count</span>
                            </label>
                            
                            <label className="inline-flex items-center">
                                <input
                                    type="checkbox"
                                    checked={checkLorem}
                                    onChange={() => setCheckLorem(!checkLorem)}
                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                />
                                <span className="ml-2 text-sm text-gray-700">Check Lorem Ipsum</span>
                            </label>
                        </div>
                    </div>
                </div>

                <div className="flex justify-between items-center">
                    <div className="flex items-center space-x-4">
                        <label className="inline-flex items-center">
                            <input
                                type="checkbox"
                                checked={includeTrash}
                                onChange={() => setIncludeTrash(!includeTrash)}
                                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                            />
                            <span className="ml-2 text-sm text-gray-700">Include Trashed Items</span>
                        </label>
                        
                        <label className="inline-flex items-center">
                            <input
                                type="checkbox"
                                checked={permanentDelete}
                                onChange={() => setPermanentDelete(!permanentDelete)}
                                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                            />
                            <span className="ml-2 text-sm text-gray-700">Permanently Delete</span>
                        </label>
                    </div>
                    
                    <button
                        onClick={loadDummyContent}
                        disabled={loading}
                        className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    >
                        <ArrowPathIcon className={`-ml-0.5 mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
                        Scan Content
                    </button>
                </div>
            </div>

            {/* Content List */}
            <div className="mb-4 flex justify-between items-center">
                <div className="flex items-center">
                    <input
                        id="select-all"
                        type="checkbox"
                        checked={selectedPostIds.length > 0 && selectedPostIds.length === dummyContent.length}
                        onChange={selectAllPosts}
                        className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                    <label htmlFor="select-all" className="ml-2 block text-sm text-gray-700">
                        {selectedPostIds.length === 0 ? 'Select All' : 
                         selectedPostIds.length === dummyContent.length ? 'Deselect All' : 
                         `Selected ${selectedPostIds.length} of ${dummyContent.length}`}
                    </label>
                </div>

                <div className="text-right">
                    <button
                        onClick={handleBulkDelete}
                        disabled={isDeleting || selectedPostIds.length === 0}
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <TrashIcon className="-ml-1 mr-2 h-5 w-5" />
                        {isDeleting ? 'Deleting...' : permanentDelete ? 'Delete Selected' : 'Trash Selected'}
                    </button>
                </div>
            </div>

            {loading ? (
                <div className="text-center py-12">
                    <div className="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
                    <p className="mt-2 text-gray-600">Scanning for dummy content...</p>
                </div>
            ) : (
                <div className="bg-white shadow overflow-hidden sm:rounded-md">
                    {dummyContent.length === 0 ? (
                        <div className="px-4 py-5 sm:p-6 text-center">
                            <DocumentTextIcon className="mx-auto h-12 w-12 text-green-500" />
                            <h3 className="mt-2 text-sm font-medium text-gray-900">No dummy content found</h3>
                            <p className="mt-1 text-sm text-gray-500">
                                Great job! We couldn't find any dummy or placeholder content based on your current filters.
                            </p>
                        </div>
                    ) : (
                        <ul className="divide-y divide-gray-200">
                            {dummyContent.map((post) => (
                                <li key={post.ID}>
                                    <div className="px-4 py-4 sm:px-6">
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center">
                                                <input
                                                    type="checkbox"
                                                    checked={selectedPostIds.includes(post.ID)}
                                                    onChange={() => togglePostSelection(post.ID)}
                                                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                                                />
                                                <div className="ml-3">
                                                    <h3 className="text-sm font-medium text-gray-900">{post.title}</h3>
                                                    <div className="mt-1 flex items-center text-xs text-gray-500 space-x-2">
                                                        <span className="inline-flex items-center">
                                                            <DocumentTextIcon className="h-3.5 w-3.5 mr-1" />
                                                            {getPostTypeLabel(post.post_type)}
                                                        </span>
                                                        <span className="inline-flex items-center">
                                                            <CalendarIcon className="h-3.5 w-3.5 mr-1" />
                                                            {formatDate(post.date)}
                                                        </span>
                                                        <span className="inline-flex items-center">
                                                            {post.word_count} words
                                                        </span>
                                                        {post.status === 'trash' && (
                                                            <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                                                Trashed
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="flex space-x-2">
                                                <a 
                                                    href={post.view_url} 
                                                    target="_blank" 
                                                    rel="noopener noreferrer"
                                                    className="inline-flex items-center p-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                                >
                                                    <EyeIcon className="h-4 w-4" />
                                                </a>
                                                <a 
                                                    href={post.edit_url} 
                                                    target="_blank" 
                                                    rel="noopener noreferrer"
                                                    className="inline-flex items-center p-1.5 border border-gray-300 shadow-sm text-xs font-medium rounded text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                                >
                                                    <PencilIcon className="h-4 w-4" />
                                                </a>
                                            </div>
                                        </div>
                                        <div className="mt-2 text-sm text-gray-500">{post.excerpt}</div>
                                        <div className="mt-2">
                                            {post.reasons.map((reason, index) => (
                                                <span 
                                                    key={index} 
                                                    className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 mr-2"
                                                >
                                                    {reason}
                                                </span>
                                            ))}
                                        </div>
                                    </div>
                                </li>
                            ))}
                        </ul>
                    )}
                </div>
            )}

            <div className="mt-6 bg-blue-50 p-4 rounded-md">
                <h3 className="text-sm font-medium text-blue-800">Why this matters:</h3>
                <ul className="mt-2 text-sm text-blue-700 list-disc pl-5 space-y-1">
                    <li>Dummy content like "Hello World" posts and sample pages can confuse visitors</li>
                    <li>Development content with lorem ipsum text should be removed before site launch</li>
                    <li>Clean content improves site professionalism and search engine indexing</li>
                    <li>Removing unnecessary content makes your site easier to manage</li>
                </ul>
            </div>
            </div>
        </Layout>
    );
};

export default DummyContentRemover;
