import React, { useState, useEffect, useMemo } from 'react';
import QuickActionButton from './QuickActionButton';
import useRenderTracker from '../../hooks/useRenderTracker';
import { IS_WORDPRESS, PLUGIN_ASSISTANT_SETTINGS } from '../../constants';

interface QuickActionsProps {
  onActionClick: (message: string) => void;
}

type QuickActionDisplay = {
  title: string;
  description: string;
};

type QuickActionDefinition = QuickActionDisplay & {
  requires?: 'logs' | 'writes';
};

const WEB_ACTIONS: QuickActionDisplay[] = [
  { title: 'Troubleshoot an issue', description: "I'm getting a 404 error on my homepage" },
  { title: 'Optimize performance', description: 'How can I speed up my WordPress site?' },
  { title: 'Customize theme', description: 'Help me add a custom footer to my theme' },
  { title: 'Plugin recommendations', description: "What's a good SEO plugin for WordPress?" },
  { title: 'Security tips', description: 'How can I improve my WordPress security?' },
  { title: 'Content creation', description: 'Give me ideas for my next blog post' },
  { title: 'Improve SEO', description: 'How can I optimize my website for SEO?' },
  { title: 'Set up a contact form', description: 'Help me set up a contact form in WordPress' },
  { title: 'Backup my site', description: "What's the best way to back up my WordPress site?" },
  { title: 'E-commerce setup', description: 'How do I set up WooCommerce for my shop?' },
  { title: 'Analytics tools', description: 'What tools can I use to track site analytics?' },
  { title: 'Update WordPress', description: 'How do I update WordPress and plugins safely?' },
  { title: 'Fix broken links', description: 'How can I find and fix broken links?' },
  { title: 'Improve mobile experience', description: 'How do I make my site mobile-friendly?' },
  { title: 'Add social sharing', description: 'Help me add social sharing buttons to my posts' },
  { title: 'Email marketing', description: 'What email marketing tools can I integrate?' },
  { title: 'Create a gallery', description: 'How can I create a photo gallery in WordPress?' },
  { title: 'Multilingual setup', description: 'How do I make my site multilingual?' },
  { title: 'Accessibility tips', description: "How can I improve my site's accessibility?" },
];

const PLUGIN_ACTIONS: QuickActionDefinition[] = [
  {
    title: 'Are my plugins current?',
    description: 'List outdated or duplicate plugins and why they matter right now.',
  },
  {
    title: 'Is anything broken today?',
    description: 'Scan Site Health and cron tasks for critical warnings to tackle first.',
  },
  {
    title: 'Why is the site slow?',
    description: 'Check plugin bloat, autoload size, and heavy scripts on the homepage.',
  },
  {
    title: 'Any errors in my logs?',
    description: 'If log sharing is on, summarize recent entries from the configured WordPress debug log file.',
    requires: 'logs',
  },
  {
    title: 'Is checkout ready?',
    description: 'Verify WooCommerce pages, payment gateways, and shipping zones are set.',
  },
  {
    title: 'What’s filling my cache?',
    description: 'Point out the noisiest transients or caches and safe cleanup ideas.',
  },
  {
    title: 'Do my links look right?',
    description: 'Review rewrite rules/permalinks and explain fixes for common 404s.',
  },
  {
    title: 'Which template renders this?',
    description: 'Tell me which template and parts render /sample-page/ and where they live.',
  },
  {
    title: 'Who just joined the site?',
    description: 'Summarize new admins or spikes in user roles without exposing PII.',
  },
  {
    title: 'Should I call Atiba?',
    description: 'Recap my blockers and suggest when to escalate to Atiba’s team.',
  },
];

const QuickActions: React.FC<QuickActionsProps> = ({ onActionClick }) => {
  const [actionCount, setActionCount] = useState(6);

  useRenderTracker('QuickActions', {
    onActionClick,
  });

  useEffect(() => {
    const updateActionCount = () => {
      if (window.matchMedia('(min-width: 1024px)').matches) {
        setActionCount(6);
      } else if (window.matchMedia('(min-width: 640px)').matches) {
        setActionCount(4);
      } else {
        setActionCount(3);
      }
    };

    updateActionCount();

    const mediaQueryList1 = window.matchMedia('(min-width: 1024px)');
    const mediaQueryList2 = window.matchMedia('(min-width: 640px)');
    mediaQueryList1.addEventListener('change', updateActionCount);
    mediaQueryList2.addEventListener('change', updateActionCount);

    return () => {
      mediaQueryList1.removeEventListener('change', updateActionCount);
      mediaQueryList2.removeEventListener('change', updateActionCount);
    };
  }, []);

  const getRandomActions = (arr: QuickActionDisplay[], count: number) => {
    const shuffled = [...arr].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
  };

  const allowLogReads = Boolean(PLUGIN_ASSISTANT_SETTINGS.allowLogReads);
  const allowWriteOperations = Boolean(PLUGIN_ASSISTANT_SETTINGS.allowWriteOperations);

  const displayedActions = useMemo<QuickActionDisplay[]>(() => {
    if (!IS_WORDPRESS) {
      return getRandomActions(WEB_ACTIONS, actionCount);
    }

    const available = PLUGIN_ACTIONS
      .filter((action) => {
        if (action.requires === 'logs') {
          return allowLogReads;
        }
        if (action.requires === 'writes') {
          return allowWriteOperations;
        }
        return true;
      });

    const summarized = available.map(({ title, description }) => ({ title, description }));

    if (summarized.length >= actionCount) {
      return summarized.slice(0, actionCount);
    }

    const fallback = getRandomActions(WEB_ACTIONS, actionCount - summarized.length);
    return [...summarized, ...fallback].slice(0, actionCount);
  }, [
    actionCount,
    allowLogReads,
    allowWriteOperations,
  ]);

  return (
    <section className="mb-4 sm:mb-8">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 sm:gap-4 gap-3">
        {displayedActions.map((action, index) => (
          <QuickActionButton
            key={index}
            title={action.title}
            description={action.description}
            onClick={() => onActionClick(action.description)}
          />
        ))}
      </div>
    </section>
  );
};

export default React.memo(QuickActions);
