import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Card } from '../components/Card';
import { Badge } from '../components/Badge';
import { useConfig, wpApiFetch, externalApiFetch, isDevMode, PLAN_OVERRIDE_KEY, dispatchPlanChange } from '../hooks/useApi';
import { PLAN_LIMITS } from '@cra-compliance/types';
import type { DashboardStats, UserWebhook, WebhookEventType } from '@cra-compliance/types';

export function Settings() {
  const config = useConfig();
  const isPremium = config.plan !== 'free';
  const [savedApiKey, setSavedApiKey] = useState(config.apiKey || '');

  const statsQuery = useQuery<DashboardStats>({
    queryKey: ['dashboard'],
    enabled: isPremium,
    queryFn: async () => {
      const res = await externalApiFetch<{ data: DashboardStats }>('/api/dashboard');
      return res.data;
    },
    staleTime: 5 * 60 * 1000,
  });
  const [apiKeyInput, setApiKeyInput] = useState(config.apiKey || '');
  const [verifying, setVerifying] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [editingKey, setEditingKey] = useState(!config.apiKey);

  const maskedKey = savedApiKey ? `cra_************************${savedApiKey.slice(-8)}` : null;

  // Fetch fresh settings from DB on mount (config.apiKey can be stale from wp_localize_script)
  useEffect(() => {
    wpApiFetch<{ success: boolean; data: { api_key: string; plan: string } }>('settings')
      .then((res) => {
        if (!res.success) return;
        const serverKey = res.data.api_key || '';
        setSavedApiKey(serverKey);
        setApiKeyInput(serverKey);
        setEditingKey(!serverKey);
      })
      .catch(() => {});
  }, []);

  const verifyAndSave = async () => {
    const nextKey = apiKeyInput.trim();
    if (!nextKey) {
      setMessage({ type: 'error', text: 'Please enter an API key' });
      return;
    }

    setVerifying(true);
    setMessage(null);

    try {
      const res = await wpApiFetch<{ success: boolean; data?: { plan: string }; error?: string }>(
        'verify-key',
        {
          method: 'POST',
          body: JSON.stringify({ api_key: nextKey }),
        },
      );

      if (res.success && res.data) {
        setSavedApiKey(nextKey);
        setApiKeyInput(nextKey);
        setEditingKey(false);
        setMessage({
          type: 'success',
          text: `API key verified! Plan: ${res.data.plan.toUpperCase()}. Reloading...`,
        });
        // Reload so the wp_localize_script data refreshes with new plan
        setTimeout(() => window.location.reload(), 1000);
      } else {
        setEditingKey(true);
        setMessage({ type: 'error', text: res.error || 'Invalid API key' });
      }
    } catch (err) {
      setEditingKey(true);
      setMessage({
        type: 'error',
        text: err instanceof Error ? err.message : 'Failed to verify API key',
      });
    } finally {
      setVerifying(false);
    }
  };

  const clearApiKey = async () => {
    try {
      await wpApiFetch('settings', {
        method: 'POST',
        body: JSON.stringify({ api_key: '' }),
      });
      setSavedApiKey('');
      setApiKeyInput('');
      setEditingKey(true);
      setMessage({ type: 'success', text: 'API key removed. Reloading...' });
      // Reload so the wp_localize_script data refreshes (plan resets to free server-side)
      setTimeout(() => window.location.reload(), 1000);
    } catch {
      setMessage({ type: 'error', text: 'Failed to clear API key' });
    }
  };

  const currentLimits = PLAN_LIMITS[config.plan as keyof typeof PLAN_LIMITS] || PLAN_LIMITS.free;
  const stats = statsQuery.data ?? null;

  return (
    <div className="cra-settings-page">
      <div className="cra-page-header">
        <h1>Settings</h1>
        <p>Configure your ResilienceWP settings.</p>
      </div>

      <Card title="Current Plan">
        <div className="cra-settings-plan">
          <Badge variant={config.plan !== 'free' ? 'success' : 'neutral'}>
            {config.plan.toUpperCase()}
          </Badge>
          {config.plan === 'free' && (
            <p style={{ marginTop: '12px' }}>
              Upgrade to Basic ($49/year) or Pro ($99/year) to unlock vulnerability
              scanning, email alerts, and compliance reports.{' '}
              <a
                href="https://www.resiliencewp.com/pricing"
                target="_blank"
                rel="noopener noreferrer"
              >
                View pricing &rarr;
              </a>
            </p>
          )}
          {config.plan !== 'free' && (
            <p style={{ marginTop: '12px' }}>
              Manage your subscription at{' '}
              <a
                href="https://www.resiliencewp.com/settings"
                target="_blank"
                rel="noopener noreferrer"
              >
                resiliencewp.com/settings
              </a>
            </p>
          )}
        </div>
      </Card>

      <Card title="Plan Limits">
        <table className="cra-limits-table" style={{ width: '100%', borderCollapse: 'collapse' }}>
          <tbody>
            <tr>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Monitored Plugins</td>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>{currentLimits.max_plugins}</td>
            </tr>
            <tr>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Scan Frequency</td>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>{currentLimits.scan_frequency}</td>
            </tr>
            <tr>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Scans Per Month</td>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>{currentLimits.max_scans_per_month}</td>
            </tr>
            <tr>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Compliance Reports</td>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>{currentLimits.reports ? 'Yes' : 'No'}</td>
            </tr>
            <tr>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Email Alerts</td>
              <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>{currentLimits.email_alerts ? 'Yes' : 'No'}</td>
            </tr>
            <tr>
              <td style={{ padding: '8px 0' }}>Priority Support</td>
              <td style={{ padding: '8px 0', textAlign: 'right', fontWeight: 600 }}>{currentLimits.priority_support ? 'Yes' : 'No'}</td>
            </tr>
          </tbody>
        </table>
      </Card>

      {isPremium && stats && (
        <Card title="Scanner Status">
          <table className="cra-limits-table" style={{ width: '100%', borderCollapse: 'collapse' }}>
            <tbody>
              <tr>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Last Scan</td>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>
                  {stats.last_scan_at ? new Date(stats.last_scan_at).toLocaleString() : 'No scans yet'}
                </td>
              </tr>
              <tr>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Next Scan</td>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>
                  {stats.next_scan_at ? new Date(stats.next_scan_at).toLocaleString() : '—'}
                </td>
              </tr>
              <tr>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Scans This Month</td>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>
                  {stats.scans_this_month ?? 0} / {currentLimits.max_scans_per_month}
                </td>
              </tr>
              <tr>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb' }}>Email Alerts</td>
                <td style={{ padding: '8px 0', borderBottom: '1px solid #e5e7eb', textAlign: 'right', fontWeight: 600 }}>
                  <span style={{ color: currentLimits.email_alerts ? 'var(--cra-green)' : 'var(--cra-muted)' }}>
                    {currentLimits.email_alerts ? 'Active' : 'Not available on your plan'}
                  </span>
                </td>
              </tr>
              <tr>
                <td style={{ padding: '8px 0' }}>Monitored Plugins</td>
                <td style={{ padding: '8px 0', textAlign: 'right', fontWeight: 600 }}>
                  {stats.total_plugins ?? 0} / {currentLimits.max_plugins}
                </td>
              </tr>
            </tbody>
          </table>
        </Card>
      )}

      <Card title="API Key" description="Enter your API key to connect to the ResilienceWP scanning service.">
        <div className="cra-form">
          <div className="cra-form-field">
            <label htmlFor="api-key">API Key</label>
            {maskedKey && !editingKey ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <code className="cra-input" style={{ flex: 1, background: '#f9fafb', color: '#6b7280', cursor: 'default' }}>
                  {maskedKey}
                </code>
                <button
                  className="cra-btn cra-btn-sm"
                  onClick={() => {
                    setApiKeyInput(savedApiKey);
                    setEditingKey(true);
                    setMessage(null);
                  }}
                >
                  Change
                </button>
              </div>
            ) : (
              <div style={{ display: 'flex', gap: '8px' }}>
                <input
                  id="api-key"
                  type="text"
                  value={apiKeyInput}
                  onChange={(e) => setApiKeyInput(e.target.value)}
                  placeholder="cra_xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                  className="cra-input"
                  style={{ flex: 1 }}
                />
                <button
                  className="cra-btn cra-btn-primary"
                  onClick={verifyAndSave}
                  disabled={verifying}
                >
                  {verifying ? 'Verifying...' : 'Verify & Save'}
                </button>
                {savedApiKey && editingKey && (
                  <button
                    className="cra-btn cra-btn-sm"
                    onClick={() => {
                      setApiKeyInput(savedApiKey);
                      setEditingKey(false);
                      setMessage(null);
                    }}
                  >
                    Cancel
                  </button>
                )}
              </div>
            )}
            <p className="cra-field-help">
              You'll receive your API key via email after purchasing a plan.
            </p>
          </div>

          {message && (
            <div className={`cra-alert cra-alert-${message.type === 'success' ? 'success' : 'error'}`}>
              {message.text}
            </div>
          )}

          {savedApiKey && !editingKey && (
            <button className="cra-btn cra-btn-sm cra-btn-danger" onClick={clearApiKey}>
              Disconnect & Clear API Key
            </button>
          )}
        </div>
      </Card>

      {config.plan === 'pro' && (
        <WebhookSettings />
      )}

      <Card title="About">
        <div className="cra-about">
          <p>
            <strong>ResilienceWP</strong> v{config.version}
          </p>
          <p>
            Helping WordPress plugin developers comply with the EU Cyber Resilience Act.
          </p>
          <p className="cra-muted">
            This plugin is not legal advice. Consult with a legal professional for
            compliance questions specific to your situation.
          </p>
        </div>
      </Card>

      {config.plan !== 'pro' && config.plan !== 'free' && (
        <Card title="Webhook Integrations">
          <p style={{ color: 'var(--cra-muted)', fontSize: 14 }}>
            Webhook integrations are available on the Pro plan. Receive HTTP callbacks when scans complete or
            vulnerabilities are found — ideal for CI/CD pipelines and external monitoring.{' '}
            <a href="https://www.resiliencewp.com/pricing" target="_blank" rel="noopener noreferrer">
              Upgrade to Pro &rarr;
            </a>
          </p>
        </Card>
      )}

      {isDevMode() && (
        <Card title="Developer Tools" description="These controls are only visible in development mode.">
          <div className="cra-form-field">
            <label>Plan Override</label>
            <p className="cra-field-help">
              Switch between plans to test how the plugin behaves on each tier.
            </p>
            <div className="cra-plan-toggle">
              {(['free', 'basic', 'pro'] as const).map((plan) => {
                const currentOverride = localStorage.getItem(PLAN_OVERRIDE_KEY);
                const isActive = currentOverride === plan;
                return (
                  <button
                    key={plan}
                    className={`cra-btn cra-btn-sm${isActive ? ' cra-btn-primary' : ''}`}
                    onClick={() => {
                      if (isActive) {
                        localStorage.removeItem(PLAN_OVERRIDE_KEY);
                      } else {
                        localStorage.setItem(PLAN_OVERRIDE_KEY, plan);
                      }
                      dispatchPlanChange();
                    }}
                  >
                    {plan.toUpperCase()}
                  </button>
                );
              })}
              {localStorage.getItem(PLAN_OVERRIDE_KEY) && (
                <button
                  className="cra-btn cra-btn-sm cra-btn-danger"
                  onClick={() => {
                    localStorage.removeItem(PLAN_OVERRIDE_KEY);
                    dispatchPlanChange();
                  }}
                >
                  Clear Override
                </button>
              )}
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}

const ALL_EVENTS: { value: WebhookEventType; label: string }[] = [
  { value: 'scan.completed', label: 'Scan completed' },
  { value: 'vulnerability.found', label: 'Vulnerability found' },
];

function WebhookSettings() {
  const [showForm, setShowForm] = useState(false);
  const [url, setUrl] = useState('');
  const [secret, setSecret] = useState('');
  const [events, setEvents] = useState<WebhookEventType[]>(['scan.completed', 'vulnerability.found']);
  const [error, setError] = useState<string | null>(null);

  const { data: webhooks = [], refetch } = useQuery<UserWebhook[]>({
    queryKey: ['webhooks'],
    queryFn: async () => {
      const res = await externalApiFetch<{ success: boolean; data: UserWebhook[] }>('/api/webhooks');
      return res.data ?? [];
    },
    staleTime: 30 * 1000,
    retry: 1,
  });

  const createMutation = useMutation({
    mutationFn: async () => {
      const res = await externalApiFetch<{ data: UserWebhook; error?: string }>('/api/webhooks', {
        method: 'POST',
        body: JSON.stringify({ url, secret: secret || undefined, events }),
      });
      if (!res.data && (res as { error?: string }).error) {
        throw new Error((res as { error?: string }).error);
      }
      return res.data;
    },
    onSuccess: () => {
      void refetch();
      setShowForm(false);
      setUrl('');
      setSecret('');
      setEvents(['scan.completed', 'vulnerability.found']);
      setError(null);
    },
    onError: (err: Error) => setError(err.message),
  });

  const toggleMutation = useMutation({
    mutationFn: async ({ id, active }: { id: string; active: boolean }) => {
      await externalApiFetch('/api/webhooks', {
        method: 'PATCH',
        body: JSON.stringify({ id, active }),
      });
    },
    onSuccess: () => void refetch(),
  });

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      await externalApiFetch(`/api/webhooks?id=${id}`, { method: 'DELETE' });
    },
    onSuccess: () => void refetch(),
  });

  const testMutation = useMutation({
    mutationFn: async () => {
      await externalApiFetch('/api/dashboard',  { method: 'POST', body: JSON.stringify({ action: 'webhook_test' }) });
    },
  });

  const toggleEvent = (event: WebhookEventType) => {
    setEvents((prev) =>
      prev.includes(event) ? prev.filter((e) => e !== event) : [...prev, event],
    );
  };

  return (
    <Card title="Webhook Integrations" description="Receive HTTP callbacks when scans complete or new vulnerabilities are found.">
      {webhooks.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          {webhooks.map((wh) => (
            <div
              key={wh.id}
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '10px 0',
                borderBottom: '1px solid #e5e7eb',
                gap: 8,
              }}
            >
              <div style={{ flex: 1, minWidth: 0 }}>
                <code style={{ fontSize: 13, wordBreak: 'break-all' }}>{wh.url}</code>
                <div style={{ fontSize: 12, color: 'var(--cra-muted)', marginTop: 2 }}>
                  {wh.events.join(', ')}
                </div>
              </div>
              <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
                <button
                  className={`cra-btn cra-btn-sm${wh.active ? '' : ' cra-btn-primary'}`}
                  onClick={() => toggleMutation.mutate({ id: wh.id, active: !wh.active })}
                >
                  {wh.active ? 'Pause' : 'Enable'}
                </button>
                <button
                  className="cra-btn cra-btn-sm cra-btn-danger"
                  onClick={() => deleteMutation.mutate(wh.id)}
                >
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {!showForm ? (
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="cra-btn cra-btn-primary" onClick={() => setShowForm(true)}>
            Add Webhook
          </button>
          {webhooks.length > 0 && (
            <button
              className="cra-btn cra-btn-sm"
              onClick={() => testMutation.mutate()}
              disabled={testMutation.isPending}
            >
              {testMutation.isPending ? 'Sending...' : 'Send Test'}
            </button>
          )}
        </div>
      ) : (
        <div className="cra-form">
          <div className="cra-form-field">
            <label>URL (HTTPS required)</label>
            <input
              type="url"
              className="cra-input"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="https://example.com/webhook"
            />
          </div>
          <div className="cra-form-field">
            <label>Signing Secret (optional)</label>
            <input
              type="text"
              className="cra-input"
              value={secret}
              onChange={(e) => setSecret(e.target.value)}
              placeholder="Your HMAC signing secret"
            />
            <p className="cra-field-help">If set, each delivery includes an X-Webhook-Signature header (HMAC-SHA256).</p>
          </div>
          <div className="cra-form-field">
            <label>Events</label>
            <div style={{ display: 'flex', gap: 12 }}>
              {ALL_EVENTS.map((evt) => (
                <label key={evt.value} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 14, cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={events.includes(evt.value)}
                    onChange={() => toggleEvent(evt.value)}
                  />
                  {evt.label}
                </label>
              ))}
            </div>
          </div>
          {error && <div className="cra-alert cra-alert-error">{error}</div>}
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              className="cra-btn cra-btn-primary"
              onClick={() => createMutation.mutate()}
              disabled={createMutation.isPending || !url || events.length === 0}
            >
              {createMutation.isPending ? 'Saving...' : 'Save Webhook'}
            </button>
            <button className="cra-btn cra-btn-sm" onClick={() => { setShowForm(false); setError(null); }}>
              Cancel
            </button>
          </div>
        </div>
      )}

      <details style={{ marginTop: 16, fontSize: 13, color: 'var(--cra-muted)' }}>
        <summary style={{ cursor: 'pointer', fontWeight: 600, fontSize: 13, marginBottom: 8 }}>
          Payload structure
        </summary>
        <p style={{ margin: '0 0 8px' }}>
          Each delivery is an HTTP POST with <code>Content-Type: application/json</code>.
          If a signing secret is set, the <code>X-Webhook-Signature</code> header contains <code>sha256=&lt;hmac&gt;</code>.
        </p>
        <p style={{ margin: '0 0 4px', fontWeight: 600 }}>scan.completed</p>
        <pre style={{ background: 'var(--cra-bg)', padding: 10, borderRadius: 6, overflow: 'auto', fontSize: 11.5, margin: '0 0 12px', border: '1px solid var(--cra-border)' }}>{`{
  "event": "scan.completed",
  "timestamp": "2026-03-10T12:00:00.000Z",
  "data": {
    "scan_id": "uuid",
    "plugin_slug": "my-plugin",
    "plugin_name": "My Plugin",
    "vulnerabilities_found": 2,
    "new_vulnerabilities": 1,
    "status": "vulnerable"
  }
}`}</pre>
        <p style={{ margin: '0 0 4px', fontWeight: 600 }}>vulnerability.found</p>
        <pre style={{ background: 'var(--cra-bg)', padding: 10, borderRadius: 6, overflow: 'auto', fontSize: 11.5, margin: '0 0 8px', border: '1px solid var(--cra-border)' }}>{`{
  "event": "vulnerability.found",
  "timestamp": "2026-03-10T12:00:00.000Z",
  "data": {
    "plugin_slug": "my-plugin",
    "plugin_name": "My Plugin",
    "vulnerabilities": [
      {
        "title": "SQL Injection in REST endpoint",
        "severity": "critical",
        "cve_id": "CVE-2026-12345",
        "fixed_in_version": "2.1.0"
      }
    ]
  }
}`}</pre>
        <p style={{ margin: 0, fontSize: 12 }}>
          Test endpoint: point a webhook URL to{' '}
          <code>https://api.resiliencewp.com/api/dashboard</code>{' '}
          to inspect delivered payloads.
        </p>
      </details>
    </Card>
  );
}
