'use client';

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

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

function generateSlug(name: string): string {
  return name
    .toLowerCase()
    .trim()
    .replace(/[^a-zа-яё0-9\s-]/gi, '')
    .replace(/[а-яё]/gi, (ch) => {
      const map: Record<string, string> = {
        'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo',
        'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm',
        'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',
        'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'shch',
        'ъ': '', 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu', 'я': 'ya',
      };
      return map[ch.toLowerCase()] ?? '';
    })
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '');
}

const initialForm = {
  name: '',
  slug: '',
  address: '',
  phone: '',
  email: '',
  licenseType: 'STARTER' as 'STARTER' | 'STANDARD' | 'PREMIUM',
  maxUsers: 5,
  maxClients: 100,
};

export function CreateClubDialog({ open, onClose, onCreated }: CreateClubDialogProps) {
  const [form, setForm] = useState(initialForm);
  const [slugManual, setSlugManual] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      setForm(initialForm);
      setSlugManual(false);
      setError(null);
    }
  }, [open]);

  useEffect(() => {
    if (!slugManual) {
      setForm((prev) => ({ ...prev, slug: generateSlug(prev.name) }));
    }
  }, [form.name, slugManual]);

  const handleChange = (field: keyof typeof form, value: string | number) => {
    setForm((prev) => ({ ...prev, [field]: value }));
    setError(null);
  };

  const handleSlugChange = (value: string) => {
    setSlugManual(true);
    setForm((prev) => ({
      ...prev,
      slug: value
        .toLowerCase()
        .replace(/[^a-z0-9-]/g, '')
        .replace(/-+/g, '-'),
    }));
    setError(null);
  };

  const handleSubmit = async () => {
    if (!form.name.trim()) {
      setError('Введите название клуба');
      return;
    }
    if (!form.slug.trim()) {
      setError('Введите slug клуба');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const body: Record<string, unknown> = {
        name: form.name.trim(),
        slug: form.slug.trim(),
        licenseType: form.licenseType,
        maxUsers: form.maxUsers,
        maxClients: form.maxClients,
      };
      if (form.address.trim()) body.address = form.address.trim();
      if (form.phone.trim()) body.phone = form.phone.trim();
      if (form.email.trim()) body.email = form.email.trim();

      await api.post('/clubs', body);
      onCreated();
      onClose();
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка при создании клуба';
      setError(message);
    } finally {
      setLoading(false);
    }
  };

  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';

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogHeader
        title="Создание клуба"
        description="Заполните данные нового клуба"
        onClose={onClose}
      />
      <DialogBody className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Название <span className="text-error">*</span>
          </label>
          <input
            type="text"
            value={form.name}
            onChange={(e) => handleChange('name', e.target.value)}
            placeholder="Фитнес-клуб «Энергия»"
            className={inputClass}
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Slug <span className="text-error">*</span>
          </label>
          <input
            type="text"
            value={form.slug}
            onChange={(e) => handleSlugChange(e.target.value)}
            placeholder="fitness-klub-energiya"
            className={inputClass}
          />
          <p className="text-xs text-muted mt-1">
            Уникальный идентификатор (латиница, цифры, дефис)
          </p>
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Адрес
          </label>
          <input
            type="text"
            value={form.address}
            onChange={(e) => handleChange('address', e.target.value)}
            placeholder="г. Москва, ул. Примерная, д. 1"
            className={inputClass}
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Телефон
            </label>
            <input
              type="text"
              value={form.phone}
              onChange={(e) => handleChange('phone', e.target.value)}
              placeholder="+7 (999) 123-45-67"
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Email
            </label>
            <input
              type="email"
              value={form.email}
              onChange={(e) => handleChange('email', e.target.value)}
              placeholder="info@club.ru"
              className={inputClass}
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Тип лицензии
          </label>
          <select
            value={form.licenseType}
            onChange={(e) => handleChange('licenseType', e.target.value)}
            className={inputClass}
          >
            <option value="STARTER">Стартовая</option>
            <option value="STANDARD">Стандартная</option>
            <option value="PREMIUM">Премиум</option>
          </select>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Макс. пользователей
            </label>
            <input
              type="number"
              min={1}
              value={form.maxUsers}
              onChange={(e) => handleChange('maxUsers', parseInt(e.target.value, 10) || 1)}
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Макс. клиентов
            </label>
            <input
              type="number"
              min={1}
              value={form.maxClients}
              onChange={(e) => handleChange('maxClients', parseInt(e.target.value, 10) || 1)}
              className={inputClass}
            />
          </div>
        </div>

        {error && (
          <div className="rounded-lg bg-error/10 border border-error/20 px-3 py-2 text-sm text-error">
            {error}
          </div>
        )}
      </DialogBody>
      <DialogFooter>
        <button
          type="button"
          onClick={onClose}
          disabled={loading}
          className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-text hover:bg-background transition-colors"
        >
          Отмена
        </button>
        <button
          type="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>
    </Dialog>
  );
}
