'use client';

import { useCallback, useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, Save } from 'lucide-react';
import { api } from '@/lib/api';
import { AvatarUpload } from '@/components/staff/avatar-upload';
import { PasswordChangeSection } from '@/components/staff/password-change-section';

const ROLE_LABELS: Record<string, string> = {
  TRAINER: 'Тренер',
  COORDINATOR: 'Координатор',
  MANAGER: 'Фитнес-менеджер',
  RECEPTIONIST: 'Администратор',
  CLUB_ADMIN: 'Админ клуба',
  SUPER_ADMIN: 'Суперадминистратор',
};

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

type UserDetail = {
  id: string;
  number: number | null;
  clubId: string;
  phone: string;
  role: string;
  roleLabel: string;
  firstName: string;
  lastName: string;
  patronymic: string | null;
  email: string | null;
  avatarUrl: string | null;
  comment: string | null;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
  department: { id: string; name: string } | null;
  room: { id: string; name: string } | null;
};

type ListItem = { id: string; name: string };
type ListResponse = { data: ListItem[]; hasMore: boolean; nextCursor: string | null };

type CurrentUser = { id: string; role: string };

export default function StaffDetailPage(): React.JSX.Element {
  const params = useParams();
  const router = useRouter();
  const staffNumber = params.id as string; // This is user.number (int)

  const [user, setUser] = useState<UserDetail | null>(null);
  const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
  const [departments, setDepartments] = useState<ListItem[]>([]);
  const [rooms, setRooms] = useState<ListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  // Form state
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [role, setRole] = useState('');
  const [departmentId, setDepartmentId] = useState('');
  const [roomId, setRoomId] = useState('');
  const [comment, setComment] = useState('');

  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [userData, profileData, deptData, roomData] = await Promise.all([
        api.get<UserDetail>(`/users/${staffNumber}`),
        api.get<CurrentUser>('/auth/profile'),
        api.get<ListResponse>('/departments'),
        api.get<ListResponse>('/rooms'),
      ]);

      setUser(userData);
      setCurrentUser({ id: profileData.id, role: profileData.role });
      setDepartments(deptData.data ?? []);
      setRooms(roomData.data ?? []);

      // Populate form
      setFirstName(userData.firstName);
      setLastName(userData.lastName);
      setPhone(userData.phone);
      setEmail(userData.email ?? '');
      setRole(userData.role);
      setDepartmentId(userData.department?.id ?? '');
      setRoomId(userData.room?.id ?? '');
      setComment(userData.comment ?? '');
    } catch {
      // If user not found, redirect back
      router.push('/staff');
    } finally {
      setLoading(false);
    }
  }, [staffNumber, router]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  const isSelf = currentUser?.id === user?.id;
  const isAdmin = currentUser ? ['CLUB_ADMIN', 'SUPER_ADMIN'].includes(currentUser.role) : false;
  const canEdit = isSelf || isAdmin;

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!canEdit) return;
    setSaving(true);
    setSaved(false);

    try {
      const name = [firstName.trim(), lastName.trim()].filter(Boolean).join(' ');
      await api.patch(`/users/${user!.id}`, {
        name,
        phone,
        email: email || undefined,
        role,
        departmentId: departmentId || undefined,
        roomId: roomId || undefined,
        comment: comment || undefined,
      });
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Ошибка сохранения');
    } finally {
      setSaving(false);
    }
  };

  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] ?? ''}`;

  return (
    <div>
      <button
        onClick={() => router.push('/staff')}
        className="flex items-center gap-1.5 text-sm text-muted hover:text-gray-900 mb-6 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        Назад к списку
      </button>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left column — avatar + summary */}
        <div className="space-y-6">
          <div className="bg-card rounded-xl p-6 shadow-sm border border-border text-center">
            <AvatarUpload
              userId={user.id}
              currentUrl={user.avatarUrl}
              initials={initials}
              disabled={!canEdit}
              onUploaded={(url) => setUser({ ...user, avatarUrl: url })}
            />
            <h2 className="mt-4 text-lg font-semibold text-gray-900">
              {user.number != null && (
                <span className="text-muted font-normal">#{user.number} </span>
              )}
              {user.firstName} {user.lastName}
            </h2>
            <span className="inline-flex mt-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary">
              {ROLE_LABELS[user.role] ?? user.role}
            </span>
            <div className="mt-3 flex items-center justify-center gap-2">
              <span
                className={`inline-flex h-2 w-2 rounded-full ${user.isActive ? 'bg-green-500' : 'bg-red-500'}`}
              />
              <span className="text-xs text-muted">{user.isActive ? 'Активен' : 'Неактивен'}</span>
            </div>
            <p className="mt-2 text-xs text-muted">
              В системе с {new Date(user.createdAt).toLocaleDateString('ru-RU')}
            </p>
          </div>

          {canEdit && <PasswordChangeSection userId={user.id} isSelf={isSelf} />}
        </div>

        {/* Right column — edit form */}
        <div className="lg:col-span-2">
          <form
            onSubmit={handleSave}
            className="bg-card rounded-xl p-6 shadow-sm border border-border"
          >
            <h3 className="text-base font-semibold text-gray-900 mb-4">Информация о сотруднике</h3>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
                <input
                  type="text"
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  disabled={!canEdit}
                  required
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
                <input
                  type="text"
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  disabled={!canEdit}
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Телефон</label>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  disabled={!canEdit}
                  required
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={!canEdit}
                  placeholder="email@example.com"
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Должность</label>
                <select
                  value={role}
                  onChange={(e) => setRole(e.target.value)}
                  disabled={!isAdmin}
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                >
                  {EDITABLE_ROLES.map((r) => (
                    <option key={r.value} value={r.value}>
                      {r.label}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Департамент</label>
                <select
                  value={departmentId}
                  onChange={(e) => setDepartmentId(e.target.value)}
                  disabled={!isAdmin}
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                >
                  <option value="">Не указан</option>
                  {departments.map((d) => (
                    <option key={d.id} value={d.id}>
                      {d.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="sm:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">Зал</label>
                <select
                  value={roomId}
                  onChange={(e) => setRoomId(e.target.value)}
                  disabled={!isAdmin}
                  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 disabled:bg-gray-50 disabled:text-gray-500"
                >
                  <option value="">Не указан</option>
                  {rooms.map((r) => (
                    <option key={r.id} value={r.id}>
                      {r.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="sm:col-span-2">
                <label className="block text-sm font-medium text-gray-700 mb-1">Комментарий</label>
                <textarea
                  value={comment}
                  onChange={(e) => setComment(e.target.value)}
                  disabled={!canEdit}
                  rows={3}
                  placeholder="Заметки о сотруднике..."
                  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 disabled:bg-gray-50 disabled:text-gray-500 resize-none"
                />
              </div>
            </div>

            {canEdit && (
              <div className="mt-6 flex items-center gap-3">
                <button
                  type="submit"
                  disabled={saving}
                  className="flex items-center gap-2 bg-primary text-white px-5 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
                >
                  <Save className="h-4 w-4" />
                  {saving ? 'Сохранение...' : 'Сохранить'}
                </button>
                {saved && <span className="text-sm text-success">Сохранено</span>}
              </div>
            )}
          </form>
        </div>
      </div>
    </div>
  );
}
