'use client';

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

type Employee = {
  id: string;
  name: string;
  role: string;
  department: string;
  phone: string;
  status: 'active' | 'inactive';
  hiredAt: string;
};

type EmployeeDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  employee?: Employee | null;
};

const ROLE_OPTIONS = [
  { value: 'trainer', label: 'Тренер' },
  { value: 'coordinator', label: 'Координатор' },
  { value: 'manager', label: 'Фитнес-менеджер' },
  { value: 'receptionist', label: 'Администратор' },
];

export function EmployeeDialog({ open, onClose, onSaved, employee }: EmployeeDialogProps) {
  const isEdit = !!employee;

  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [role, setRole] = useState('trainer');
  const [departmentId, setDepartmentId] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      if (employee) {
        setName(employee.name);
        setPhone(employee.phone);
        setRole(employee.role);
        setDepartmentId(employee.department);
        setPassword('');
      } else {
        setName('');
        setPhone('');
        setRole('trainer');
        setDepartmentId('');
        setPassword('');
      }
      setError(null);
    }
  }, [open, employee]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const body: Record<string, string> = {
        name,
        phone,
        role,
        departmentId,
      };

      if (!isEdit) {
        body.password = password;
      }

      if (isEdit && employee) {
        await api.patch(`/users/${employee.id}`, body);
      } else {
        await api.post('/users', body);
      }

      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Произошла ошибка при сохранении');
    } finally {
      setLoading(false);
    }
  };

  const inputClassName =
    '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={isEdit ? 'Редактировать сотрудника' : 'Добавить сотрудника'}
        description={isEdit ? 'Измените данные сотрудника' : 'Заполните данные нового сотрудника'}
        onClose={onClose}
      />
      <form onSubmit={(e) => void handleSubmit(e)}>
        <DialogBody className="space-y-4">
          {error && (
            <div className="bg-red-50 text-error text-sm px-4 py-3 rounded-lg">{error}</div>
          )}

          <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="Введите имя сотрудника"
              required
              className={inputClassName}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Телефон</label>
            <input
              type="text"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+7 (999) 123-45-67"
              required
              className={inputClassName}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Роль</label>
            <select
              value={role}
              onChange={(e) => setRole(e.target.value)}
              required
              className={inputClassName}
            >
              {ROLE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Департамент</label>
            <input
              type="text"
              value={departmentId}
              onChange={(e) => setDepartmentId(e.target.value)}
              placeholder="ID департамента"
              className={inputClassName}
            />
          </div>

          {!isEdit && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Введите пароль"
                required
                className={inputClassName}
              />
            </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-gray-700 hover:bg-gray-50 transition-colors"
          >
            Отмена
          </button>
          <button
            type="submit"
            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 ? 'Сохранение...' : isEdit ? 'Сохранить' : 'Добавить'}
          </button>
        </DialogFooter>
      </form>
    </Dialog>
  );
}
