/**
 * Organization/Site Representation Tab Component
 *
 * Manages whether site represents an organization or person
 *
 * @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, Input, Select, Toggle } from '../../../../components/ui';

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

  useEffect(() => {
    // Load WordPress users for person selection
    loadUsers();
  }, []);

  const loadUsers = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/users?per_page=100',
      });
      const userOptions = response.map(user => ({
        label: `${user.name} (${user.slug})`,
        value: user.id.toString(),
      }));
      userOptions.unshift({ label: __('Select a user...', 'prorank-seo'), value: '' });
      setUsers(userOptions);
    } catch (error) {
      // Failed to load users, 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 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();
      handleChange(key, attachment.url);
      handleChange(`${key}_id`, attachment.id);
    });

    mediaUploader.open();
  };

  const employeeRanges = [
    { label: __('Select a range', 'prorank-seo'), value: '' },
    { label: '1-10', value: '1-10' },
    { label: '11-50', value: '11-50' },
    { label: '51-200', value: '51-200' },
    { label: '201-500', value: '201-500' },
    { label: '501-1000', value: '501-1000' },
    { label: '1001-5000', value: '1001-5000' },
    { label: '5001-10000', value: '5001-10000' },
    { label: '10000+', value: '10000+' },
  ];

  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">
          {__('This information appears in Google\'s Knowledge Graph and helps search engines understand your site\'s identity.', 'prorank-seo')}
        </p>
      </div>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Site Representation', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-3">
          <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
            {__('Does your site represent an organization or a person?', 'prorank-seo')}
          </label>
          <div className="pr:space-y-2">
            <label className="pr:flex pr:items-center pr:gap-3 pr:p-3 pr:border pr:border-gray-300 pr:rounded-lg pr:cursor-pointer pr:hover:bg-gray-50 pr:transition-colors">
              <input
                type="radio"
                name="org_or_person"
                value="organization"
                checked={(settings.org_or_person || 'organization') === 'organization'}
                onChange={(e) => handleChange('org_or_person', e.target.value)}
                className="pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:focus:ring-2 pr:focus:ring-primary-500"
              />
              <div className="pr:flex-1">
                <div className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Organization', 'prorank-seo')}
                </div>
                <div className="pr:text-xs pr:text-gray-500">
                  {__('For businesses, companies, or organizations', 'prorank-seo')}
                </div>
              </div>
            </label>
            <label className="pr:flex pr:items-center pr:gap-3 pr:p-3 pr:border pr:border-gray-300 pr:rounded-lg pr:cursor-pointer pr:hover:bg-gray-50 pr:transition-colors">
              <input
                type="radio"
                name="org_or_person"
                value="person"
                checked={settings.org_or_person === 'person'}
                onChange={(e) => handleChange('org_or_person', e.target.value)}
                className="pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:focus:ring-2 pr:focus:ring-primary-500"
              />
              <div className="pr:flex-1">
                <div className="pr:text-sm pr:font-medium pr:text-gray-900">
                  {__('Person', 'prorank-seo')}
                </div>
                <div className="pr:text-xs pr:text-gray-500">
                  {__('For individual personal websites or blogs', 'prorank-seo')}
                </div>
              </div>
            </label>
          </div>
        </div>
      </Card>

      {settings.org_or_person === 'person' ? (
        <Card
          header={
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Personal Information', 'prorank-seo')}
            </h3>
          }
        >
          <div className="pr:space-y-4">
            <Select
              label={__('Select User', 'prorank-seo')}
              value={settings.person_user_id || ''}
              options={users}
              onChange={(value) => handleChange('person_user_id', value)}
              helperText={__('Select the WordPress user this site represents', 'prorank-seo')}
            />

            <div className="pr:space-y-2">
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                {__('Personal Logo or Avatar', 'prorank-seo')}
              </label>
              {settings.person_logo ? (
                <div className="pr:flex pr:items-start pr:gap-4">
                  <img
                    src={settings.person_logo}
                    alt={__('Personal Avatar', 'prorank-seo')}
                    className="pr:w-32 pr:h-32 pr:object-cover pr:rounded-lg pr:border pr:border-gray-200"
                  />
                  <div className="pr:flex pr:flex-col pr:gap-2">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => openMediaLibrary('person_logo')}
                    >
                      {__('Replace', 'prorank-seo')}
                    </Button>
                    <Button
                      variant="danger"
                      size="sm"
                      onClick={() => {
                        handleChange('person_logo', '');
                        handleChange('person_logo_id', '');
                      }}
                    >
                      {__('Remove', 'prorank-seo')}
                    </Button>
                  </div>
                </div>
              ) : (
                <Button
                  variant="secondary"
                  onClick={() => openMediaLibrary('person_logo')}
                >
                  {__('Select Image', 'prorank-seo')}
                </Button>
              )}
            </div>
          </div>
        </Card>
      ) : (
        <>
          <Card
            header={
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {__('Organization Details', 'prorank-seo')}
              </h3>
            }
          >
            <div className="pr:space-y-4">
              <Input
                label={__('Organization Name', 'prorank-seo')}
                value={settings.org_name || ''}
                onChange={(value) => handleChange('org_name', value)}
                helperText={__('The official name of your organization', 'prorank-seo')}
              />

              <Toggle
                label={__('This is a local business', 'prorank-seo')}
                description={__('Use LocalBusiness schema and include address details for local visibility.', 'prorank-seo')}
                checked={Boolean(settings.org_local_business_enabled)}
                onChange={(value) => handleChange('org_local_business_enabled', value)}
              />

              <Input
                label={__('Alternate Organization Name', 'prorank-seo')}
                value={settings.org_alternate_name || ''}
                onChange={(value) => handleChange('org_alternate_name', value)}
                helperText={__('Use for acronyms or shorter version of your organization name', 'prorank-seo')}
              />

              <div className="pr:space-y-2">
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Organization Logo', 'prorank-seo')}
                </label>
                <p className="pr:text-xs pr:text-gray-500">
                  {__('Your organization logo for structured data. Should be square, minimum 112x112px.', 'prorank-seo')}
                </p>
                {settings.org_logo ? (
                  <div className="pr:flex pr:items-start pr:gap-4">
                    <img
                      src={settings.org_logo}
                      alt={__('Organization Logo', 'prorank-seo')}
                      className="pr:w-40 pr:h-40 pr:object-contain pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200"
                    />
                    <div className="pr:flex pr:flex-col pr:gap-2">
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => openMediaLibrary('org_logo')}
                      >
                        {__('Replace', 'prorank-seo')}
                      </Button>
                      <Button
                        variant="danger"
                        size="sm"
                        onClick={() => {
                          handleChange('org_logo', '');
                          handleChange('org_logo_id', '');
                        }}
                      >
                        {__('Remove', 'prorank-seo')}
                      </Button>
                    </div>
                  </div>
                ) : (
                  <Button
                    variant="secondary"
                    onClick={() => openMediaLibrary('org_logo')}
                  >
                    {__('Select Logo', 'prorank-seo')}
                  </Button>
                )}
              </div>

              <div className="pr:space-y-2">
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Organization Description', '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.org_description || ''}
                  onChange={(e) => handleChange('org_description', e.target.value)}
                  rows={3}
                />
                <p className="pr:text-xs pr:text-gray-500">
                  {__('A brief description of what your organization does', 'prorank-seo')}
                </p>
              </div>

              <Input
                label={__('Organization Email', 'prorank-seo')}
                type="email"
                value={settings.org_email || ''}
                onChange={(value) => handleChange('org_email', value)}
                helperText={__('Public contact email for your organization', 'prorank-seo')}
              />

              <Input
                label={__('Organization Phone', 'prorank-seo')}
                type="tel"
                value={settings.org_phone || ''}
                onChange={(value) => handleChange('org_phone', value)}
                helperText={__('Include country code (e.g., +1-555-123-4567)', 'prorank-seo')}
              />

              <Input
                label={__('Legal Name', 'prorank-seo')}
                value={settings.org_legal_name || ''}
                onChange={(value) => handleChange('org_legal_name', value)}
                helperText={__('The registered legal name if different from organization name', 'prorank-seo')}
              />

              <Input
                label={__('Founding Date', 'prorank-seo')}
                type="date"
                value={settings.org_founding_date || ''}
                onChange={(value) => handleChange('org_founding_date', value)}
                helperText={__('When was your organization founded?', 'prorank-seo')}
              />

              <Select
                label={__('Number of Employees', 'prorank-seo')}
                value={settings.org_num_employees || ''}
                options={employeeRanges}
                onChange={(value) => handleChange('org_num_employees', value)}
                helperText={__('Approximate number of employees', 'prorank-seo')}
              />
            </div>
          </Card>

          <Card
            header={
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {__('Organization Address', 'prorank-seo')}
              </h3>
            }
          >
            <div className="pr:space-y-4">
              <p className="pr:text-sm pr:text-gray-600">
                {__('Physical address of your organization. This is required for Local SEO and appears in Organization schema.', 'prorank-seo')}
              </p>

              <Input
                label={__('Street Address', 'prorank-seo')}
                value={settings.org_street_address || ''}
                onChange={(value) => handleChange('org_street_address', value)}
                helperText={__('Street address including building number', 'prorank-seo')}
              />

              <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-4">
                <Input
                  label={__('City', 'prorank-seo')}
                  value={settings.org_address_locality || ''}
                  onChange={(value) => handleChange('org_address_locality', value)}
                  helperText={__('City or locality', 'prorank-seo')}
                />

                <Input
                  label={__('State / Region', 'prorank-seo')}
                  value={settings.org_address_region || ''}
                  onChange={(value) => handleChange('org_address_region', value)}
                  helperText={__('State, province, or region', 'prorank-seo')}
                />
              </div>

              <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-4">
                <Input
                  label={__('Postal Code', 'prorank-seo')}
                  value={settings.org_postal_code || ''}
                  onChange={(value) => handleChange('org_postal_code', value)}
                  helperText={__('ZIP or postal code', 'prorank-seo')}
                />

                <Input
                  label={__('Country', 'prorank-seo')}
                  value={settings.org_address_country || ''}
                  onChange={(value) => handleChange('org_address_country', value)}
                  helperText={__('Country name (e.g., United States)', 'prorank-seo')}
                />
              </div>
            </div>
          </Card>

          <Card
            header={
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {__('Organization Identifiers', 'prorank-seo')}
              </h3>
            }
          >
            <div className="pr:space-y-4">
              <p className="pr:text-sm pr:text-gray-600">
                {__('These identifiers help Google accurately identify your organization. Fill in only the ones that apply.', 'prorank-seo')}
              </p>

              <Input
                label={__('VAT ID', 'prorank-seo')}
                value={settings.org_vat_id || ''}
                onChange={(value) => handleChange('org_vat_id', value)}
                helperText={__('Value Added Tax identification number', 'prorank-seo')}
              />

              <Input
                label={__('Tax ID', 'prorank-seo')}
                value={settings.org_tax_id || ''}
                onChange={(value) => handleChange('org_tax_id', value)}
                helperText={__('Tax identification number (EIN in the US)', 'prorank-seo')}
              />

              <Input
                label={__('DUNS Number', 'prorank-seo')}
                value={settings.org_duns || ''}
                onChange={(value) => handleChange('org_duns', value)}
                helperText={__('Data Universal Numbering System number', 'prorank-seo')}
              />

              <Input
                label={__('LEI Code', 'prorank-seo')}
                value={settings.org_lei_code || ''}
                onChange={(value) => handleChange('org_lei_code', value)}
                helperText={__('Legal Entity Identifier', 'prorank-seo')}
              />

              <Input
                label={__('NAICS Code', 'prorank-seo')}
                value={settings.org_naics || ''}
                onChange={(value) => handleChange('org_naics', value)}
                helperText={__('North American Industry Classification System code', 'prorank-seo')}
              />

              <Input
                label={__('ISO 6523', 'prorank-seo')}
                value={settings.org_iso_6523 || ''}
                onChange={(value) => handleChange('org_iso_6523', value)}
                helperText={__('International Organization for Standardization identifier', 'prorank-seo')}
              />
            </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 OrganizationTab;
