/**
 * Site Policies Tab Component
 *
 * Manages site policy pages for transparency and trust
 *
 * @package ProRank\SEO
 */

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

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

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

  const loadPages = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/pages?per_page=100&status=publish',
      });
      const pageOptions = response.map(page => ({
        label: page.title.rendered,
        value: page.id.toString(),
      }));
      pageOptions.unshift({ label: __('None', 'prorank-seo'), value: '' });
      setPages(pageOptions);
    } catch (error) {
      // Failed to load pages, will use empty list
    }
  };

  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 policies = [
    {
      key: 'privacy_policy_page',
      label: __('Privacy Policy', 'prorank-seo'),
      help: __('Your privacy policy page. Required by GDPR, CCPA, and other privacy laws. Describes how you collect, use, and protect user data.', 'prorank-seo'),
    },
    {
      key: 'terms_of_service_page',
      label: __('Terms of Service', 'prorank-seo'),
      help: __('Your terms of service or terms and conditions page. Legal agreement between your site and its users.', 'prorank-seo'),
    },
    {
      key: 'publishing_principles_page',
      label: __('Publishing Principles', 'prorank-seo'),
      help: __('Describes the editorial principles of your organization. What do you write about, who do you write for, and why?', 'prorank-seo'),
    },
    {
      key: 'ownership_funding_page',
      label: __('Ownership / Funding Info', 'prorank-seo'),
      help: __('Describes the ownership structure of your organization. Should include information about funding and grants.', 'prorank-seo'),
    },
    {
      key: 'actionable_feedback_page',
      label: __('Actionable Feedback Policy', 'prorank-seo'),
      help: __('Describes how your organization collects and responds to feedback, engages with the public, and prioritizes transparency.', 'prorank-seo'),
    },
    {
      key: 'corrections_policy_page',
      label: __('Corrections Policy', 'prorank-seo'),
      help: __('Outlines your procedure for addressing errors (e.g., publishing retractions or corrections).', 'prorank-seo'),
    },
    {
      key: 'ethics_policy_page',
      label: __('Ethics Policy', 'prorank-seo'),
      help: __('Describes the personal, organizational, and corporate standards of behavior expected by your organization.', 'prorank-seo'),
    },
    {
      key: 'diversity_policy_page',
      label: __('Diversity Policy', 'prorank-seo'),
      help: __('Provides information on your diversity policies for editorial content.', 'prorank-seo'),
    },
    {
      key: 'diversity_staffing_page',
      label: __('Diversity Staffing Report', 'prorank-seo'),
      help: __('Provides information about your diversity policies for staffing, hiring and employment.', 'prorank-seo'),
    },
  ];

  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">
          {__('Site policies demonstrate transparency and build trust with users and search engines. Select existing pages that contain your policy information.', 'prorank-seo')}
        </p>
      </div>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Policy Pages', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <p className="pr:text-sm pr:text-gray-600">
            {__('Select the pages on your website which contain information about your organizational and publishing policies. Some of these might not apply to your site, and you can select the same page for multiple policies.', 'prorank-seo')}
          </p>

          {policies.map((policy) => (
            <Select
              key={policy.key}
              label={policy.label}
              value={settings[policy.key] || ''}
              options={pages}
              onChange={(value) => handleChange(policy.key, value)}
              helperText={policy.help}
            />
          ))}
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Why Site Policies Matter', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <div>
            <p className="pr:text-sm pr:text-gray-700 pr:mb-3">
              {__('Setting your site policies is important for:', 'prorank-seo')}
            </p>
            <ul className="pr:list-disc pr:list-inside pr:space-y-1 pr:text-sm pr:text-gray-600">
              <li>{__('Building trust with your audience', 'prorank-seo')}</li>
              <li>{__('Meeting Google\'s E-E-A-T (Experience, Expertise, Authoritativeness, Trustworthiness) guidelines', 'prorank-seo')}</li>
              <li>{__('Improving your site\'s credibility signals', 'prorank-seo')}</li>
              <li>{__('Qualifying for Google News and other aggregators', 'prorank-seo')}</li>
              <li>{__('Demonstrating transparency and accountability', 'prorank-seo')}</li>
            </ul>
          </div>

          <a
            href="https://developers.google.com/search/docs/appearance/structured-data/article#structured-data-guidelines"
            target="_blank"
            rel="noopener noreferrer"
            className="pr:inline-flex pr:items-center pr:gap-2 pr:text-sm pr:text-primary-500 pr:hover:text-primary-600 pr:font-medium"
          >
            {__('Learn more about structured data guidelines', 'prorank-seo')}
            <svg className="pr:w-4 pr:h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
            </svg>
          </a>
        </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 SitePoliciesTab;
