import React, { useState, useEffect } from 'react';
import { toast } from 'react-toastify';

interface SavedPage {
  id: string;
  title: string;
  html: string;
  createdAt: number;
}

interface SavedPagesProps {
  currentHtml: string;
  onLoadPage: (html: string) => void;
}

const SavedPages: React.FC<SavedPagesProps> = ({ currentHtml, onLoadPage }) => {
  const [pages, setPages] = useState<SavedPage[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [newPageTitle, setNewPageTitle] = useState('');
  const [isAdding, setIsAdding] = useState(false);

  // Load saved pages from localStorage
  useEffect(() => {
    const savedPagesJson = localStorage.getItem('autosite_saved_pages');
    if (savedPagesJson) {
      try {
        const savedPages = JSON.parse(savedPagesJson);
        setPages(savedPages);
      } catch (error) {
        console.error('Error loading saved pages:', error);
      }
    }
  }, []);

  // Save pages to localStorage when they change
  useEffect(() => {
    localStorage.setItem('autosite_saved_pages', JSON.stringify(pages));
  }, [pages]);

  // Save current page
  const savePage = () => {
    if (!currentHtml) {
      toast.error('No content to save');
      return;
    }

    if (!newPageTitle.trim()) {
      toast.error('Please enter a title for your page');
      return;
    }

    // Create a new page
    const newPage: SavedPage = {
      id: `page_${Date.now()}`,
      title: newPageTitle,
      html: currentHtml,
      createdAt: Date.now()
    };

    setPages([newPage, ...pages]);
    setNewPageTitle('');
    setIsAdding(false);
    toast.success('Page saved successfully');
  };

  // Load a page
  const loadPage = (page: SavedPage) => {
    if (window.confirm('Are you sure you want to load this page? Your current work will be replaced.')) {
      onLoadPage(page.html);
      setIsOpen(false);
      toast.info(`Loaded page: ${page.title}`);
    }
  };

  // Delete a page
  const deletePage = (e: React.MouseEvent, pageId: string) => {
    e.stopPropagation();
    if (window.confirm('Are you sure you want to delete this page?')) {
      setPages(pages.filter(page => page.id !== pageId));
      toast.info('Page deleted');
    }
  };

  return (
    <div className="saved-pages-container">
      <button
        className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded text-sm"
        onClick={() => setIsOpen(!isOpen)}
      >
        {isOpen ? 'Close Saved Pages' : 'Saved Pages'}
      </button>

      {isOpen && (
        <div className="saved-pages-modal fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-gray-900 rounded-lg w-full max-w-2xl p-5 max-h-[80vh] overflow-y-auto">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl text-white font-bold">Saved Pages</h2>
              <button
                className="text-gray-400 hover:text-white"
                onClick={() => setIsOpen(false)}
              >
                ✕
              </button>
            </div>

            {/* Add new page form */}
            {isAdding ? (
              <div className="mb-6 bg-gray-800 p-4 rounded-lg">
                <input
                  type="text"
                  className="w-full bg-gray-700 border border-gray-600 text-white px-3 py-2 rounded mb-3"
                  placeholder="Page Title"
                  value={newPageTitle}
                  onChange={(e) => setNewPageTitle(e.target.value)}
                />
                <div className="flex space-x-2">
                  <button
                    className="px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white rounded"
                    onClick={savePage}
                  >
                    Save Page
                  </button>
                  <button
                    className="px-3 py-1.5 bg-gray-700 hover:bg-gray-600 text-white rounded"
                    onClick={() => {
                      setIsAdding(false);
                      setNewPageTitle('');
                    }}
                  >
                    Cancel
                  </button>
                </div>
              </div>
            ) : (
              <button
                className="px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white rounded mb-6"
                onClick={() => setIsAdding(true)}
              >
                Save Current Page
              </button>
            )}

            {/* List of saved pages */}
            {pages.length === 0 ? (
              <p className="text-gray-400 text-center py-4">No saved pages yet</p>
            ) : (
              <div className="space-y-3">
                {pages.map((page) => (
                  <div
                    key={page.id}
                    className="bg-gray-800 p-3 rounded cursor-pointer hover:bg-gray-700 flex justify-between items-center"
                    onClick={() => loadPage(page)}
                  >
                    <div>
                      <h3 className="text-white font-medium">{page.title}</h3>
                      <p className="text-gray-400 text-sm">
                        {new Date(page.createdAt).toLocaleString()}
                      </p>
                    </div>
                    <div className="flex space-x-2">
                      <button
                        className="text-red-500 hover:text-red-400"
                        onClick={(e) => deletePage(e, page.id)}
                      >
                        Delete
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default SavedPages;