import React, { useState, useEffect } from "react";
import axios from "axios";
import ReactPlayer from 'react-player';
import Form from "./Form";
import wpxpertise from '../../assets/icons/support/logo.png';
import supportagent from '../../assets/icons/support/supportagent.svg';
import Modal from '../Components/Modal/Modal';
import NoticeModal from '../Components/NoticeModal/NoticeModal';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import ChecklistRtlIcon from '@mui/icons-material/ChecklistRtl';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import SaveIcon from '@mui/icons-material/Save';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import PlayCircleFilledIcon from '@mui/icons-material/PlayCircleFilled';
import InfoIcon from '@mui/icons-material/Info';
import LaunchIcon from '@mui/icons-material/Launch';
import Tippy from '@tippy.js/react';
import { isPro, getNoticeData } from '../Helpers';
import 'tippy.js/dist/tippy.css';
import "./pluginlist.scss";

const PluginList = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [pluginslist, setPluginslist] = useState([]);
  const [copySuccess, setCopySuccess] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortOrder, setSortOrder] = useState('newest');

  const proData = isPro();
  const limit = 2; // Free limit
  const allConditionsMet = proData;

  const [modalConfig, setModalConfig] = useState({
    isOpen: false,
    type: 'confirmation',
    title: '',
    message: '',
    onConfirm: () => { },
    confirmText: 'Confirm',
    declineText: 'Cancel'
  });

  const closeModal = () => {
    setModalConfig(prev => ({ ...prev, isOpen: false }));
  };

  // Extract the last part of the URL as the site identifier
  const pathParts = window.location.pathname.split("/").filter(Boolean);
  const indexOfAdmin = pathParts.indexOf('wp-admin');
  const siteIdentifier = indexOfAdmin !== -1 ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() : pathParts.slice(-1).pop();
  const localStorageKey = `wpnts_pluginslist_${siteIdentifier}`;

  useEffect(() => {
    const wpnts_plugin_list_data = getNoticeData().wpnts_plugin_list;

    const wpnts_plugin_list = Array.isArray(wpnts_plugin_list_data)
      ? wpnts_plugin_list_data
      : [
        {
          id: 1707213500663,
          title: "add-plugin-name",
          content: "notifier-to-slack",
          dateAdded: new Date().toISOString(),
          status: 'active'
        },
      ];

    const saveForm = localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_plugin_list);

    try {
      const parsedForm = JSON.parse(saveForm);
      if (Array.isArray(parsedForm)) {
        setPluginslist(parsedForm);
      } else {
        console.error('Invalid data format in localStorage:', parsedForm);
        setPluginslist([]);
      }
    } catch (error) {
      console.error(error);
      setPluginslist([]);
    }
  }, [localStorageKey]);

  const addContact = () => {
    window.open('https://wpazleen.com/', '_blank');
  };

  const addSupport = () => {
    window.open('https://wordpress.org/support/plugin/notifier-to-slack/', '_blank');
  };

  const addPlugin = async () => {
    if (pluginslist.length >= limit && !allConditionsMet) {
      setModalConfig({
        isOpen: true,
        type: 'premium',
        title: '🚀 Upgrade to Premium',
        message: `You've reached the free limit of ${limit} plugins. Upgrade to add unlimited plugins and access premium features.`,
        onConfirm: () => {
          window.open('https://wpazleen.com/pricing/', '_blank');
          closeModal();
        },
        confirmText: 'Upgrade Now',
        declineText: 'Maybe Later'
      });
      return;
    }

    setIsLoading(true);

    const newPlugin = {
      id: Date.now(),
      title: `Plugin ${pluginslist.length + 1}`,
      content: `plugin-name-${pluginslist.length + 1}`,
      dateAdded: new Date().toISOString(),
      status: 'active'
    };

    const updatePluginslist = [...pluginslist, newPlugin];
    setPluginslist(updatePluginslist);
    localStorage.setItem(localStorageKey, JSON.stringify(updatePluginslist));

    try {
      const url = `${appLocalizer.wpntsUrl}/wpnts/v1/org_plugin_name`;
      await axios.post(url, {
        updatePluginslist
      }, {
        headers: {
          'content-type': 'application/json',
          'X-WP-NONCE': appLocalizer.nonce
        }
      });
    } catch (err) {
      console.error('Error adding plugin:', err);
    } finally {
      setIsLoading(false);
    }
  };

  const deletePlugin = (id) => {
    const filteredPluginlist = pluginslist.filter(
      (plugin) => plugin.id !== id
    );
    setPluginslist(filteredPluginlist);
    localStorage.setItem(localStorageKey, JSON.stringify(filteredPluginlist));
  };

  const handleContentChange = (id, newContent) => {
    const updatePluginslist = pluginslist.map((plist) => {
      if (plist.id === id) {
        return { ...plist, content: newContent };
      }
      return plist;
    });
    setPluginslist(updatePluginslist);
    localStorage.setItem(localStorageKey, JSON.stringify(updatePluginslist));
  };

  const handleSaveAll = async () => {
    setIsLoading(true);

    try {
      const url = `${appLocalizer.wpntsUrl}/wpnts/v1/org_plugin_name`;
      await axios.post(url, {
        updatePluginslist: pluginslist
      }, {
        headers: {
          'content-type': 'application/json',
          'X-WP-NONCE': appLocalizer.nonce
        }
      });

      setModalConfig({
        isOpen: true,
        type: 'toast',
        title: 'Success!',
        message: 'All plugin names updated successfully',
        position: 'top-right'
      });
      setTimeout(closeModal, 3000);
    } catch (err) {
      console.error('Error saving plugins:', err);
      setModalConfig({
        isOpen: true,
        type: 'toast',
        title: 'Error!',
        message: 'Failed to update plugin names',
        position: 'top-right'
      });
      setTimeout(closeModal, 3000);
    } finally {
      setIsLoading(false);
    }
  };

  const currentURL = window.location.href;
  const home = currentURL.substring(0, currentURL.indexOf("/wp-admin/"));
  const copied_json = home + '/wp-json/wpnts/v1/plugin_corn_run';

  const handleCopyClick = async () => {
    try {
      await navigator.clipboard.writeText(copied_json);
      setCopySuccess('Copied to clipboard!');
    } catch (err) {
      // Fallback for older browsers
      const textArea = document.createElement('textarea');
      textArea.value = copied_json;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
      setCopySuccess('Copied to clipboard!');
    }
  };

  useEffect(() => {
    if (copySuccess) {
      const timer = setTimeout(() => {
        setCopySuccess('');
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [copySuccess]);

  // Filter and sort plugins
  const filteredPlugins = pluginslist
    .filter(plugin =>
      plugin.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
      plugin.title.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      if (sortOrder === 'newest') {
        return new Date(b.dateAdded || 0) - new Date(a.dateAdded || 0);
      } else if (sortOrder === 'oldest') {
        return new Date(a.dateAdded || 0) - new Date(b.dateAdded || 0);
      } else if (sortOrder === 'alphabetical') {
        return a.content.localeCompare(b.content);
      }
      return 0;
    });

  return (
    <div className="plugin-list-container">
      {/* Header Section */}
      <div className="plugin-list-header">
        <div className="header-content">
          <div className="brand-section">
            <img
              className="brand-logo"
              src={wpxpertise}
              alt="WPXpertise"
              onClick={addContact}
              title="Visit WPXpertise"
            />
            <div className="support-icon">
              <Tippy content="Get Support">
                <img
                  className="support-logo"
                  src={supportagent}
                  alt="Support"
                  onClick={addSupport}
                />
              </Tippy>
            </div>
          </div>

          <div className="page-title">
            <ChecklistRtlIcon className="title-icon" />
            <h1>Plugin Management</h1>
            <span className="plugin-count">
              {pluginslist.length} {pluginslist.length === 1 ? 'plugin' : 'plugins'}
            </span>
          </div>

          <div className="header-actions">
            <div className="search-container">
              <input
                type="text"
                placeholder="Search plugins..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="search-input"
              />
            </div>

            <select
              value={sortOrder}
              onChange={(e) => setSortOrder(e.target.value)}
              className="sort-select"
            >
              <option value="newest">Newest First</option>
              <option value="oldest">Oldest First</option>
              <option value="alphabetical">A-Z</option>
            </select>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="plugin-list-main">
        {/* Left Panel - Plugin List */}
        <div className="plugins-panel">
          <div className="panel-header">
            <h2>Your Plugins</h2>
            <div className="panel-actions">
              <Tippy content="Add new plugin to monitor">
                <button
                  className="add-plugin-btn"
                  onClick={addPlugin}
                  disabled={isLoading}
                >
                  <AddCircleOutlineIcon />
                  Add Plugin
                  {!allConditionsMet && pluginslist.length >= limit && (
                    <span className="pro-badge">PRO</span>
                  )}
                </button>
              </Tippy>

              <Tippy content="Save all changes">
                <button
                  className="save-all-btn"
                  onClick={handleSaveAll}
                  disabled={isLoading || pluginslist.length === 0}
                >
                  <SaveIcon />
                  {isLoading ? 'Saving...' : 'Save All'}
                </button>
              </Tippy>
            </div>
          </div>

          <div className="plugins-list">
            {filteredPlugins.length === 0 ? (
              <div className="empty-state">
                <ChecklistRtlIcon className="empty-icon" />
                <h3>No plugins found</h3>
                <p>
                  {searchTerm
                    ? `No plugins match "${searchTerm}"`
                    : "Add your first plugin to start monitoring"
                  }
                </p>
                {!searchTerm && (
                  <button className="add-first-plugin" onClick={addPlugin}>
                    <AddCircleOutlineIcon />
                    Add Your First Plugin
                  </button>
                )}
              </div>
            ) : (
              filteredPlugins.map((plugin) => (
                <Form
                  key={plugin.id}
                  id={plugin.id}
                  title={plugin.title}
                  content={plugin.content}
                  dateAdded={plugin.dateAdded}
                  status={plugin.status}
                  onDelete={() => deletePlugin(plugin.id)}
                  onContentChange={handleContentChange}
                />
              ))
            )}
          </div>

          {/* Usage Stats */}
          <div className="usage-stats">
            <div className="stats-item">
              <span className="stats-label">Usage:</span>
              <span className="stats-value">
                {pluginslist.length} / {allConditionsMet ? '∞' : limit}
              </span>
            </div>
            {!allConditionsMet && (
              <div className="upgrade-hint">
                <InfoIcon className="info-icon" />
                <span>Upgrade to add unlimited plugins</span>
              </div>
            )}
          </div>
        </div>

        {/* Right Panel - Instructions & Video */}
        <div className="instructions-panel">
          <div className="cron-section">
            <h2>Cron Job Setup</h2>
            <p className="section-description">
              Set up automated monitoring even when your site has no traffic
            </p>

            <div className="cron-url-section">
              <label>API Endpoint:</label>
              <div className="url-container">
                <code className="cron-url">{copied_json}</code>
                <Tippy content={copySuccess || "Copy to clipboard"}>
                  <button
                    className="copy-btn"
                    onClick={handleCopyClick}
                  >
                    <ContentCopyIcon />
                  </button>
                </Tippy>
              </div>
              {copySuccess && (
                <div className="copy-success">
                  <span>✓ {copySuccess}</span>
                </div>
              )}
            </div>

            <div className="cron-instructions">
              <h3>Setup Instructions:</h3>
              <ol>
                <li>
                  <strong>Visit Cron Service:</strong>
                  <a
                    href="https://console.cron-job.org/jobs/create"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="external-link"
                  >
                    cron-job.org <LaunchIcon />
                  </a>
                </li>
                <li><strong>Create Job:</strong> Set a descriptive title</li>
                <li><strong>Add URL:</strong> Paste the copied API endpoint</li>
                <li><strong>Schedule:</strong> Set 5-25 minute intervals</li>
                <li><strong>Notifications:</strong> Disable failure notifications</li>
                <li><strong>Test & Create:</strong> Run a test before saving</li>
              </ol>
            </div>
          </div>

          <div className="video-section">
            <h3>
              <PlayCircleFilledIcon className="video-icon" />
              Video Tutorial
            </h3>
            <div className="video-wrapper">
              <ReactPlayer
                className="react-player"
                url="https://youtu.be/_UT_xdLRPPY"
                width="100%"
                height="100%"
                controls={true}
                light={true}
                config={{
                  youtube: {
                    playerVars: {
                      modestbranding: 1,
                      showinfo: 0,
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Modals */}
      {modalOpen && (
        <>
          <div className="popup-overlay"></div>
          <Modal setOpenModal={setModalOpen} />
        </>
      )}

      <NoticeModal
        isOpen={modalConfig.isOpen}
        onClose={closeModal}
        onConfirm={modalConfig.onConfirm}
        onDecline={closeModal}
        type={modalConfig.type}
        title={modalConfig.title}
        message={modalConfig.message}
        confirmText={modalConfig.confirmText}
        declineText={modalConfig.declineText}
        position={modalConfig.position || 'center'}
        autoClose={modalConfig.type === 'toast'}
        autoCloseTime={3000}
      />
    </div>
  );
};

export default PluginList;