/**
 * Site Basics Settings Component
 *
 * Main component for fundamental site configuration including
 * site info, verification, social profiles, and more.
 *
 * @package ProRank\SEO
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { useNotification } from '../../../contexts/NotificationContext';
import { Alert } from '../../../components/ui';
import LoadingState from '../../../components/LoadingState';

// Import tab components
import SiteInfoTab from './tabs/SiteInfoTab';
import SiteVerificationTab from './tabs/SiteVerificationTab';
import SocialProfilesTab from './tabs/SocialProfilesTab';
import OrganizationTab from './tabs/OrganizationTab';
import SitePoliciesTab from './tabs/SitePoliciesTab';

const SiteBasicsSettings = () => {
  const { showNotification } = useNotification();
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('site-info');
  const [settings, setSettings] = useState({
    // Site Information
    site_name: '',
    site_alternate_name: '',
    site_tagline: '',
    title_separator: '-',
    site_logo: '',
    site_image: '',

    // Site Verification
    google_verification: '',
    bing_verification: '',
    baidu_verification: '',
    yandex_verification: '',
    pinterest_verification: '',
    norton_verification: '',
    custom_meta_tags: '',

    // Social Profiles
    facebook_page_url: '',
    facebook_authorship: '',
    facebook_admin_id: '',
    facebook_app_id: '',
    facebook_secret: '',
    twitter_username: '',
    linkedin_url: '',
    instagram_url: '',
    youtube_url: '',
    pinterest_url: '',
    tiktok_url: '',
    threads_url: '',
    mastodon_url: '',
    additional_profiles: [],

    // Organization Info
    org_or_person: 'organization',
    org_name: '',
    org_alternate_name: '',
    org_logo: '',
    org_local_business_enabled: false,
    person_user_id: '',
    org_description: '',
    org_email: '',
    org_phone: '',
    org_legal_name: '',
    org_founding_date: '',
    org_num_employees: '',
    org_vat_id: '',
    org_tax_id: '',
    org_iso_6523: '',
    org_duns: '',
    org_lei_code: '',
    org_naics: '',
    org_street_address: '',
    org_address_locality: '',
    org_address_region: '',
    org_postal_code: '',
    org_address_country: '',

    // Site Policies
    privacy_policy_page: '',
    terms_of_service_page: '',
    publishing_principles_page: '',
    ownership_funding_page: '',
    actionable_feedback_page: '',
    corrections_policy_page: '',
    ethics_policy_page: '',
    diversity_policy_page: '',
    diversity_staffing_page: '',

  });

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/site_basics',
        method: 'GET',
      });

      if (response && response.settings) {
        setSettings(prevSettings => ({
          ...prevSettings,
          ...response.settings
        }));
      }
    } catch (error) {
      // If settings don't exist yet, use defaults
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async (updatedSettings) => {
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/site_basics',
        method: 'POST',
        data: {
          settings: updatedSettings || settings,
        },
      });
      showNotification(__('Settings saved successfully!', 'prorank-seo'), 'success');
      return true;
    } catch (error) {
      showNotification(
        __('Failed to save settings. Please try again.', 'prorank-seo'),
        'error'
      );
      return false;
    }
  };

  const updateSettings = (newSettings) => {
    setSettings(prevSettings => ({
      ...prevSettings,
      ...newSettings
    }));
  };

  if (loading) {
    return <LoadingState message={__('Loading site basics settings...', 'prorank-seo')} />;
  }

  const tabs = [
    {
      name: 'site-info',
      title: __('Site Information', 'prorank-seo'),
    },
    {
      name: 'verification',
      title: __('Site Verification', 'prorank-seo'),
    },
    {
      name: 'social',
      title: __('Social Profiles', 'prorank-seo'),
    },
    {
      name: 'organization',
      title: __('Site Representation', 'prorank-seo'),
    },
    {
      name: 'policies',
      title: __('Site Policies', 'prorank-seo'),
    },
  ];

  return (
    <div className="pr:space-y-6">
      <Alert variant="info" title={__('Site Basics', 'prorank-seo')}>
        {__('These settings provide essential information about your site to search engines and social platforms. Proper configuration improves your site\'s visibility and credibility.', 'prorank-seo')}
      </Alert>

      {/* Tab Navigation */}
      <div className="pr:bg-white pr:rounded-lg pr:shadow-card pr:overflow-hidden">
        <div className="pr:border-b pr:border-gray-200">
          <nav className="pr:flex pr:gap-0" aria-label="Tabs">
            {tabs.map((tab) => (
              <button
                key={tab.name}
                onClick={() => setActiveTab(tab.name)}
                className={`
                  pr:flex-1 pr:px-6 pr:py-4 pr:text-sm pr:font-medium pr:text-center pr:border-b-2 pr:transition-colors
                  ${
                    activeTab === tab.name
                      ? 'pr:border-primary-500 pr:text-primary-600 pr:bg-primary-50'
                      : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-900 pr:hover:border-gray-300'
                  }
                `}
                aria-current={activeTab === tab.name ? 'page' : undefined}
              >
                {tab.title}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content */}
        <div className="pr:p-6">
          {activeTab === 'site-info' && (
            <SiteInfoTab
              settings={settings}
              updateSettings={updateSettings}
              saveSettings={saveSettings}
            />
          )}
          {activeTab === 'verification' && (
            <SiteVerificationTab
              settings={settings}
              updateSettings={updateSettings}
              saveSettings={saveSettings}
            />
          )}
          {activeTab === 'social' && (
            <SocialProfilesTab
              settings={settings}
              updateSettings={updateSettings}
              saveSettings={saveSettings}
            />
          )}
          {activeTab === 'organization' && (
            <OrganizationTab
              settings={settings}
              updateSettings={updateSettings}
              saveSettings={saveSettings}
            />
          )}
          {activeTab === 'policies' && (
            <SitePoliciesTab
              settings={settings}
              updateSettings={updateSettings}
              saveSettings={saveSettings}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default SiteBasicsSettings;
