"use client";

import {
  Zap,
  Phone,
  MessageSquare,
  RefreshCw,
  Copy,
  Check,
} from "lucide-react";
import { IntegrationsState } from "./types";

interface IntegrationsTabProps {
  integrations: IntegrationsState;
  submitting: boolean;
  generatingToken: boolean;
  copiedText: string | null;
  onIntegrationsChange: (integrations: IntegrationsState) => void;
  onGenerateToken: () => void;
  onRevokeToken: () => void;
  onSaveIntegrations: () => void;
  onCopyToClipboard: (text: string) => void;
}

export function IntegrationsTab({
  integrations,
  submitting,
  generatingToken,
  copiedText,
  onIntegrationsChange,
  onGenerateToken,
  onRevokeToken,
  onSaveIntegrations,
  onCopyToClipboard,
}: IntegrationsTabProps) {
  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-lg font-semibold text-brand-ink">
          Integration Settings
        </h3>
        <p className="text-sm text-gray-600 mt-1">
          Configure N8N workflows, voice agents, and other integrations for this
          user&apos;s dashboard.
        </p>
      </div>

      {/* N8N Webhook Token */}
      <N8NWebhookSection
        token={integrations.n8nWebhookToken}
        generatingToken={generatingToken}
        submitting={submitting}
        copiedText={copiedText}
        onGenerateToken={onGenerateToken}
        onRevokeToken={onRevokeToken}
        onCopyToClipboard={onCopyToClipboard}
      />

      {/* Voice Agent Configuration */}
      <VoiceAgentSection
        voiceAgentId={integrations.voiceAgentId}
        voiceAgentConfig={integrations.voiceAgentConfig}
        onVoiceAgentIdChange={(value) =>
          onIntegrationsChange({ ...integrations, voiceAgentId: value })
        }
        onVoiceAgentConfigChange={(config) =>
          onIntegrationsChange({ ...integrations, voiceAgentConfig: config })
        }
      />

      {/* WhatsApp Configuration */}
      <WhatsAppSection
        voiceAgentConfig={integrations.voiceAgentConfig}
        onVoiceAgentConfigChange={(config) =>
          onIntegrationsChange({ ...integrations, voiceAgentConfig: config })
        }
      />

      {/* Save Button */}
      <div className="flex justify-end">
        <button
          onClick={onSaveIntegrations}
          disabled={submitting}
          className="flex items-center gap-2 px-6 py-2.5 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
        >
          {submitting ? "Saving..." : "Save Integration Settings"}
        </button>
      </div>
    </div>
  );
}

// Sub-components
function N8NWebhookSection({
  token,
  generatingToken,
  submitting,
  copiedText,
  onGenerateToken,
  onRevokeToken,
  onCopyToClipboard,
}: {
  token: string;
  generatingToken: boolean;
  submitting: boolean;
  copiedText: string | null;
  onGenerateToken: () => void;
  onRevokeToken: () => void;
  onCopyToClipboard: (text: string) => void;
}) {
  return (
    <div className="p-6 bg-white border border-gray-200 rounded-lg">
      <div className="flex items-center gap-3 mb-4">
        <div className="p-2 bg-blue-100 rounded-lg">
          <Zap className="w-5 h-5 text-blue-600" />
        </div>
        <div>
          <h4 className="font-semibold text-brand-ink">
            N8N Webhook Integration
          </h4>
          <p className="text-sm text-gray-600">
            Enable AI workflow automation via N8N
          </p>
        </div>
      </div>

      {token ? (
        <div className="space-y-4">
          <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
            <div className="flex items-center gap-2 mb-2">
              <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
              <span className="text-sm font-medium text-green-700">
                Token Active
              </span>
            </div>
            <div className="flex items-center gap-2">
              <code className="flex-1 text-xs bg-white px-2 py-1 rounded border border-green-200 overflow-hidden text-ellipsis">
                {token.substring(0, 20)}...
              </code>
              <button
                onClick={() => onCopyToClipboard(token)}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
              >
                {copiedText === token ? (
                  <Check className="w-4 h-4 text-green-600" />
                ) : (
                  <Copy className="w-4 h-4" />
                )}
              </button>
            </div>
          </div>
          <div className="flex gap-3">
            <button
              onClick={onGenerateToken}
              disabled={generatingToken}
              className="flex items-center gap-2 px-4 py-2 text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 disabled:opacity-50"
            >
              <RefreshCw
                className={`w-4 h-4 ${generatingToken ? "animate-spin" : ""}`}
              />
              Regenerate Token
            </button>
            <button
              onClick={onRevokeToken}
              disabled={submitting}
              className="flex items-center gap-2 px-4 py-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 disabled:opacity-50"
            >
              Revoke Token
            </button>
          </div>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="p-3 bg-gray-50 border border-gray-200 rounded-lg">
            <p className="text-sm text-gray-600">
              No webhook token configured. Generate one to enable N8N
              integrations.
            </p>
          </div>
          <button
            onClick={onGenerateToken}
            disabled={generatingToken}
            className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
          >
            <Zap
              className={`w-4 h-4 ${generatingToken ? "animate-spin" : ""}`}
            />
            {generatingToken ? "Generating..." : "Generate Token"}
          </button>
        </div>
      )}
    </div>
  );
}

