'use client';

import { useEffect, useState } from 'react';
import { User, Shield, Phone, ChevronDown } from 'lucide-react';
import { api } from '@/lib/api';

type UserProfile = {
  id: string;
  firstName: string;
  lastName: string;
  role: string;
  phone: string;
};

const ALL_ROLES = [
  { value: 'SUPER_ADMIN', label: 'Суперадминистратор' },
  { value: 'CLUB_ADMIN', label: 'Админ клуба' },
  { value: 'MANAGER', label: 'Фитнес-менеджер' },
  { value: 'COORDINATOR', label: 'Координатор' },
  { value: 'RECEPTIONIST', label: 'Рецепция' },
  { value: 'TRAINER', label: 'Тренер' },
] as const;

const ROLE_LABELS: Record<string, string> = Object.fromEntries(
  ALL_ROLES.map((r) => [r.value, r.label]),
);

const VIEW_ROLE_KEY = 'fitcrm_club_view_role';

function getViewRole(): string | null {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem(VIEW_ROLE_KEY);
}

function setViewRole(role: string | null): void {
  if (role) {
    localStorage.setItem(VIEW_ROLE_KEY, role);
  } else {
    localStorage.removeItem(VIEW_ROLE_KEY);
  }
  window.dispatchEvent(new Event('viewrole-change'));
}

const CAN_SWITCH_ROLES = ['SUPER_ADMIN', 'CLUB_ADMIN'];

export default function ProfilePage(): React.JSX.Element {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeViewRole, setActiveViewRole] = useState<string | null>(null);
  const [dropdownOpen, setDropdownOpen] = useState(false);

  useEffect(() => {
    setActiveViewRole(getViewRole());
    api.get<UserProfile>('/auth/profile')
      .then(setUser)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleRoleChange = (role: string) => {
    if (role === user?.role) {
      setActiveViewRole(null);
      setViewRole(null);
    } else {
      setActiveViewRole(role);
      setViewRole(role);
    }
    setDropdownOpen(false);
  };

  const handleReset = () => {
    setActiveViewRole(null);
    setViewRole(null);
  };

  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 (!user) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-sm text-muted">Не удалось загрузить профиль</p>
      </div>
    );
  }

  const initials = `${user.firstName[0]}${user.lastName[0]}`;
  const canSwitch = CAN_SWITCH_ROLES.includes(user.role);
  const currentViewLabel = activeViewRole
    ? ROLE_LABELS[activeViewRole] ?? activeViewRole
    : null;

  return (
    <div className="max-w-2xl mx-auto">
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Профиль</h1>

      {/* User card */}
      <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-6">
        <div className="flex items-center gap-4 mb-6">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-primary/10">
            <span className="text-xl font-bold text-primary">{initials}</span>
          </div>
          <div>
            <h2 className="text-lg font-semibold text-gray-900">
              {user.firstName} {user.lastName}
            </h2>
            <p className="text-sm text-muted">
              {ROLE_LABELS[user.role] ?? user.role}
            </p>
          </div>
        </div>

        <div className="space-y-3">
          <div className="flex items-center gap-3 text-sm">
            <User className="h-4 w-4 text-muted shrink-0" />
            <span className="text-gray-600">ID:</span>
            <span className="text-gray-900 font-mono text-xs">{user.id}</span>
          </div>
          <div className="flex items-center gap-3 text-sm">
            <Phone className="h-4 w-4 text-muted shrink-0" />
            <span className="text-gray-600">Телефон:</span>
            <span className="text-gray-900">{user.phone}</span>
          </div>
          <div className="flex items-center gap-3 text-sm">
            <Shield className="h-4 w-4 text-muted shrink-0" />
            <span className="text-gray-600">Роль:</span>
            <span className="text-gray-900">{ROLE_LABELS[user.role] ?? user.role}</span>
          </div>
        </div>
      </div>

      {/* Role switcher */}
      {canSwitch && (
        <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
          <div className="flex items-center gap-2 mb-1">
            <Shield className="h-5 w-5 text-primary" />
            <h2 className="text-base font-semibold text-gray-900">
              Просмотр интерфейса от лица другой роли
            </h2>
          </div>
          <p className="text-sm text-muted mb-4">
            Переключите роль, чтобы увидеть, как выглядит интерфейс для разных
            пользователей. Это не влияет на реальные права доступа к API.
          </p>

          {currentViewLabel && (
            <div className="flex items-center gap-2 mb-4 px-3 py-2 rounded-lg bg-amber-50 border border-amber-200">
              <div className="h-2 w-2 rounded-full bg-amber-500 shrink-0" />
              <p className="text-sm text-amber-800 flex-1">
                Вы просматриваете интерфейс как <strong>{currentViewLabel}</strong>
              </p>
              <button
                onClick={handleReset}
                className="text-xs text-amber-700 hover:text-amber-900 font-medium hover:underline"
              >
                Сбросить
              </button>
            </div>
          )}

          <div className="relative">
            <button
              onClick={() => setDropdownOpen(!dropdownOpen)}
              className="w-full flex items-center justify-between px-4 py-2.5 rounded-xl border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
            >
              <span>
                {activeViewRole
                  ? ROLE_LABELS[activeViewRole] ?? activeViewRole
                  : 'Выберите роль для просмотра'}
              </span>
              <ChevronDown
                className={`h-4 w-4 text-muted transition-transform ${dropdownOpen ? 'rotate-180' : ''}`}
              />
            </button>

            {dropdownOpen && (
              <>
                <div
                  className="fixed inset-0 z-10"
                  onClick={() => setDropdownOpen(false)}
                />
                <div className="absolute left-0 right-0 mt-1 bg-card border border-border rounded-xl shadow-lg z-20 py-1 overflow-hidden">
                  {ALL_ROLES.map((role) => {
                    const isActive = activeViewRole === role.value;
                    const isOwnRole = user.role === role.value && !activeViewRole;
                    return (
                      <button
                        key={role.value}
                        onClick={() => handleRoleChange(role.value)}
                        className={`w-full text-left px-4 py-2.5 text-sm transition-colors ${
                          isActive
                            ? 'bg-primary/10 text-primary font-medium'
                            : isOwnRole
                              ? 'text-gray-400 cursor-default'
                              : 'text-gray-700 hover:bg-gray-50'
                        }`}
                        disabled={isOwnRole}
                      >
                        <span>{role.label}</span>
                        {isActive && (
                          <span className="ml-2 text-xs text-primary/70">(активна)</span>
                        )}
                        {isOwnRole && (
                          <span className="ml-2 text-xs text-muted">(ваша роль)</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
