import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
  Card,
  CardHeader,
  CardBody,
  Input,
  Textarea,
  Button,
  Notice,
} from '../../../components/ui';

const CssExclusionEditor = ({ exclusions = '', onChange, onBack }) => {
  const [newExclusion, setNewExclusion] = useState('');
  const [showHelp, setShowHelp] = useState(false);
  const [mode, setMode] = useState('list'); // 'list' or 'raw'

  const exclusionList = exclusions
    .split('\n')
    .map((line) => line.trim())
    .filter((line) => line.length > 0);

  const handleAdd = () => {
    if (newExclusion.trim()) {
      const updated = exclusionList.concat(newExclusion.trim());
      onChange(updated.join('\n'));
      setNewExclusion('');
    }
  };

  const handleRemove = (index) => {
    const updated = exclusionList.filter((_, i) => i !== index);
    onChange(updated.join('\n'));
  };

  const handleRawChange = (value) => {
    onChange(value);
  };

  const commonExclusions = [
    { handle: 'admin-bar', description: __('WordPress admin bar styles', 'prorank-seo') },
    { handle: 'dashicons', description: __('WordPress dashboard icons', 'prorank-seo') },
    { handle: 'wp-block-library', description: __('Gutenberg block styles', 'prorank-seo') },
    { handle: 'elementor-frontend', description: __('Elementor page builder', 'prorank-seo') },
    { handle: 'google-fonts', description: __('Google Fonts stylesheets', 'prorank-seo') },
    { handle: 'font-awesome', description: __('Font Awesome icons', 'prorank-seo') },
  ];

  return (
    <div className="css-exclusion-editor">
      <div className="pr:mb-5">
        <Button variant="link" onClick={onBack}>
          ← {__('Back to Settings', 'prorank-seo')}
        </Button>
      </div>

      <h3>{__('CSS Exclusion Editor', 'prorank-seo')}</h3>

      {/* Mode Toggle */}
      <div className="pr:mb-5">
        <Button
          variant={mode === 'list' ? 'primary' : 'secondary'}
          onClick={() => setMode('list')}
          className="pr:mr-2.5 pr:transition-all pr:duration-300"
        >
          {__('List View', 'prorank-seo')}
        </Button>
        <Button
          variant={mode === 'raw' ? 'primary' : 'secondary'}
          onClick={() => setMode('raw')}
          className="pr:transition-all pr:duration-300"
        >
          {__('Raw Edit', 'prorank-seo')}
        </Button>
        <Button
          variant="link"
          onClick={() => setShowHelp(!showHelp)}
          className="pr:ml-2.5 pr:transition-all pr:duration-300"
        >
          {showHelp ? __('Hide Help', 'prorank-seo') : __('Show Help', 'prorank-seo')}
        </Button>
      </div>

      {/* Help Section */}
      {showHelp && (
        <Notice status="info" isDismissible={false} className="pr:mb-5">
          <strong>{__('How to exclude CSS files:', 'prorank-seo')}</strong>
          <ul className="pr:mt-2.5 pr:mb-0">
            <li>{__("Use the stylesheet handle (e.g., 'my-theme-style')", 'prorank-seo')}</li>
            <li>{__("Use part of the file URL (e.g., 'theme-name/style.css')", 'prorank-seo')}</li>
            <li>{__('One exclusion per line in raw edit mode', 'prorank-seo')}</li>
          </ul>
        </Notice>
      )}

      {mode === 'list' ? (
        <>
          {/* Add New Exclusion */}
          <Card className="pr:mb-5">
            <CardHeader>
              <h3>{__('Add Exclusion', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <div className="pr:flex pr:gap-2.5">
                <div className="pr:flex-1">
                  <Input
                    placeholder={__('Enter CSS handle or URL pattern to exclude', 'prorank-seo')}
                    value={newExclusion}
                    onChange={(e) => setNewExclusion(e.target.value)}
                    onKeyPress={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        handleAdd();
                      }
                    }}
                  />
                </div>
                <Button variant="primary" onClick={handleAdd} disabled={!newExclusion.trim()}>
                  {__('Add', 'prorank-seo')}
                </Button>
              </div>
            </CardBody>
          </Card>

          {/* Current Exclusions */}
          <Card className="pr:mb-5">
            <CardHeader>
              <h3>{__('Current Exclusions', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              {exclusionList.length > 0 ? (
                <ul className="css-exclusion-list">
                  {exclusionList.map((exclusion, index) => {
                    const commonExclusion = commonExclusions.find((e) => e.handle === exclusion);
                    return (
                      <li key={index} className="css-exclusion-item">
                        <div className="css-exclusion-info">
                          <strong className="css-exclusion-handle">{exclusion}</strong>
                          {commonExclusion && (
                            <span className="css-exclusion-description">
                              {commonExclusion.description}
                            </span>
                          )}
                        </div>
                        <Button variant="link" isDestructive onClick={() => handleRemove(index)}>
                          {__('Remove', 'prorank-seo')}
                        </Button>
                      </li>
                    );
                  })}
                </ul>
              ) : (
                <Notice status="info" isDismissible={false}>
                  {__('No exclusions configured. All CSS files will be optimized.', 'prorank-seo')}
                </Notice>
              )}
            </CardBody>
          </Card>

          {/* Common Exclusions */}
          <Card>
            <CardHeader>
              <h3>{__('Common Exclusions', 'prorank-seo')}</h3>
            </CardHeader>
            <CardBody>
              <p>{__('Click to add commonly excluded stylesheets:', 'prorank-seo')}</p>
              <div className="css-common-exclusions pr:mt-2.5">
                {commonExclusions
                  .filter((e) => !exclusionList.includes(e.handle))
                  .map((exclusion) => (
                    <Button
                      key={exclusion.handle}
                      variant="secondary"
                      onClick={() => {
                        const updated = exclusionList.concat(exclusion.handle);
                        onChange(updated.join('\n'));
                      }}
                      className="css-common-exclusion-chip"
                    >
                      + {exclusion.handle}
                    </Button>
                  ))}
              </div>
            </CardBody>
          </Card>
        </>
      ) : (
        /* Raw Edit Mode */
        <Card>
          <CardHeader>
            <h3>{__('Raw Exclusion List', 'prorank-seo')}</h3>
          </CardHeader>
          <CardBody>
            <Textarea
              value={exclusions}
              onChange={(e) => handleRawChange(e.target.value)}
              placeholder={__(
                'Enter one exclusion per line\n\nExamples:\nadmin-bar\ntheme-name/style.css\ngoogle-fonts',
                'prorank-seo'
              )}
              rows={15}
              className="pr:font-mono pr:transition-all pr:duration-300"
            />
          </CardBody>
        </Card>
      )}
    </div>
  );
};

export default CssExclusionEditor;
