/**
 * Social Profiles Tab Component
 *
 * Manages social media profiles and integration settings
 *
 * @package ProRank\SEO
 */

import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { PlusIcon, XMarkIcon, InformationCircleIcon } from '@heroicons/react/24/outline';
import { Card, Button, Input } from '../../../../components/ui';

const SocialProfilesTab = ({ settings, updateSettings, saveSettings }) => {
  const [isSaving, setIsSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [newProfile, setNewProfile] = useState({ platform: '', url: '' });

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

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

  const addAdditionalProfile = () => {
    if (newProfile.platform && newProfile.url) {
      const currentProfiles = settings.additional_profiles || [];
      const updated = [...currentProfiles, { ...newProfile }];
      handleChange('additional_profiles', updated);
      setNewProfile({ platform: '', url: '' });
    }
  };

  const removeAdditionalProfile = (index) => {
    const currentProfiles = settings.additional_profiles || [];
    const updated = currentProfiles.filter((_, i) => i !== index);
    handleChange('additional_profiles', updated);
  };

  const formatUsername = (value, removePlatformUrl = '') => {
    // Remove common platform URLs if pasted
    if (removePlatformUrl && value.includes(removePlatformUrl)) {
      const parts = value.split(removePlatformUrl);
      return parts[parts.length - 1].replace(/[\/\?#].*$/, '');
    }
    // Remove @ symbol if present
    return value.replace('@', '');
  };

  return (
    <div className="pr:space-y-6">
      <div className="pr:flex pr:items-start pr:gap-3 pr:p-4 pr:bg-info-50 pr:border pr:border-info-200 pr:rounded-lg">
        <InformationCircleIcon className="pr:w-5 pr:h-5 pr:text-info-500 pr:shrink-0 pr:mt-0.5" />
        <p className="pr:text-sm pr:text-info-700">
          {__('Social profiles help search engines understand your brand presence across platforms. They are used in structured data and can appear in knowledge panels.', 'prorank-seo')}
        </p>
      </div>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Facebook Settings', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <Input
            label={__('Facebook Page URL', 'prorank-seo')}
            type="url"
            value={settings.facebook_page_url || ''}
            onChange={(value) => handleChange('facebook_page_url', value)}
            placeholder="https://www.facebook.com/YourPage"
            helperText={__('Enter your complete Facebook page URL', 'prorank-seo')}
          />

          <Input
            label={__('Facebook Authorship', 'prorank-seo')}
            type="url"
            value={settings.facebook_authorship || ''}
            onChange={(value) => handleChange('facebook_authorship', value)}
            placeholder="https://www.facebook.com/yourprofile"
            helperText={__('Personal Facebook profile URL to show authorship when articles are shared', 'prorank-seo')}
          />

          <Input
            label={__('Facebook Admin ID', 'prorank-seo')}
            value={settings.facebook_admin_id || ''}
            onChange={(value) => handleChange('facebook_admin_id', value)}
            placeholder="123456789,987654321"
            helperText={__('Enter numeric user ID(s). Use commas to separate multiple IDs.', 'prorank-seo')}
          />

          <Input
            label={__('Facebook App ID', 'prorank-seo')}
            value={settings.facebook_app_id || ''}
            onChange={(value) => handleChange('facebook_app_id', value)}
            placeholder="1234567890123456"
            helperText={__('Enter numeric app ID. You can use either Admin ID or App ID.', 'prorank-seo')}
          />

          <Input
            label={__('Facebook Secret', 'prorank-seo')}
            type="password"
            value={settings.facebook_secret || ''}
            onChange={(value) => handleChange('facebook_secret', value)}
            placeholder="abc123def456ghi789"
            helperText={
              <>
                {__('Enter alphanumeric secret ID. ', 'prorank-seo')}
                <a
                  href="https://developers.facebook.com/docs/sharing/webmasters/getting-started"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="pr:text-primary-500 pr:hover:text-primary-600"
                >
                  {__('Learn more', 'prorank-seo')}
                </a>
              </>
            }
          />
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Twitter/X Settings', 'prorank-seo')}
          </h3>
        }
      >
        <Input
          label={__('Twitter/X Username', 'prorank-seo')}
          value={settings.twitter_username || ''}
          onChange={(value) => {
            const formatted = formatUsername(value, 'twitter.com/');
            handleChange('twitter_username', formatted);
          }}
          placeholder="YourUsername"
          helperText={__('Enter username without @ symbol. Used for twitter:creator tag.', 'prorank-seo')}
        />
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Primary Social Profiles', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <Input
            label={__('LinkedIn URL', 'prorank-seo')}
            type="url"
            value={settings.linkedin_url || ''}
            onChange={(value) => handleChange('linkedin_url', value)}
            placeholder="https://www.linkedin.com/company/yourcompany"
          />

          <Input
            label={__('Instagram URL', 'prorank-seo')}
            type="url"
            value={settings.instagram_url || ''}
            onChange={(value) => handleChange('instagram_url', value)}
            placeholder="https://www.instagram.com/yourprofile"
          />

          <Input
            label={__('YouTube URL', 'prorank-seo')}
            type="url"
            value={settings.youtube_url || ''}
            onChange={(value) => handleChange('youtube_url', value)}
            placeholder="https://www.youtube.com/c/yourchannel"
          />

          <Input
            label={__('Pinterest URL', 'prorank-seo')}
            type="url"
            value={settings.pinterest_url || ''}
            onChange={(value) => handleChange('pinterest_url', value)}
            placeholder="https://www.pinterest.com/yourprofile"
          />

          <Input
            label={__('TikTok URL', 'prorank-seo')}
            type="url"
            value={settings.tiktok_url || ''}
            onChange={(value) => handleChange('tiktok_url', value)}
            placeholder="https://www.tiktok.com/@yourprofile"
            helperText={__('Your TikTok profile URL. Critical for 2025 social media presence (1.7B users).', 'prorank-seo')}
          />

          <Input
            label={__('Threads URL', 'prorank-seo')}
            type="url"
            value={settings.threads_url || ''}
            onChange={(value) => handleChange('threads_url', value)}
            placeholder="https://www.threads.net/@yourprofile"
            helperText={__('Your Threads profile URL. Meta\'s Twitter/X alternative with 100M+ users.', 'prorank-seo')}
          />

          <Input
            label={__('Mastodon Profile', 'prorank-seo')}
            value={settings.mastodon_url || ''}
            onChange={(value) => handleChange('mastodon_url', value)}
            placeholder="@username@mastodon.social or https://mastodon.social/@username"
            helperText={__('Your Mastodon profile (@username@instance.social format or full URL).', 'prorank-seo')}
          />
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Additional Profiles', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <p className="pr:text-sm pr:text-gray-600">
            {__('Add any other social profiles to include in the sameAs Schema property. This helps search engines understand all your official social media presence.', 'prorank-seo')}
          </p>

          {settings.additional_profiles && settings.additional_profiles.length > 0 && (
            <div className="pr:space-y-2">
              {settings.additional_profiles.map((profile, index) => (
                <div
                  key={index}
                  className="pr:flex pr:items-center pr:justify-between pr:gap-4 pr:p-3 pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200"
                >
                  <div className="pr:flex-1">
                    <div className="pr:text-sm pr:font-semibold pr:text-gray-900">
                      {profile.platform}
                    </div>
                    <div className="pr:text-xs pr:text-gray-600 pr:truncate">
                      {profile.url}
                    </div>
                  </div>
                  <button
                    onClick={() => removeAdditionalProfile(index)}
                    className="pr:p-2 pr:text-error-500 pr:hover:bg-error-50 pr:rounded-md pr:transition-colors"
                    aria-label={__('Remove', 'prorank-seo')}
                  >
                    <XMarkIcon className="pr:w-5 pr:h-5" />
                  </button>
                </div>
              ))}
            </div>
          )}

          <div className="pr:border-t pr:border-gray-200 pr:pt-4">
            <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-3">
              {__('Add New Profile', 'prorank-seo')}
            </h4>
            <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-[200px_1fr_auto] pr:gap-3 pr:items-end">
              <Input
                label={__('Platform Name', 'prorank-seo')}
                value={newProfile.platform}
                onChange={(value) => setNewProfile({ ...newProfile, platform: value })}
                placeholder="TikTok, GitHub, etc."
              />
              <Input
                label={__('Profile URL', 'prorank-seo')}
                type="url"
                value={newProfile.url}
                onChange={(value) => setNewProfile({ ...newProfile, url: value })}
                placeholder="https://example.com/profile"
              />
              <Button
                variant="secondary"
                icon={PlusIcon}
                onClick={addAdditionalProfile}
                disabled={!newProfile.platform || !newProfile.url}
              >
                {__('Add', 'prorank-seo')}
              </Button>
            </div>
          </div>
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Best Practices', 'prorank-seo')}
          </h3>
        }
      >
        <div>
          <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-2">
            {__('Tips for Social Profiles:', 'prorank-seo')}
          </h4>
          <ul className="pr:list-disc pr:list-inside pr:space-y-1 pr:text-sm pr:text-gray-600">
            <li>{__('Use official business accounts, not personal profiles (except for authorship)', 'prorank-seo')}</li>
            <li>{__('Keep all URLs up to date if you change usernames', 'prorank-seo')}</li>
            <li>{__('Include only active profiles you regularly maintain', 'prorank-seo')}</li>
            <li>{__('Facebook Admin ID helps with Insights and moderation', 'prorank-seo')}</li>
            <li>{__('Twitter username enables Twitter Cards for better sharing', 'prorank-seo')}</li>
            <li>{__('These profiles appear in your site\'s structured data', 'prorank-seo')}</li>
          </ul>
        </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 SocialProfilesTab;
