import { useState, useEffect } from 'react';
import { useSettings } from '../../contexts/SettingsContext';
import { useAuth } from '../../contexts/AuthContext';
import {
  PageHeader,
  Button,
  IconButton,
  ModalLayout,
  IconContentCopy,
  IconCheck,
  IconRefresh,
} from '../ui';
import styles from './Settings.module.scss';

export default function Settings() {
  const { showNotification } = useSettings();
  const { checkAuth } = useAuth();
  const [apiKey, setApiKey] = useState<string>(() => (window as any).sideconvoData?.apiKey || '');
  // Seed siteId/scSiteUrl immediately from PHP-localized data so they
  // display on first paint even if the REST call is slow or fails.
  const [siteId, setSiteId] = useState<string>(() => (window as any).sideconvoData?.siteId || '');
  const [scSiteUrl, setScSiteUrl] = useState<string>(() => (window as any).sideconvoData?.scSiteUrl || '');
  const [isLoading, setIsLoading] = useState(true);
  const [showResetModal, setShowResetModal] = useState(false);
  const [isResetting, setIsResetting] = useState(false);
  const [copiedField, setCopiedField] = useState<string | null>(null);
  const [isRefreshingKey, setIsRefreshingKey] = useState(false);
  useEffect(() => {
    fetchSettings();
  }, []);

  const fetchSettings = async () => {
    try {
      const response = await fetch(
        `${(window as any).sideconvoData.restUrl}sideconvo/v1/settings`,
        {
          headers: {
            'X-WP-Nonce': (window as any).sideconvoData.nonce,
          },
          cache: 'no-store',
        }
      );

      if (!response.ok) {
        console.error('Settings fetch failed:', response.status, response.statusText);
        setIsLoading(false);
        return;
      }

      const data = await response.json();
      setApiKey(data.apiKey || '');
      setSiteId(data.siteId || '');
      setScSiteUrl(data.scSiteUrl || '');
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching settings:', error);
      setIsLoading(false);
    }
  };

  const handleCopy = async (value: string, field: string) => {
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(value);
      } else {
        const textarea = document.createElement('textarea');
        textarea.value = value;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
      }
      setCopiedField(field);
      setTimeout(() => setCopiedField(null), 2000);
    } catch {
      showNotification('error', `Failed to copy ${field}`);
    }
  };

  const handleCopyApiKey = async () => {
    try {
      const response = await fetch(
        `${(window as any).sideconvoData.restUrl}sideconvo/v1/settings/api-key`,
        {
          headers: { 'X-WP-Nonce': (window as any).sideconvoData.nonce },
          cache: 'no-store',
        }
      );
      const rawKey = response.ok ? (await response.json()).apiKey : apiKey;
      await handleCopy(rawKey || apiKey, 'api-key');
    } catch {
      await handleCopy(apiKey, 'api-key');
    }
  };

  const handleRefreshApiKey = async () => {
    if (isRefreshingKey) return;
    setIsRefreshingKey(true);
    try {
      const response = await fetch(
        `${(window as any).sideconvoData.restUrl}sideconvo/v1/auth-status?force=true`,
        {
          headers: { 'X-WP-Nonce': (window as any).sideconvoData.nonce },
          cache: 'no-store',
        }
      );
      if (response.ok) {
        const data = await response.json();
        if (data.authenticated) {
          showNotification('success', 'API key is valid');
        } else {
          showNotification('error', 'API key is invalid or has been revoked');
        }
      } else {
        showNotification('error', 'Could not validate API key');
      }
    } catch {
      showNotification('error', 'Could not validate API key');
    } finally {
      setIsRefreshingKey(false);
    }
  };

  const handleReset = async () => {
    setIsResetting(true);

    try {
      const response = await fetch(
        `${(window as any).sideconvoData.restUrl}sideconvo/v1/disconnect-site`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': (window as any).sideconvoData.nonce,
          },
          body: JSON.stringify({ delete_sync_data: false }),
        }
      );

      if (!response.ok) {
        throw new Error('Failed to reset plugin');
      }

      showNotification('success', 'Plugin reset successfully');
      setTimeout(() => {
        checkAuth();
      }, 500);
    } catch (error) {
      console.error('Error resetting plugin:', error);
      showNotification('error', 'Failed to reset plugin');
      setIsResetting(false);
    }
  };

  if (isLoading) {
    return (
      <div className={styles.container}>
        <PageHeader
          title="Plugin Settings"
          subtitle="Manage your Sideconvo Plugin configuration"
        />
        {[1, 2, 3].map((i) => (
          <div key={i} className={styles.card}>
            <div className={styles.cardHeader}>
              <div className={styles.skeletonCell} style={{ width: 140, height: 14 }} />
            </div>
            <div className={styles.cardBody}>
              <div className={styles.skeletonCell} style={{ width: '60%', height: 12 }} />
              <div className={styles.skeletonCell} style={{ width: i === 1 ? 280 : '40%', height: 36, borderRadius: 8 }} />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <PageHeader
        title="Plugin Settings"
        subtitle="Manage your Sideconvo Plugin configuration"
      />

      {/* API Configuration */}
      <div className={styles.card}>
        <div className={styles.cardHeader}>
          <h2 className={styles.cardTitle}>API Configuration</h2>
        </div>
        <div className={styles.cardBody}>
          <p className={styles.cardDescription}>
            Your Sideconvo API key for authentication
          </p>
          <div className={styles.apiKeyRow}>
            <span className={styles.apiKeyText}>{apiKey}</span>
            <IconButton
              variant="tertiary"
              size="small"
              onClick={handleRefreshApiKey}
              aria-label="Refresh API key"
              title="Refresh API key"
              disabled={isRefreshingKey}
            >
              <IconRefresh className={isRefreshingKey ? 'spin' : undefined} />
            </IconButton>
            <IconButton
              variant="tertiary"
              size="small"
              onClick={handleCopyApiKey}
              aria-label="Copy API key"
              title={copiedField === 'api-key' ? 'Copied!' : 'Copy API key'}
            >
              {copiedField === 'api-key' ? <IconCheck /> : <IconContentCopy />}
            </IconButton>
          </div>
        </div>
      </div>

      {/* Site Information */}
      {(siteId || scSiteUrl) && (
        <div className={styles.card}>
          <div className={styles.cardHeader}>
            <h2 className={styles.cardTitle}>Site Information</h2>
          </div>
          <div className={styles.cardBody}>
            <div className={styles.infoPills}>
              {scSiteUrl && (
                <div className={styles.infoPill}>
                  <span className={styles.pillLabel}>Site URL:</span>
                  <span className={styles.pillValue}>{scSiteUrl}</span>
                  <IconButton
                    variant="tertiary"
                    size="small"
                    onClick={() => handleCopy(scSiteUrl, 'site-url')}
                    aria-label="Copy Site URL"
                    title={copiedField === 'site-url' ? 'Copied!' : 'Copy Site URL'}
                  >
                    {copiedField === 'site-url' ? <IconCheck /> : <IconContentCopy />}
                  </IconButton>
                </div>
              )}
              {siteId && (
                <div className={styles.infoPill}>
                  <span className={styles.pillLabel}>Site ID:</span>
                  <span className={styles.pillValue}>{siteId}</span>
                  <IconButton
                    variant="tertiary"
                    size="small"
                    onClick={() => handleCopy(siteId, 'site-id')}
                    aria-label="Copy Site ID"
                    title={copiedField === 'site-id' ? 'Copied!' : 'Copy Site ID'}
                  >
                    {copiedField === 'site-id' ? <IconCheck /> : <IconContentCopy />}
                  </IconButton>
                </div>
              )}
            </div>
          </div>
        </div>
      )}


      {/* Reset Plugin */}
      <div className={styles.card}>
        <div className={styles.cardHeader}>
          <h2 className={styles.cardTitle}>Reset Plugin</h2>
          <Button
            variant="danger"
            size="small"
            onClick={() => setShowResetModal(true)}
            disabled={isResetting}
          >
            {isResetting ? 'Resetting...' : 'Reset Plugin'}
          </Button>
        </div>
        <div className={styles.cardBody}>
          <p className={styles.cardDescription}>
            This will remove configuration and reset the plugin to its initial state.
          </p>
        </div>
      </div>

      {/* Reset Confirmation Modal */}
      <ModalLayout
        isOpen={showResetModal}
        title="Reset plugin?"
        showDismiss={false}
        width={540}
        primaryActionText="Reset Plugin"
        primaryActionVariant="danger"
        secondaryActionText="Cancel"
        onPrimaryAction={() => {
          setShowResetModal(false);
          handleReset();
        }}
        onSecondaryAction={() => setShowResetModal(false)}
        onDismiss={() => setShowResetModal(false)}
        primaryActionDisabled={isResetting}
      >
        <p className={styles.modalDescription}>
          This will disconnect your WordPress site from Sideconvo and return you to the splash screen.
        </p>
        <div className={styles.checklist}>
          <p className={styles.checklistTitle}>After resetting:</p>
          <div className={styles.checklistItem}>
            <IconCheck size={16} className={styles.checkIcon} />
            <span>API keys will be removed from WordPress</span>
          </div>
          <div className={styles.checklistItem}>
            <IconCheck size={16} className={styles.checkIcon} />
            <span>You'll need to reconnect to Sideconvo</span>
          </div>
          <div className={styles.checklistItem}>
            <IconCheck size={16} className={styles.checkIcon} />
            <span>Your data in Sideconvo stays intact</span>
          </div>
          <div className={styles.checklistItem}>
            <IconCheck size={16} className={styles.checkIcon} />
            <span>Your subscription and conversations are not affected</span>
          </div>
        </div>
      </ModalLayout>
    </div>
  );
}
