/**
 * Site Information Tab Component
 *
 * Manages basic site information including name, tagline, separator, and images
 *
 * @package ProRank\SEO
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Input, Select } from '../../../../components/ui';

const SiteInfoTab = ({ settings, updateSettings, saveSettings }) => {
  const [isSaving, setIsSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);

  // Ensure WordPress media library is available and get site info
  useEffect(() => {
    // Get WordPress site name and tagline if not set
    if (!settings.site_name && window.prorankSeoAdmin?.site_name) {
      updateSettings({ site_name: window.prorankSeoAdmin.site_name });
    }
    if (!settings.site_tagline && window.prorankSeoAdmin?.site_tagline) {
      updateSettings({ site_tagline: window.prorankSeoAdmin.site_tagline });
    }
  }, []);

  // Title separators with their display and actual values
  const separatorOptions = [
    { label: '- (Dash)', value: '-' },
    { label: '– (En Dash)', value: '–' },
    { label: '— (Em Dash)', value: '—' },
    { label: ': (Colon)', value: ':' },
    { label: '· (Middle Dot)', value: '·' },
    { label: '• (Bullet)', value: '•' },
    { label: '* (Asterisk)', value: '*' },
    { label: '⋆ (Star)', value: '⋆' },
    { label: '| (Pipe)', value: '|' },
    { label: '~ (Tilde)', value: '~' },
    { label: '« (Left Guillemet)', value: '«' },
    { label: '» (Right Guillemet)', value: '»' },
    { label: '> (Greater Than)', value: '>' },
    { label: '< (Less Than)', value: '<' },
  ];

  const handleChange = (key, value) => {
    updateSettings({ [key]: value });
    setHasChanges(true);

    // Update WordPress site title and tagline if changed
    if (key === 'site_name') {
      updateWordPressSetting('blogname', value);
    } else if (key === 'site_tagline') {
      updateWordPressSetting('blogdescription', value);
    }
  };

  const updateWordPressSetting = async (option, value) => {
    try {
      await apiFetch({
        path: '/wp/v2/settings',
        method: 'POST',
        data: { [option]: value },
      });
    } catch (error) {
      // Failed to update WordPress setting
    }
  };

  const handleSave = async () => {
    setIsSaving(true);
    const success = await saveSettings(settings);
    if (success) {
      setHasChanges(false);
    }
    setIsSaving(false);
  };

  const openMediaLibrary = (key) => {
    if (!window.wp || !window.wp.media) {
      // Media library not available
      return;
    }

    const mediaUploader = window.wp.media({
      title: __('Select Image', 'prorank-seo'),
      button: {
        text: __('Use this image', 'prorank-seo')
      },
      multiple: false,
      library: {
        type: 'image'
      }
    });

    mediaUploader.on('select', () => {
      const attachment = mediaUploader.state().get('selection').first().toJSON();
      updateSettings({
        [key]: attachment.url,
        [`${key}_id`]: attachment.id
      });
      setHasChanges(true);
    });

    mediaUploader.open();
  };

  const handleRemoveImage = (key) => {
    updateSettings({
      [key]: '',
      [`${key}_id`]: ''
    });
    setHasChanges(true);
  };

  return (
    <div className="pr:space-y-6">
      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Website Information', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <Input
            label={__('Website Name', 'prorank-seo')}
            value={settings.site_name || ''}
            onChange={(value) => handleChange('site_name', value)}
            helperText={__('This is your site\'s name. It appears in search results and browser tabs.', 'prorank-seo')}
          />

          <Input
            label={__('Alternate Website Name', 'prorank-seo')}
            value={settings.site_alternate_name || ''}
            onChange={(value) => handleChange('site_alternate_name', value)}
            helperText={__('Use for acronyms or a shorter version of your website\'s name.', 'prorank-seo')}
          />

          <div className="pr:space-y-2">
            <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
              {__('Tagline', 'prorank-seo')}
            </label>
            <textarea
              className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
              value={settings.site_tagline || ''}
              onChange={(e) => handleChange('site_tagline', e.target.value)}
              rows={2}
            />
            <p className="pr:text-xs pr:text-gray-500">
              {__('This field updates the tagline in your WordPress settings. Use it as a brief description of your site.', 'prorank-seo')}
            </p>
          </div>

          <Select
            label={__('Title Separator', 'prorank-seo')}
            value={settings.title_separator || '-'}
            options={separatorOptions}
            onChange={(value) => handleChange('title_separator', value)}
            helperText={__('This separator is used between your page title and site name in search results.', 'prorank-seo')}
          />

          <div className="pr:p-4 pr:bg-gray-50 pr:border pr:border-gray-200 pr:rounded-md">
            <div className="pr:text-xs pr:text-gray-600 pr:mb-2">
              {__('Preview:', 'prorank-seo')}
            </div>
            <div className="pr:text-base pr:font-medium pr:transition-all pr:duration-300" style={{ color: '#1a0dab', fontFamily: 'arial, sans-serif' }}>
              {__('Page Title', 'prorank-seo')} {settings.title_separator || '-'} {settings.site_name || __('Your Site Name', 'prorank-seo')}
            </div>
            <div className="pr:text-sm pr:mt-1 pr:transition-all pr:duration-300" style={{ color: '#006621' }}>
              {window.location.hostname || 'yoursite.com'}
            </div>
          </div>
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Site Images', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-6">
          {/* Site Logo */}
          <div className="pr:space-y-3">
            <div className="pr:flex pr:items-start pr:gap-3">
              <div className="pr:shrink-0 pr:w-12 pr:h-12 pr:flex pr:items-center pr:justify-center pr:bg-primary-50 pr:rounded-lg">
                <svg className="pr:w-6 pr:h-6 pr:text-primary-500" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 2L2 7V17C2 17.55 2.45 18 3 18H9V12H15V18H21C21.55 18 22 17.55 22 17V7L12 2Z"/>
                </svg>
              </div>
              <div className="pr:flex-1">
                <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900">
                  {__('Site Logo', 'prorank-seo')}
                </h4>
                <p className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {__('Appears in search results and social shares', 'prorank-seo')}
                </p>
                <span className="pr:text-xs pr:text-gray-500">
                  {__('Recommended: Square image, min 512x512px', 'prorank-seo')}
                </span>
              </div>
            </div>

            <div className="pr:border pr:border-gray-200 pr:rounded-lg pr:overflow-hidden">
              {settings.site_logo ? (
                <div className="pr:relative pr:group">
                  <div className="pr:aspect-square pr:bg-gray-50 pr:flex pr:items-center pr:justify-center">
                    <img
                      src={settings.site_logo}
                      alt={__('Site Logo', 'prorank-seo')}
                      className="pr:max-w-full pr:max-h-full pr:object-contain"
                    />
                  </div>
                  <div className="pr:absolute pr:inset-0 pr:bg-black/50 pr:opacity-0 pr:group-hover:opacity-100 pr:transition-opacity pr:flex pr:items-center pr:justify-center pr:gap-2">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => openMediaLibrary('site_logo')}
                    >
                      {__('Change', 'prorank-seo')}
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => handleRemoveImage('site_logo')}
                    >
                      {__('Remove', 'prorank-seo')}
                    </Button>
                  </div>
                  <div className="pr:px-3 pr:py-2 pr:bg-gray-50 pr:border-t pr:border-gray-200">
                    <p className="pr:text-xs pr:text-gray-600 pr:truncate">
                      {settings.site_logo.split('/').pop()}
                    </p>
                  </div>
                </div>
              ) : (
                <button
                  className="pr:w-full pr:aspect-square pr:flex pr:flex-col pr:items-center pr:justify-center pr:gap-3 pr:bg-gray-50 pr:hover:bg-gray-100 pr:transition-colors pr:cursor-pointer"
                  onClick={() => openMediaLibrary('site_logo')}
                >
                  <svg className="pr:w-12 pr:h-12" viewBox="0 0 24 24" fill="none">
                    <rect x="3" y="3" width="18" height="18" rx="2" stroke="#3b82f6" strokeWidth="2" strokeDasharray="3 3"/>
                    <path d="M12 8v8M16 12H8" stroke="#3b82f6" strokeWidth="2" strokeLinecap="round"/>
                  </svg>
                  <div className="pr:text-center">
                    <span className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                      {__('Click to upload logo', 'prorank-seo')}
                    </span>
                    <span className="pr:block pr:text-xs pr:text-gray-500">
                      {__('or drag and drop', 'prorank-seo')}
                    </span>
                  </div>
                </button>
              )}
            </div>
          </div>

          {/* Default Site Image */}
          <div className="pr:space-y-3">
            <div className="pr:flex pr:items-start pr:gap-3">
              <div className="pr:shrink-0 pr:w-12 pr:h-12 pr:flex pr:items-center pr:justify-center pr:bg-purple-50 pr:rounded-lg">
                <svg className="pr:w-6 pr:h-6 pr:text-purple-500" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z"/>
                </svg>
              </div>
              <div className="pr:flex-1">
                <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900">
                  {__('Default Site Image', 'prorank-seo')}
                </h4>
                <p className="pr:text-xs pr:text-gray-600 pr:mt-1">
                  {__('Fallback for posts without featured images', 'prorank-seo')}
                </p>
                <span className="pr:text-xs pr:text-gray-500">
                  {__('Recommended: 1200x675px (16:9 ratio)', 'prorank-seo')}
                </span>
              </div>
            </div>

            <div className="pr:border pr:border-gray-200 pr:rounded-lg pr:overflow-hidden">
              {settings.site_image ? (
                <div className="pr:relative pr:group">
                  <div className="pr:aspect-video pr:bg-gray-50 pr:flex pr:items-center pr:justify-center">
                    <img
                      src={settings.site_image}
                      alt={__('Site Image', 'prorank-seo')}
                      className="pr:max-w-full pr:max-h-full pr:object-cover"
                    />
                  </div>
                  <div className="pr:absolute pr:inset-0 pr:bg-black/50 pr:opacity-0 pr:group-hover:opacity-100 pr:transition-opacity pr:flex pr:items-center pr:justify-center pr:gap-2">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => openMediaLibrary('site_image')}
                    >
                      {__('Change', 'prorank-seo')}
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => handleRemoveImage('site_image')}
                    >
                      {__('Remove', 'prorank-seo')}
                    </Button>
                  </div>
                  <div className="pr:px-3 pr:py-2 pr:bg-gray-50 pr:border-t pr:border-gray-200">
                    <p className="pr:text-xs pr:text-gray-600 pr:truncate">
                      {settings.site_image.split('/').pop()}
                    </p>
                  </div>
                </div>
              ) : (
                <button
                  className="pr:w-full pr:aspect-video pr:flex pr:flex-col pr:items-center pr:justify-center pr:gap-3 pr:bg-gray-50 pr:hover:bg-gray-100 pr:transition-colors pr:cursor-pointer"
                  onClick={() => openMediaLibrary('site_image')}
                >
                  <svg className="pr:w-12 pr:h-12" viewBox="0 0 24 24" fill="none">
                    <rect x="3" y="3" width="18" height="18" rx="2" stroke="#2563eb" strokeWidth="2" strokeDasharray="3 3"/>
                    <path d="M12 8v8M16 12H8" stroke="#2563eb" strokeWidth="2" strokeLinecap="round"/>
                  </svg>
                  <div className="pr:text-center">
                    <span className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                      {__('Click to upload image', 'prorank-seo')}
                    </span>
                    <span className="pr:block pr:text-xs pr:text-gray-500">
                      {__('or drag and drop', 'prorank-seo')}
                    </span>
                  </div>
                </button>
              )}
            </div>
          </div>
        </div>
      </Card>

      {hasChanges && (
        <Card>
          <div className="pr:flex pr:items-center pr:justify-end pr:gap-3">
            <Button
              variant="ghost"
              onClick={() => window.location.reload()}
              disabled={isSaving}
            >
              {__('Discard Changes', 'prorank-seo')}
            </Button>
            <Button
              variant="primary"
              onClick={handleSave}
              loading={isSaving}
              disabled={isSaving}
            >
              {isSaving ? __('Saving...', 'prorank-seo') : __('Save Changes', 'prorank-seo')}
            </Button>
          </div>
        </Card>
      )}
    </div>
  );
};

export default SiteInfoTab;
