'use client';

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

type Department = {
  id: string;
  name: string;
  head: string;
  trainersCount: number;
  activeClients: number;
  description: string;
};

type DepartmentDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  department?: Department | null;
};

export function DepartmentDialog({ open, onClose, onSaved, department }: DepartmentDialogProps) {
  const isEdit = !!department;

  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [headId, setHeadId] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      if (department) {
        setName(department.name);
        setDescription(department.description);
        setHeadId(department.head);
      } else {
        setName('');
        setDescription('');
        setHeadId('');
      }
      setError(null);
    }
  }, [open, department]);

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

    try {
      const body = {
        name,
        description,
        headId,
      };

      if (isEdit && department) {
        await api.patch(`/departments/${department.id}`, body);
      } else {
        await api.post('/departments', 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>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Описание департамента"
              rows={3}
              className={inputClassName}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Руководитель
            </label>
            <input
              type="text"
              value={headId}
              onChange={(e) => setHeadId(e.target.value)}
              placeholder="ID руководителя"
              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>
  );
}
