'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  Plug,
  Phone,
  Webhook,
  KeyRound,
  CheckCircle,
  XCircle,
  Eye,
  EyeOff,
  Copy,
  RefreshCw,
} from 'lucide-react';
import { api } from '@/lib/api';
import { AlertDialog } from '@/components/ui/alert-dialog';
import { CreateApiKeyDialog } from '@/components/integrations/create-api-key-dialog';
import { ConfigureIntegrationDialog } from '@/components/integrations/configure-integration-dialog';

type IntegrationStatus = 'connected' | 'disconnected' | 'error';

type IntegrationConfig = {
  id: string;
  name: string;
  description: string;
  status: IntegrationStatus;
  lastSync?: string;
};

type WebhookEntry = {
  id: string;
  url: string;
  events: string[];
  active: boolean;
};

type WebhooksResponse = {
  data: WebhookEntry[];
  hasMore: boolean;
  nextCursor: string | null;
};

type ApiKey = {
  id: string;
  name: string;
  key: string;
  scopes: string[];
  createdAt: string;
  lastUsed: string;
};

type ApiKeysResponse = {
  data: ApiKey[];
};

type SipSettings = {
  enabled?: boolean;
  status?: IntegrationStatus;
};

const integrationIcons: Record<string, typeof Plug> = {
  '1c': Plug,
  sip: Phone,
  webhooks: Webhook,
};

const statusConfig: Record<IntegrationStatus, { label: string; className: string; icon: typeof CheckCircle }> = {
  connected: { label: 'Подключено', className: 'text-success', icon: CheckCircle },
  disconnected: { label: 'Отключено', className: 'text-muted', icon: XCircle },
  error: { label: 'Ошибка', className: 'text-error', icon: XCircle },
};

const defaultIntegrations: IntegrationConfig[] = [
  { id: '1c', name: '1C:Фитнес клуб', description: 'Двусторонняя синхронизация клиентов, членств, продаж и графика работы', status: 'disconnected' },
  { id: 'sip', name: 'SIP-телефония', description: 'Встроенный SIP-клиент для исходящих звонков с CallerID клуба', status: 'disconnected' },
  { id: 'webhooks', name: 'Webhooks', description: '12 типов исходящих событий для внешних интеграций (HMAC-SHA256)', status: 'disconnected' },
];

