'use client';

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

type ServicePackage = {
  id: string;
  name: string;
  services: (string | { id: string; name: string })[];
  totalPrice: number;
  discountPercent: number;
  validDays: number;
  isActive: boolean;
};

type PackageDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  pkg?: ServicePackage | null;
};

export function PackageDialog({ open, onClose, onSaved, pkg }: PackageDialogProps) {
  const [name, setName] = useState('');
  const [servicesText, setServicesText] = useState('');
  const [totalPrice, setTotalPrice] = useState<number>(0);
  const [discountPercent, setDiscountPercent] = useState<number>(0);
  const [validDays, setValidDays] = useState<number>(30);
  const [isActive, setIsActive] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isEdit = !!pkg;

  useEffect(() => {
    if (open) {
      if (pkg) {
        setName(pkg.name);
        setServicesText((pkg.services ?? []).map((s) => typeof s === 'string' ? s : s.name).join(', '));
        setTotalPrice(pkg.totalPrice);
        setDiscountPercent(pkg.discountPercent);
        setValidDays(pkg.validDays);
        setIsActive(pkg.isActive);
      } else {
        setName('');
        setServicesText('');
        setTotalPrice(0);
        setDiscountPercent(0);
        setValidDays(30);
        setIsActive(true);
      }
      setError(null);
    }
  }, [open, pkg]);

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

    const services = servicesText
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);

    const body = { name, services, totalPrice, discountPercent, validDays, isActive };

    try {
      if (isEdit) {
        await api.patch(`/catalog/packages/${pkg.id}`, body);
      } else {
        await api.post('/catalog/packages', 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="Например: Безлимит 12 месяцев"
              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={servicesText}
              onChange={(e) => setServicesText(e.target.value)}
              placeholder="Через запятую: Тренажёрный зал, Бассейн, Сауна"
              className={inputClass}
            />
            <p className="text-xs text-muted mt-1">Перечислите через запятую</p>
          </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={totalPrice}
                onChange={(e) => setTotalPrice(Number(e.target.value))}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Скидка, %
              </label>
              <input
                type="number"
                min={0}
                max={100}
                value={discountPercent}
                onChange={(e) => setDiscountPercent(Number(e.target.value))}
                className={inputClass}
              />
            </div>
          </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={validDays}
              onChange={(e) => setValidDays(Number(e.target.value))}
              className={inputClass}
            />
          </div>

          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              id="package-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="package-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>
  );
}
