'use client';

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

type Room = {
  id: string;
  name: string;
  location: string;
  capacity: number;
  type: string;
  equipment: string[];
  status: 'available' | 'occupied' | 'maintenance';
  workingHours: string;
};

type RoomDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  room?: Room | null;
};

export function RoomDialog({ open, onClose, onSaved, room }: RoomDialogProps) {
  const [name, setName] = useState('');
  const [location, setLocation] = useState('');
  const [capacity, setCapacity] = useState<number>(0);
  const [type, setType] = useState('');
  const [workingHours, setWorkingHours] = useState('');
  const [status, setStatus] = useState<'available' | 'occupied' | 'maintenance'>('available');
  const [equipmentText, setEquipmentText] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!room;

  useEffect(() => {
    if (open) {
      if (room) {
        setName(room.name);
        setLocation(room.location);
        setCapacity(room.capacity);
        setType(room.type);
        setWorkingHours(room.workingHours);
        setStatus(room.status);
        setEquipmentText(room.equipment.join(', '));
      } else {
        setName('');
        setLocation('');
        setCapacity(0);
        setType('');
        setWorkingHours('');
        setStatus('available');
        setEquipmentText('');
      }
      setError(null);
    }
  }, [open, room]);

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

    const equipment = equipmentText
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);

    const body = { name, location, capacity, type, workingHours, status, equipment };

    try {
      if (isEdit) {
        await api.patch(`/rooms/${room.id}`, body);
      } else {
        await api.post('/rooms', body);
      }
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Не удалось сохранить зал');
    } finally {
      setLoading(false);
    }
  };

  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 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 border border-red-200 text-error text-sm px-3 py-2 rounded-lg">
              {error}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Название <span className="text-error">*</span>
            </label>
            <input
              type="text"
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Например: Зал групповых программ"
              className={inputClass}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Локация <span className="text-error">*</span>
            </label>
            <input
              type="text"
              required
              value={location}
              onChange={(e) => setLocation(e.target.value)}
              placeholder="Например: 2 этаж, корпус А"
              className={inputClass}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Вместимость <span className="text-error">*</span>
              </label>
              <input
                type="number"
                required
                min={0}
                value={capacity}
                onChange={(e) => setCapacity(Number(e.target.value))}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Тип
              </label>
              <input
                type="text"
                value={type}
                onChange={(e) => setType(e.target.value)}
                placeholder="Например: тренажёрный"
                className={inputClass}
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Часы работы
            </label>
            <input
              type="text"
              value={workingHours}
              onChange={(e) => setWorkingHours(e.target.value)}
              placeholder="Например: 07:00 — 23:00"
              className={inputClass}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Статус
            </label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value as 'available' | 'occupied' | 'maintenance')}
              className={inputClass}
            >
              <option value="available">Свободен</option>
              <option value="occupied">Занят</option>
              <option value="maintenance">Обслуживание</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Оборудование
            </label>
            <input
              type="text"
              value={equipmentText}
              onChange={(e) => setEquipmentText(e.target.value)}
              placeholder="Через запятую: коврики, зеркала, колонки"
              className={inputClass}
            />
            <p className="text-xs text-muted mt-1">Перечислите через запятую</p>
          </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>
  );
}
