import React, { useEffect, useMemo, useState } from 'react';
import { useAuth } from '../auth/AuthProvider';
import { getServices, getService } from '../services/serviceCatalog';
import { callApi } from '../services/apiClient';
import CreativePreview from './CreativePreview';
import AudiencePreview from './AudiencePreview';

// localStorage key for persisting tenant ID
const TENANT_STORAGE_KEY = 'adp_tenantId';

export default function ServiceForm({ initialProvider }) {
  const { sessionUser, getIdToken, getAccessToken } = useAuth();
  
  const providerId = initialProvider || 'gateway';

  const services = useMemo(() => getServices(providerId), [providerId]);
  const [serviceId, setServiceId] = useState(services?.[0]?.id || '');

  const [input, setInput] = useState('{}');
  const [resp, setResp] = useState(null);
  const [isBusy, setIsBusy] = useState(false);

  // Tenant ID - persisted for convenience
  const [tenantId, setTenantId] = useState(() => 
    localStorage.getItem(TENANT_STORAGE_KEY) || ''
  );

  // Get current service definition for display
  const currentService = useMemo(() => getService(providerId, serviceId), [providerId, serviceId]);

  // Persist tenant ID changes
  useEffect(() => {
    localStorage.setItem(TENANT_STORAGE_KEY, tenantId);
  }, [tenantId]);

  // Reset service selection + sample when provider changes
  useEffect(() => {
    const newServices = getServices(providerId);
    const firstService = newServices?.[0];
    setServiceId(firstService?.id || '');
    if (firstService?.sample) {
      setInput(JSON.stringify(firstService.sample, null, 2));
    }
    setResp(null);
  }, [providerId]);

  // Update sample input when service changes
  useEffect(() => {
    const service = getService(providerId, serviceId);
    if (service?.sample) {
      setInput(JSON.stringify(service.sample, null, 2));
    }
  }, [serviceId, providerId]);

  const submit = async () => {
    setIsBusy(true);
    setResp(null);
    try {
      const token = await getIdToken();
      const entraToken = await getAccessToken();
      const authConfig = {
        sessionToken: token,       // Gateway + provider calls
        entraToken:   entraToken,  // Management / staff-plane calls
        tenantId: tenantId.trim() || undefined,
      };
      const result = await callApi(providerId, serviceId, input, authConfig);
      setResp(result);
    } catch (e) {
      setResp({ ok: false, error: e?.message || String(e) });
    } finally {
      setIsBusy(false);
    }
  };

  // Tenant ID placeholder varies by provider
  const tenantPlaceholder = {
    google: 'Google Ads Customer ID (e.g. 1234567890)',
    meta: 'Meta Ad Account ID (e.g. act_123456789)',
    tiktok: 'TikTok Advertiser ID (e.g. 7123456789012345678)',
    creative: 'Not required for Creative',
    gateway: 'Not required for Gateway direct calls',
  }[providerId] || 'Account ID (optional)';

  const showTenant = providerId !== 'gateway';

  return (
    <div className="service-form">
      {/* Tenant Configuration */}
      {showTenant && (
        <fieldset className="auth-section">
          <legend>Target Account</legend>
          <div className="row row-inline">
            <label>Tenant ID</label>
            <input 
              type="text" 
              value={tenantId} 
              onChange={(e) => setTenantId(e.target.value)}
              placeholder={tenantPlaceholder}
            />
          </div>
        </fieldset>
      )}

      {/* Operation selector */}
      <div className="row">
        <label>Operation</label>
        <select value={serviceId} onChange={(e) => setServiceId(e.target.value)}>
          {services.map(s => (
            <option key={s.id} value={s.id}>{s.label}</option>
          ))}
        </select>
      </div>

      {/* Routing indicator for provider calls */}
      {currentService && !currentService.endpoint && (
        <div className="row routing-info">
          <span className="route-badge">
            <strong>Route:</strong> Gateway → {providerId} → {currentService.service}.{currentService.action}
          </span>
        </div>
      )}

      {/* Endpoint indicator for direct gateway calls */}
      {currentService?.endpoint && (
        <div className="row routing-info">
          <span className="route-badge route-direct">
            <strong>Direct:</strong> {currentService.method} {currentService.endpoint}
          </span>
        </div>
      )}

      <div className="row">
        <label>Payload (JSON)</label>
        <textarea rows={10} value={input} onChange={(e) => setInput(e.target.value)} />
      </div>

      <button className="submit-btn" onClick={submit} disabled={!serviceId || isBusy}>
        {isBusy ? 'Calling…' : 'Submit'}
      </button>

      {resp && (
        <div className="response-section">
          {/* Status badge */}
          <div className={`response-status ${resp.ok !== false ? 'status-ok' : 'status-fail'}`}>
            {resp.ok !== false ? '✓ Success' : '✗ Error'}
          </div>

          {/* Visual Preview for Creative responses */}
          {providerId === 'creative' && resp.ok && (
            <CreativePreview data={resp} />
          )}
          
          {/* Visual Preview for Audience responses */}
          {providerId === 'google' && currentService?.service === 'audience' && resp.ok && (
            <AudiencePreview data={resp} />
          )}
          
          {/* Raw JSON response */}
          <details className="json-details" open={
            (providerId !== 'creative' && currentService?.service !== 'audience') || !resp.ok
          }>
            <summary>Raw JSON Response</summary>
            <pre className="response">{JSON.stringify(resp, null, 2)}</pre>
          </details>
        </div>
      )}
    </div>
  );
}
