/**
 * Module Manager Tab Component
 *
 * @package
 * @since   0.1.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Toggle, Alert } from '../../components/ui';
import {
  ShieldCheckIcon,
  PencilIcon,
  UserGroupIcon,
  RocketLaunchIcon,
  StarIcon as StarFilledIcon,
} from '@heroicons/react/24/solid';
import { StarIcon as StarOutlineIcon } from '@heroicons/react/24/outline';
import { useNotification } from '../../contexts/NotificationContext';
import { useUserPreferences } from '../../hooks/useUserPreferences';
import LoadingState from '../../components/LoadingState';

// Icon mapping for module groups
const moduleIcons = {
  'on-page-seo': PencilIcon,
  'technical-seo': ShieldCheckIcon,
  performance: RocketLaunchIcon,
  support: UserGroupIcon,
};

const ModuleManagerTab = () => {
  const [moduleGroups, setModuleGroups] = useState([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState({});
  const [error, setError] = useState(null);
  const [updatingPin, setUpdatingPin] = useState({});

  const { showNotification } = useNotification();
  const { pinnedModules, togglePinnedModule } = useUserPreferences();

  // Fetch module groups
  useEffect(() => {
    fetchModuleGroups();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchModuleGroups = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/modules/groups',
      });

      const allowedGroups = ['on-page-seo', 'technical-seo', 'performance', 'support'];
      const safeGroups = (response.groups || []).filter(
        (group) => group?.tier === 'free' && allowedGroups.includes(group.slug)
      );
      setModuleGroups(safeGroups);
    } catch (err) {
      setError(err.message || __('Failed to load module groups', 'prorank-seo'));
    } finally {
      setLoading(false);
    }
  };

  const handleToggleModule = async (groupSlug, newState) => {
    const group = moduleGroups.find((g) => g.slug === groupSlug);

    setSaving({ ...saving, [groupSlug]: true });

    try {
      await apiFetch({
        path: `/prorank-seo/v1/modules/groups/${groupSlug}/status`,
        method: 'POST',
        data: { enabled: newState },
      });

      setModuleGroups((groups) =>
        groups.map((g) => (g.slug === groupSlug ? { ...g, enabled: newState } : g))
      );

      showNotification(
        sprintf(
          __('Module group "%1$s" has been %2$s', 'prorank-seo'),
          group.name,
          newState ? __('enabled', 'prorank-seo') : __('disabled', 'prorank-seo')
        ),
        'success'
      );
    } catch (err) {
      showNotification(err.message || __('Failed to update module status', 'prorank-seo'), 'error');
    } finally {
      setSaving({ ...saving, [groupSlug]: false });
    }
  };

  const getModulePageUrl = (slug) => {
    if (slug === 'support') {
      return 'admin.php?page=prorank-support';
    }
    return `admin.php?page=prorank-${slug}`;
  };

  const handleTogglePin = async (moduleSlug) => {
    setUpdatingPin({ ...updatingPin, [moduleSlug]: true });

    try {
      const result = await togglePinnedModule(moduleSlug);

      showNotification(
        result.is_pinned
          ? __('Module pinned to top', 'prorank-seo')
          : __('Module unpinned', 'prorank-seo'),
        'success'
      );
    } catch (err) {
      showNotification(__('Failed to update pinned status', 'prorank-seo'), 'error');
    } finally {
      setUpdatingPin({ ...updatingPin, [moduleSlug]: false });
    }
  };

  const renderModuleCard = (group) => {
    const isEnabled = Boolean(group.enabled);
    const isSaving = saving[group.slug];
    const isPinned = pinnedModules.includes(group.slug);
    const isPinning = updatingPin[group.slug];
    const IconComponent = moduleIcons[group.slug] || ShieldCheckIcon;

    return (
      <Card
        key={group.slug}
        className="pr:relative"
        variant="elevated"
      >
        <div className="pr:flex pr:items-start pr:gap-4 pr:mb-4">
          <div className={`pr:p-3 pr:rounded-lg ${isEnabled ? 'pr:bg-primary-100' : 'pr:bg-gray-100'}`}>
            <IconComponent className={`pr:w-6 pr:h-6 ${isEnabled ? 'pr:text-primary-600' : 'pr:text-gray-600'}`} />
          </div>
          <div className="pr:flex-1">
            <div className="pr:flex pr:items-center pr:gap-2 pr:mb-1">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{group.name}</h3>
            </div>
            <p className="pr:text-sm pr:text-gray-600">{group.description}</p>
          </div>
          <button
            onClick={() => handleTogglePin(group.slug)}
            disabled={isPinning}
            className="pr:p-2 pr:rounded-md pr:hover:bg-gray-100 pr:transition-colors pr:disabled:opacity-50"
            aria-label={isPinned ? __('Unpin module', 'prorank-seo') : __('Pin module', 'prorank-seo')}
          >
            {isPinned ? (
              <StarFilledIcon className="pr:w-5 pr:h-5 pr:text-warning-500" />
            ) : (
              <StarOutlineIcon className="pr:w-5 pr:h-5 pr:text-gray-400" />
            )}
          </button>
        </div>

        <div className="pr:flex pr:items-center pr:justify-between pr:pt-4 pr:border-t pr:border-gray-200">
          <Toggle
            checked={isEnabled}
            onChange={(value) => handleToggleModule(group.slug, value)}
            disabled={isSaving}
            label={isEnabled ? __('Enabled', 'prorank-seo') : __('Disabled', 'prorank-seo')}
          />

          <Button
            variant="primary"
            size="sm"
            onClick={() => window.location.href = getModulePageUrl(group.slug)}
            disabled={isSaving || !isEnabled}
          >
            {__('Configure', 'prorank-seo')}
          </Button>
        </div>

        {isSaving && (
          <div className="pr:absolute pr:inset-0 pr:bg-white/75 pr:flex pr:items-center pr:justify-center pr:rounded-lg">
            <LoadingState message={__('Updating…', 'prorank-seo')} />
          </div>
        )}
      </Card>
    );
  };

  if (loading) {
    return <LoadingState message={__('Loading modules…', 'prorank-seo')} />;
  }

  if (error) {
    return (
      <Alert variant="error" title={__('Error', 'prorank-seo')}>
        {error}
      </Alert>
    );
  }

  return (
    <div className="pr:space-y-6">
      <div className="pr:mb-8">
        <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Module Manager', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__(
            'Enable or disable ProRank SEO feature groups. Disabled groups stop loading their runtime features, though saved settings and admin assets may still exist.',
            'prorank-seo'
          )}
        </p>
      </div>

      {pinnedModules.length > 0 && (
        <>
          <div className="pr:flex pr:items-center pr:gap-2 pr:mb-4">
            <StarFilledIcon className="pr:w-5 pr:h-5 pr:text-warning-500" />
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Pinned Modules', 'prorank-seo')}
            </h3>
          </div>
          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:lg:grid-cols-3 pr:gap-6 pr:mb-8">
            {moduleGroups
              .filter((group) => pinnedModules.includes(group.slug))
              .map((group) => renderModuleCard(group))}
          </div>

          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-4">
            {__('All Modules', 'prorank-seo')}
          </h3>
        </>
      )}

      <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:lg:grid-cols-3 pr:gap-6">
        {moduleGroups
          .filter((group) => !pinnedModules.includes(group.slug))
          .map((group) => renderModuleCard(group))}
      </div>
    </div>
  );
};

export default ModuleManagerTab;
