'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, Pencil, Trash2, Loader2, Shield, ShieldCheck } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';

interface RoleData {
  id: string;
  clubId: string | null;
  name: string;
  slug: string;
  isBuiltIn: boolean;
  isActive: boolean;
  userCount: number;
}

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 bg-background text-text';

export default function RolesSettingsPage() {
  const router = useRouter();
  const [roles, setRoles] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(true);

  // Create/rename form
  const [showForm, setShowForm] = useState(false);
  const [editingRole, setEditingRole] = useState<RoleData | null>(null);
  const [formName, setFormName] = useState('');
  const [formSlug, setFormSlug] = useState('');
  const [saving, setSaving] = useState(false);

  const fetchRoles = useCallback(async () => {
    try {
      const data = await api.get<RoleData[]>('/roles');
      setRoles(data);
    } catch {
      //
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void fetchRoles();
  }, [fetchRoles]);

  const openCreate = () => {
    setEditingRole(null);
    setFormName('');
    setFormSlug('');
    setShowForm(true);
  };

  const openRename = (role: RoleData) => {
    setEditingRole(role);
    setFormName(role.name);
    setFormSlug(role.slug);
    setShowForm(true);
  };

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

  const handleSave = async () => {
    if (!formName.trim()) return;
    setSaving(true);
    try {
      if (editingRole) {
        await api.patch(`/roles/${editingRole.id}`, { name: formName.trim() });
      } else {
        await api.post('/roles', { name: formName.trim(), slug: formSlug.trim() });
      }
      setShowForm(false);
      await fetchRoles();
    } catch (err: any) {
      alert(err?.message || 'Ошибка');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (role: RoleData) => {
    if (!confirm(`Удалить роль "${role.name}"? Это возможно только если нет назначений.`)) return;
    try {
      await api.delete(`/roles/${role.id}`);
      await fetchRoles();
    } catch (err: any) {
      alert(err?.message || 'Ошибка удаления');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center gap-3 mb-6">
        <button
          onClick={() => router.back()}
          className="p-2 rounded-lg hover:bg-background transition-colors"
        >
          <ArrowLeft className="h-5 w-5 text-muted" />
        </button>
        <div className="flex-1">
          <h1 className="text-xl font-bold text-text">Управление ролями</h1>
          <p className="text-sm text-muted">Системные и кастомные роли</p>
        </div>
        <button
          onClick={openCreate}
          className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Новая роль
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-background/50">
                <th className="text-left px-4 py-3 text-muted font-medium">Роль</th>
                <th className="text-left px-4 py-3 text-muted font-medium">Slug</th>
                <th className="text-center px-4 py-3 text-muted font-medium">Тип</th>
                <th className="text-center px-4 py-3 text-muted font-medium">Пользователей</th>
                <th className="text-right px-4 py-3 text-muted font-medium w-24">Действия</th>
              </tr>
            </thead>
            <tbody>
              {roles.map((role) => (
                <tr key={role.id} className="border-b border-border/50 group">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      {role.isBuiltIn ? (
                        <ShieldCheck className="h-4 w-4 text-primary" />
                      ) : (
                        <Shield className="h-4 w-4 text-muted" />
                      )}
                      <span className="font-medium text-text">{role.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-muted font-mono text-xs">{role.slug}</td>
                  <td className="px-4 py-3 text-center">
                    <span
                      className={cn(
                        'text-[10px] px-2 py-0.5 rounded-full',
                        role.isBuiltIn ? 'bg-primary/10 text-primary' : 'bg-background text-muted',
                      )}
                    >
                      {role.isBuiltIn ? 'Системная' : 'Кастомная'}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-center text-muted">{role.userCount}</td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex items-center justify-end gap-1">
                      {(!role.isBuiltIn ||
                        !['super_admin', 'club_admin', 'trainer'].includes(role.slug)) && (
                        <button
                          onClick={() => openRename(role)}
                          className="p-1.5 rounded-lg hover:bg-background text-muted hover:text-text transition-colors"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </button>
                      )}
                      {!role.isBuiltIn && (
                        <button
                          onClick={() => handleDelete(role)}
                          className="p-1.5 rounded-lg hover:bg-error/10 text-muted hover:text-error transition-colors"
                        >
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create/Rename dialog */}
      <Dialog open={showForm} onClose={() => setShowForm(false)}>
        <DialogHeader
          title={editingRole ? 'Переименовать роль' : 'Новая роль'}
          onClose={() => setShowForm(false)}
        />
        <DialogBody className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Название</label>
            <input
              type="text"
              value={formName}
              onChange={(e) => handleNameChange(e.target.value)}
              placeholder="Инструктор групповых"
              className={inputClass}
            />
          </div>
          {!editingRole && (
            <div>
              <label className="block text-sm font-medium text-text mb-1">
                Slug (латиница, snake_case)
              </label>
              <input
                type="text"
                value={formSlug}
                onChange={(e) => setFormSlug(e.target.value)}
                placeholder="group_instructor"
                className={inputClass}
              />
            </div>
          )}
        </DialogBody>
        <DialogFooter>
          <button
            onClick={() => setShowForm(false)}
            className="px-4 py-2 text-sm text-muted hover:text-text transition-colors"
          >
            Отмена
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !formName.trim() || (!editingRole && !formSlug.trim())}
            className="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 transition-colors"
          >
            {saving ? 'Сохранение...' : 'Сохранить'}
          </button>
        </DialogFooter>
      </Dialog>
    </div>
  );
}