function VoiceAgentSection({
  voiceAgentId,
  voiceAgentConfig,
  onVoiceAgentIdChange,
  onVoiceAgentConfigChange,
}: {
  voiceAgentId: string;
  voiceAgentConfig: Record<string, string>;
  onVoiceAgentIdChange: (value: string) => void;
  onVoiceAgentConfigChange: (config: Record<string, string>) => void;
}) {
  return (
    <div className="p-6 bg-white border border-gray-200 rounded-lg">
      <div className="flex items-center gap-3 mb-4">
        <div className="p-2 bg-purple-100 rounded-lg">
          <Phone className="w-5 h-5 text-purple-600" />
        </div>
        <div>
          <h4 className="font-semibold text-brand-ink">AI Voice Agent</h4>
          <p className="text-sm text-gray-600">
            Configure ElevenLabs voice agent for this user
          </p>
        </div>
      </div>

      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Voice Agent ID
          </label>
          <input
            type="text"
            value={voiceAgentId}
            onChange={(e) => onVoiceAgentIdChange(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="agent_xxxxx"
          />
          <p className="text-xs text-gray-500 mt-1">
            The ElevenLabs agent ID for this user
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Agent Phone Number
          </label>
          <input
            type="text"
            value={voiceAgentConfig?.phoneNumber || ""}
            onChange={(e) =>
              onVoiceAgentConfigChange({
                ...voiceAgentConfig,
                phoneNumber: e.target.value,
              })
            }
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="+1234567890"
          />
          <p className="text-xs text-gray-500 mt-1">
            The phone number assigned to this voice agent
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Greeting Message
          </label>
          <textarea
            value={voiceAgentConfig?.greeting || ""}
            onChange={(e) =>
              onVoiceAgentConfigChange({
                ...voiceAgentConfig,
                greeting: e.target.value,
              })
            }
            rows={2}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="Hello, this is the AI receptionist for..."
          />
        </div>
      </div>
    </div>
  );
}

function WhatsAppSection({
  voiceAgentConfig,
  onVoiceAgentConfigChange,
}: {
  voiceAgentConfig: Record<string, string>;
  onVoiceAgentConfigChange: (config: Record<string, string>) => void;
}) {
  return (
    <div className="p-6 bg-white border border-gray-200 rounded-lg">
      <div className="flex items-center gap-3 mb-4">
        <div className="p-2 bg-green-100 rounded-lg">
          <MessageSquare className="w-5 h-5 text-green-600" />
        </div>
        <div>
          <h4 className="font-semibold text-brand-ink">WhatsApp Integration</h4>
          <p className="text-sm text-gray-600">
            Configure WhatsApp Business API settings
          </p>
        </div>
      </div>

      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            WhatsApp Number
          </label>
          <input
            type="text"
            value={voiceAgentConfig?.whatsappNumber || ""}
            onChange={(e) =>
              onVoiceAgentConfigChange({
                ...voiceAgentConfig,
                whatsappNumber: e.target.value,
              })
            }
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="+1234567890"
          />
          <p className="text-xs text-gray-500 mt-1">
            The WhatsApp Business number for this user
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            Business Hours
          </label>
          <input
            type="text"
            value={voiceAgentConfig?.businessHours || ""}
            onChange={(e) =>
              onVoiceAgentConfigChange({
                ...voiceAgentConfig,
                businessHours: e.target.value,
              })
            }
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
            placeholder="Mon-Fri 9am-5pm"
          />
        </div>
      </div>
    </div>
  );
}
