'use client';

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

const ALL_SCOPES = [
  'clients:read',
  'clients:write',
  'trainings:read',
  'trainings:write',
  'sales:read',
  'sales:write',
  'funnel:read',
  'funnel:write',
  'stats:read',
  'webhooks:manage',
] as const;

type CreateApiKeyResponse = {
  id: string;
  name: string;
  key: string;
  scopes: string[];
};

type CreateApiKeyDialogProps = {
  open: boolean;
  onClose: () => void;
  onCreated: () => void;
};

export function CreateApiKeyDialog({ open, onClose, onCreated }: CreateApiKeyDialogProps) {
  const [step, setStep] = useState<'form' | 'result'>('form');
  const [name, setName] = useState('');
  const [scopes, setScopes] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [createdKey, setCreatedKey] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const reset = () => {
    setStep('form');
    setName('');
    setScopes([]);
    setLoading(false);
    setError(null);
    setCreatedKey(null);
    setCopied(false);
  };

  const handleClose = () => {
    if (step === 'result') {
      onCreated();
    }
    reset();
    onClose();
  };

  const toggleScope = (scope: string) => {
    setScopes((prev) =>
      prev.includes(scope)
        ? prev.filter((s) => s !== scope)
        : [...prev, scope],
    );
  };

  const handleSubmit = async () => {
    if (!name.trim()) {
      setError('Введите название ключа');
      return;
    }
    if (scopes.length === 0) {
      setError('Выберите хотя бы один scope');
      return;
    }

    setLoading(true);
    setError(null);
    try {
      const res = await api.post<CreateApiKeyResponse>('/auth/api-keys', {
        name: name.trim(),
        scopes,
      });
      setCreatedKey(res.key);
      setStep('result');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось создать ключ');
    } finally {
      setLoading(false);
    }
  };

  const handleCopy = async () => {
    if (!createdKey) return;
    try {
      await navigator.clipboard.writeText(createdKey);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard API not available
    }
  };

  return (
    <Dialog open={open} onClose={handleClose}>
      {step === 'form' ? (
        <>
          <DialogHeader
            title="Создать API-ключ"
            description="Укажите название и права доступа для нового ключа"
            onClose={handleClose}
          />
          <DialogBody>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Название
                </label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Например: Интеграция с 1С"
                  className="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"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Права доступа (scopes)
                </label>
                <div className="grid grid-cols-2 gap-2">
                  {ALL_SCOPES.map((scope) => (
                    <label
                      key={scope}
                      className="flex items-center gap-2 p-2 rounded-lg border border-border hover:bg-gray-50 cursor-pointer transition-colors"
                    >
                      <input
                        type="checkbox"
                        checked={scopes.includes(scope)}
                        onChange={() => toggleScope(scope)}
                        className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary/30"
                      />
                      <span className="text-xs font-mono text-gray-700">{scope}</span>
                    </label>
                  ))}
                </div>
              </div>

              {error && (
                <p className="text-sm text-error">{error}</p>
              )}
            </div>
          </DialogBody>
          <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 handleSubmit()}
              disabled={loading}
              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>
        </>
      ) : (
        <>
          <DialogHeader
            title="Ключ создан"
            description="Скопируйте ключ сейчас. Он больше не будет показан."
            onClose={handleClose}
          />
          <DialogBody>
            <div className="space-y-4">
              <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3">
                <p className="text-sm text-yellow-800 font-medium">
                  Сохраните этот ключ в надёжном месте. После закрытия окна он будет недоступен.
                </p>
              </div>
              <div className="flex items-center gap-2">
                <code className="flex-1 text-xs bg-gray-100 px-3 py-2.5 rounded-lg font-mono text-gray-900 break-all select-all">
                  {createdKey}
                </code>
                <button
                  onClick={() => void handleCopy()}
                  className="shrink-0 p-2.5 rounded-lg border border-border hover:bg-gray-50 transition-colors"
                  title="Копировать"
                >
                  {copied ? (
                    <Check className="h-4 w-4 text-success" />
                  ) : (
                    <Copy className="h-4 w-4 text-muted" />
                  )}
                </button>
              </div>
            </div>
          </DialogBody>
          <DialogFooter>
            <button
              onClick={handleClose}
              className="bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
            >
              Закрыть
            </button>
          </DialogFooter>
        </>
      )}
    </Dialog>
  );
}