export default function IntegrationsPage(): React.JSX.Element {
  const [showKey, setShowKey] = useState<string | null>(null);
  const [integrations, setIntegrations] = useState<IntegrationConfig[]>(defaultIntegrations);
  const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showCreateKeyDialog, setShowCreateKeyDialog] = useState(false);
  const [configureIntegration, setConfigureIntegration] = useState<{ id: string; name: string } | null>(null);
  const [regenerateKeyId, setRegenerateKeyId] = useState<string | null>(null);

  const loadData = useCallback(() => {
    setLoading(true);
    setError(null);
    void Promise.all([
      api.get<IntegrationConfig>('/integration/config')
        .then((config) => {
          setIntegrations((prev) =>
            prev.map((item) => {
              if (item.id === '1c') {
                return {
                  ...item,
                  status: (config as Record<string, unknown>).status as IntegrationStatus ?? item.status,
                  lastSync: (config as Record<string, unknown>).lastSync as string | undefined,
                };
              }
              return item;
            })
          );
        })
        .catch(() => {}),
      api.get<SipSettings>('/sip/settings')
        .then((sipConfig) => {
          setIntegrations((prev) =>
            prev.map((item) => {
              if (item.id === 'sip') {
                return {
                  ...item,
                  status: sipConfig.enabled ? 'connected' : 'disconnected',
                };
              }
              return item;
            })
          );
        })
        .catch(() => {}),
      api.get<WebhooksResponse>('/webhooks')
        .then((res) => {
          const hasActive = (res.data ?? []).some((w) => w.active);
          setIntegrations((prev) =>
            prev.map((item) => {
              if (item.id === 'webhooks') {
                return {
                  ...item,
                  status: hasActive ? 'connected' : 'disconnected',
                };
              }
              return item;
            })
          );
        })
        .catch(() => {}),
      api.get<ApiKeysResponse>('/auth/api-keys')
        .then((res) => setApiKeys(res.data ?? []))
        .catch(() => setApiKeys([])),
    ])
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Не удалось загрузить данные');
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const handleCopyKey = async (key: string) => {
    try {
      await navigator.clipboard.writeText(key);
    } catch {
      // Clipboard API not available
    }
  };

  const handleRegenerateKey = async () => {
    if (!regenerateKeyId) return;
    await api.post(`/auth/api-keys/${regenerateKeyId}/regenerate`);
    setRegenerateKeyId(null);
    loadData();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={loadData}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Интеграции</h1>

      <div className="space-y-6 mb-10">
        {integrations.map((integration) => {
          const Icon = integrationIcons[integration.id] ?? Plug;
          const status = statusConfig[integration.status];
          const StatusIcon = status.icon;
          return (
            <div
              key={integration.id}
              className="bg-card rounded-xl p-6 shadow-sm border border-border"
            >
              <div className="flex items-start justify-between">
                <div className="flex items-start gap-4">
                  <div className="bg-orange-50 text-primary p-3 rounded-lg">
                    <Icon className="h-6 w-6" />
                  </div>
                  <div>
                    <h3 className="text-base font-semibold text-gray-900">
                      {integration.name}
                    </h3>
                    <p className="text-sm text-gray-600 mt-1">
                      {integration.description}
                    </p>
                    {integration.lastSync && (
                      <p className="text-xs text-muted mt-2">
                        Последняя синхронизация: {integration.lastSync}
                      </p>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-3 shrink-0">
                  <span className={`flex items-center gap-1.5 text-sm font-medium ${status.className}`}>
                    <StatusIcon className="h-4 w-4" />
                    {status.label}
                  </span>
                  <button
                    onClick={() => setConfigureIntegration({ id: integration.id, name: integration.name })}
                    className="px-4 py-2 rounded-lg border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                  >
                    Настроить
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900">API-ключи</h2>
          <button
            onClick={() => setShowCreateKeyDialog(true)}
            className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            <KeyRound className="h-4 w-4" />
            Создать ключ
          </button>
        </div>

        <div className="space-y-4">
          {apiKeys.length === 0 && (
            <div className="text-center py-8 text-muted text-sm">
              Нет API-ключей. Создайте первый ключ для доступа к API.
            </div>
          )}
          {apiKeys.map((apiKey) => (
            <div
              key={apiKey.id}
              className="bg-card rounded-xl p-6 shadow-sm border border-border"
            >
              <div className="flex items-start justify-between mb-3">
                <div>
                  <h3 className="text-sm font-semibold text-gray-900">
                    {apiKey.name}
                  </h3>
                  <div className="flex items-center gap-2 mt-2">
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded font-mono text-gray-700">
                      {showKey === apiKey.id ? apiKey.key : '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'}
                    </code>
                    <button
                      onClick={() => setShowKey(showKey === apiKey.id ? null : apiKey.id)}
                      className="p-1 rounded hover:bg-gray-100"
                    >
                      {showKey === apiKey.id ? (
                        <EyeOff className="h-3.5 w-3.5 text-muted" />
                      ) : (
                        <Eye className="h-3.5 w-3.5 text-muted" />
                      )}
                    </button>
                    <button
                      onClick={() => void handleCopyKey(apiKey.key)}
                      className="p-1 rounded hover:bg-gray-100"
                    >
                      <Copy className="h-3.5 w-3.5 text-muted" />
                    </button>
                  </div>
                </div>
                <button
                  onClick={() => setRegenerateKeyId(apiKey.id)}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-border text-xs font-medium text-gray-700 hover:bg-gray-50"
                >
                  <RefreshCw className="h-3 w-3" />
                  Перевыпустить
                </button>
              </div>

              <div className="flex flex-wrap gap-1.5 mb-3">
                {apiKey.scopes.map((scope) => (
                  <span
                    key={scope}
                    className="bg-blue-50 text-blue-700 px-2 py-0.5 rounded text-xs font-mono"
                  >
                    {scope}
                  </span>
                ))}
              </div>

              <div className="flex gap-4 text-xs text-muted">
                <span>Создан: {apiKey.createdAt}</span>
                <span>Последнее использование: {apiKey.lastUsed}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      <CreateApiKeyDialog
        open={showCreateKeyDialog}
        onClose={() => setShowCreateKeyDialog(false)}
        onCreated={loadData}
      />

      <ConfigureIntegrationDialog
        open={configureIntegration !== null}
        onClose={() => setConfigureIntegration(null)}
        onSaved={loadData}
        integration={configureIntegration}
      />

      <AlertDialog
        open={regenerateKeyId !== null}
        onClose={() => setRegenerateKeyId(null)}
        onConfirm={handleRegenerateKey}
        title="Перевыпустить API-ключ"
        description="Текущий ключ будет отозван и заменён новым. Все интеграции, использующие старый ключ, перестанут работать. Продолжить?"
        confirmLabel="Перевыпустить"
        variant="warning"
      />
    </div>
  );
}
