'use client';

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

type Service = {
  id: string;
  name: string;
  category: string | { id: string; name: string };
  price: number;
  duration: number;
  isActive: boolean;
};

type ServiceDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  service?: Service | null;
};

export function ServiceDialog({ open, onClose, onSaved, service }: ServiceDialogProps) {
  const [name, setName] = useState('');
  const [category, setCategory] = useState('');
  const [price, setPrice] = useState<number>(0);
  const [duration, setDuration] = useState<number>(60);
  const [isActive, setIsActive] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!service;

  useEffect(() => {
    if (open) {
      if (service) {
        setName(service.name);
        setCategory(typeof service.category === 'string' ? service.category : service.category.name);
        setPrice(service.price);
        setDuration(service.duration);
        setIsActive(service.isActive);
      } else {
        setName('');
        setCategory('');
        setPrice(0);
        setDuration(60);
        setIsActive(true);
      }
      setError(null);
    }
  }, [open, service]);

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

    const body = { name, category, price, duration, isActive };

    try {
      if (isEdit) {
        await api.patch(`/catalog/services/${service.id}`, body);
      } else {
        await api.post('/catalog/services', 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={category}
              onChange={(e) => setCategory(e.target.value)}
              placeholder="Например: Персональные тренировки"
              className={inputClass}
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Цена, &#8381; <span className="text-error">*</span>
              </label>
              <input
                type="number"
                required
                min={0}
                value={price}
                onChange={(e) => setPrice(Number(e.target.value))}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Длительность, мин <span className="text-error">*</span>
              </label>
              <input
                type="number"
                required
                min={1}
                value={duration}
                onChange={(e) => setDuration(Number(e.target.value))}
                className={inputClass}
              />
            </div>
          </div>

          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              id="service-active"
              checked={isActive}
              onChange={(e) => setIsActive(e.target.checked)}
              className="h-4 w-4 rounded border-border text-primary focus:ring-primary/30"
            />
            <label htmlFor="service-active" className="text-sm font-medium text-gray-700">
              Услуга активна
            </label>
          </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>
  );
}
