'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';
import { api } from '@/lib/api';

type Integration = {
  id: string;
  name: string;
};

type ConfigureIntegrationDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  integration: Integration | null;
};

type OneCForm = {
  serverUrl: string;
  apiKey: string;
  syncInterval: number;
};

type SipForm = {
  host: string;
  port: number;
  username: string;
  password: string;
};

const inputClass =
  'w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary';

export function ConfigureIntegrationDialog({
  open,
  onClose,
  onSaved,
  integration,
}: ConfigureIntegrationDialogProps) {
  const [oneCForm, setOneCForm] = useState<OneCForm>({
    serverUrl: '',
    apiKey: '',
    syncInterval: 15,
  });
  const [sipForm, setSipForm] = useState<SipForm>({
    host: '',
    port: 5060,
    username: '',
    password: '',
  });
  const [loading, setLoading] = useState(false);
  const [loadingConfig, setLoadingConfig] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open || !integration) return;
    setError(null);

    if (integration.id === '1c') {
      setLoadingConfig(true);
      api.get<Record<string, unknown>>('/integration/config')
        .then((res) => {
          setOneCForm({
            serverUrl: (res.serverUrl as string) ?? '',
            apiKey: (res.apiKey as string) ?? '',
            syncInterval: (res.syncInterval as number) ?? 15,
          });
        })
        .catch(() => {
          // Use default empty form
        })
        .finally(() => setLoadingConfig(false));
    } else if (integration.id === 'sip') {
      setLoadingConfig(true);
      api.get<Record<string, unknown>>('/sip/settings')
        .then((res) => {
          setSipForm({
            host: (res.host as string) ?? '',
            port: (res.port as number) ?? 5060,
            username: (res.username as string) ?? '',
            password: '',
          });
        })
        .catch(() => {
          // Use default empty form
        })
        .finally(() => setLoadingConfig(false));
    }
  }, [open, integration]);

  const handleClose = () => {
    setError(null);
    setLoading(false);
    setLoadingConfig(false);
    onClose();
  };

  const handleSave = async () => {
    if (!integration) return;

    setLoading(true);
    setError(null);

    try {
      if (integration.id === '1c') {
        if (!oneCForm.serverUrl.trim()) {
          setError('Введите URL сервера');
          setLoading(false);
          return;
        }
        await api.patch('/integration/config', {
          serverUrl: oneCForm.serverUrl.trim(),
          apiKey: oneCForm.apiKey.trim(),
          syncInterval: oneCForm.syncInterval,
        });
      } else if (integration.id === 'sip') {
        if (!sipForm.host.trim()) {
          setError('Введите хост SIP-сервера');
          setLoading(false);
          return;
        }
        await api.patch('/sip/settings', {
          host: sipForm.host.trim(),
          port: sipForm.port,
          username: sipForm.username.trim(),
          password: sipForm.password || undefined,
        });
      }

      onSaved();
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось сохранить настройки');
    } finally {
      setLoading(false);
    }
  };

  if (!integration) return null;

  const title = `Настройка: ${integration.name}`;

  return (
    <Dialog open={open} onClose={handleClose}>
      <DialogHeader title={title} onClose={handleClose} />
      <DialogBody>
        {loadingConfig ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
          </div>
        ) : (
          <div className="space-y-4">
            {integration.id === '1c' && (
              <>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    URL сервера 1С
                  </label>
                  <input
                    type="text"
                    value={oneCForm.serverUrl}
                    onChange={(e) => setOneCForm((prev) => ({ ...prev, serverUrl: e.target.value }))}
                    placeholder="https://1c.example.com/api"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    API-ключ 1С
                  </label>
                  <input
                    type="text"
                    value={oneCForm.apiKey}
                    onChange={(e) => setOneCForm((prev) => ({ ...prev, apiKey: e.target.value }))}
                    placeholder="Ключ авторизации"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Интервал синхронизации (минуты)
                  </label>
                  <input
                    type="number"
                    min={1}
                    max={1440}
                    value={oneCForm.syncInterval}
                    onChange={(e) =>
                      setOneCForm((prev) => ({ ...prev, syncInterval: Number(e.target.value) || 15 }))
                    }
                    className={inputClass}
                  />
                </div>
              </>
            )}

            {integration.id === 'sip' && (
              <>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Хост SIP-сервера
                  </label>
                  <input
                    type="text"
                    value={sipForm.host}
                    onChange={(e) => setSipForm((prev) => ({ ...prev, host: e.target.value }))}
                    placeholder="sip.example.com"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Порт
                  </label>
                  <input
                    type="number"
                    min={1}
                    max={65535}
                    value={sipForm.port}
                    onChange={(e) =>
                      setSipForm((prev) => ({ ...prev, port: Number(e.target.value) || 5060 }))
                    }
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Имя пользователя
                  </label>
                  <input
                    type="text"
                    value={sipForm.username}
                    onChange={(e) => setSipForm((prev) => ({ ...prev, username: e.target.value }))}
                    placeholder="sip_user"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Пароль
                  </label>
                  <input
                    type="password"
                    value={sipForm.password}
                    onChange={(e) => setSipForm((prev) => ({ ...prev, password: e.target.value }))}
                    placeholder="Оставьте пустым, чтобы не менять"
                    className={inputClass}
                  />
                </div>
              </>
            )}

            {integration.id === 'webhooks' && (
              <div className="text-center py-6">
                <p className="text-sm text-gray-600">
                  Управление webhooks доступно через API.
                </p>
                <p className="text-xs text-muted mt-2">
                  Используйте API-ключ и эндпоинт <code className="bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono">/v1/webhooks</code> для создания и настройки webhook-подписок.
                </p>
              </div>
            )}

            {error && (
              <p className="text-sm text-error">{error}</p>
            )}
          </div>
        )}
      </DialogBody>
      {integration.id !== 'webhooks' && (
        <DialogFooter>
          <button
            onClick={handleClose}
            disabled={loading}
            className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Отмена
          </button>
          <button
            onClick={() => void handleSave()}
            disabled={loading || loadingConfig}
            className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            {loading ? 'Сохранение...' : 'Сохранить'}
          </button>
        </DialogFooter>
      )}
      {integration.id === 'webhooks' && (
        <DialogFooter>
          <button
            onClick={handleClose}
            className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Закрыть
          </button>
        </DialogFooter>
      )}
    </Dialog>
  );
}
