/**
 * Connection Selector Component
 *
 * Dropdown for selecting which connection to use for an integration action.
 * Auto-selects when only one connection exists.
 * Shows nothing when no connections exist (action should show error).
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Label } from '../ui/label';
import { Loader2, AlertCircle } from 'lucide-react';
import { IntegrationConnection } from '../../types/integration';
import { getIntegrationService } from '../../services/integrations';

interface ConnectionSelectorProps {
  /** Integration slug (e.g., 'mailchimp', 'notion') */
  integration: string;
  /** Currently selected connection ID */
  value?: string;
  /** Callback when selection changes */
  onChange: (connectionId: string) => void;
  /** Whether the selector is disabled */
  disabled?: boolean;
  /** Optional label text */
  label?: string;
}

export function ConnectionSelector({
  integration,
  value,
  onChange,
  disabled = false,
  label = 'Account',
}: ConnectionSelectorProps) {
  const [connections, setConnections] = useState<IntegrationConnection[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Use ref to avoid infinite loops from onChange in dependencies
  const onChangeRef = useRef(onChange);
  onChangeRef.current = onChange;

  // Track if we've already auto-selected to prevent loops
  const hasAutoSelected = useRef(false);

  // Fetch connections for the integration
  const fetchConnections = useCallback(async () => {
    const service = getIntegrationService(integration);
    if (!service) {
      setError('Integration not found');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      const data = await service.listConnections();
      setConnections(data);

      // Auto-select if only one connection and no value selected
      if (data.length === 1 && !value && !hasAutoSelected.current) {
        hasAutoSelected.current = true;
        onChangeRef.current(data[0].id);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load connections');
    } finally {
      setLoading(false);
    }
  }, [integration, value]);

  useEffect(() => {
    hasAutoSelected.current = false;
    fetchConnections();
  }, [fetchConnections]);

  // Show read-only display if only one connection (auto-selected)
  if (!loading && connections.length === 1) {
    const connection = connections[0];
    return (
      <div className="space-y-2">
        <Label className="text-[13px] font-medium text-slate-700 tracking-tight">{label}</Label>
        <div className="flex items-center justify-between h-10 px-3 rounded-lg border border-slate-200 bg-slate-50/50">
          <span className="text-[13px] text-slate-600">{connection.label}</span>
          <a
            href="/wp-admin/admin.php?page=sequensy-workflows-integrations"
            className="text-[12px] text-cyan-600 hover:text-cyan-700 hover:underline"
          >
            Manage
          </a>
        </div>
      </div>
    );
  }

  // Show error state
  if (error) {
    return (
      <div className="space-y-2">
        <Label className="text-[13px] font-medium text-slate-700 tracking-tight">{label}</Label>
        <div className="flex items-start gap-2 rounded-lg bg-rose-50 border border-rose-100 px-3 py-2.5">
          <AlertCircle className="h-4 w-4 text-rose-500 mt-0.5 shrink-0" />
          <span className="text-[13px] text-rose-700 leading-snug">{error}</span>
        </div>
      </div>
    );
  }

  // Show loading state
  if (loading) {
    return (
      <div className="space-y-2">
        <Label className="text-[13px] font-medium text-slate-700 tracking-tight">{label}</Label>
        <div className="flex items-center gap-2.5 h-10 px-3 rounded-lg border border-slate-200 bg-slate-50/50">
          <Loader2 className="h-4 w-4 text-slate-400 animate-spin" />
          <span className="text-[13px] text-slate-400">Loading accounts...</span>
        </div>
      </div>
    );
  }

  // Show message if no connections
  if (connections.length === 0) {
    return (
      <div className="space-y-2">
        <Label className="text-[13px] font-medium text-slate-700 tracking-tight">{label}</Label>
        <div className="flex items-start gap-2 rounded-lg bg-rose-50 border border-rose-100 px-3 py-2.5">
          <AlertCircle className="h-4 w-4 text-rose-500 mt-0.5 shrink-0" />
          <span className="text-[13px] text-rose-700 leading-snug">
            No accounts connected. Please connect an account in Integrations settings.
          </span>
        </div>
      </div>
    );
  }

  // Render selector for multiple connections
  return (
    <div className="space-y-2">
      <Label className="text-[13px] font-medium text-slate-700 tracking-tight">{label}</Label>
      <Select value={value || ''} onValueChange={onChange} disabled={disabled}>
        <SelectTrigger className="w-full h-10 text-[13px] border-slate-200 hover:border-slate-300 focus:ring-2 focus:ring-cyan-500/20 focus:border-cyan-500 transition-colors duration-150">
          <SelectValue placeholder="Select an account..." />
        </SelectTrigger>
        <SelectContent>
          {connections.map((connection) => (
            <SelectItem key={connection.id} value={connection.id} className="text-[13px]">
              {connection.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <p className="text-[12px] text-slate-400 leading-relaxed">
        Choose which {integration} account to use for this action.
      </p>
    </div>
  );
}
