'use client';

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

type EditClubDialogProps = {
  open: boolean;
  onClose: () => void;
  onSaved: () => void;
  club: { id: string; name: string; city: string } | null;
};

interface ClubDetail {
  id: string;
  name: string;
  address: string | null;
  phone: string | null;
  email: string | null;
}

export function EditClubDialog({ open, onClose, onSaved, club }: EditClubDialogProps) {
  const [form, setForm] = useState({
    name: '',
    address: '',
    phone: '',
    email: '',
  });
  const [loading, setLoading] = useState(false);
  const [fetching, setFetching] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open || !club) return;

    let cancelled = false;
    setFetching(true);
    setError(null);

    api
      .get<ClubDetail>(`/clubs/${club.id}`)
      .then((data) => {
        if (cancelled) return;
        setForm({
          name: data.name ?? '',
          address: data.address ?? '',
          phone: data.phone ?? '',
          email: data.email ?? '',
        });
      })
      .catch((err) => {
        if (cancelled) return;
        const message = err instanceof Error ? err.message : 'Ошибка загрузки данных клуба';
        setError(message);
      })
      .finally(() => {
        if (!cancelled) setFetching(false);
      });

    return () => {
      cancelled = true;
    };
  }, [open, club]);

  const handleChange = (field: keyof typeof form, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
    setError(null);
  };

  const handleSubmit = async () => {
    if (!club) return;

    if (!form.name.trim()) {
      setError('Введите название клуба');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const body: Record<string, string> = {
        name: form.name.trim(),
      };
      if (form.address.trim()) body.address = form.address.trim();
      else body.address = '';
      if (form.phone.trim()) body.phone = form.phone.trim();
      else body.phone = '';
      if (form.email.trim()) body.email = form.email.trim();
      else body.email = '';

      await api.patch(`/clubs/${club.id}`, body);
      onSaved();
      onClose();
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ошибка при сохранении';
      setError(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="Редактирование клуба"
        description={club?.name ?? ''}
        onClose={onClose}
      />
      <DialogBody className="space-y-4">
        {fetching ? (
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
          </div>
        ) : (
          <>
            <div>
              <label className="block text-sm font-medium text-text mb-1">
                Название <span className="text-error">*</span>
              </label>
              <input
                type="text"
                value={form.name}
                onChange={(e) => handleChange('name', e.target.value)}
                placeholder="Название клуба"
                className={inputClass}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-text mb-1">
                Адрес
              </label>
              <input
                type="text"
                value={form.address}
                onChange={(e) => handleChange('address', e.target.value)}
                placeholder="г. Москва, ул. Примерная, д. 1"
                className={inputClass}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-text mb-1">
                  Телефон
                </label>
                <input
                  type="text"
                  value={form.phone}
                  onChange={(e) => handleChange('phone', e.target.value)}
                  placeholder="+7 (999) 123-45-67"
                  className={inputClass}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-text mb-1">
                  Email
                </label>
                <input
                  type="email"
                  value={form.email}
                  onChange={(e) => handleChange('email', e.target.value)}
                  placeholder="info@club.ru"
                  className={inputClass}
                />
              </div>
            </div>

            {error && (
              <div className="rounded-lg bg-error/10 border border-error/20 px-3 py-2 text-sm text-error">
                {error}
              </div>
            )}
          </>
        )}
      </DialogBody>
      {!fetching && (
        <DialogFooter>
          <button
            type="button"
            onClick={onClose}
            disabled={loading}
            className="px-4 py-2 rounded-xl border border-border text-sm font-medium text-text hover:bg-background transition-colors"
          >
            Отмена
          </button>
          <button
            type="button"
            onClick={() => void handleSubmit()}
            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 ? 'Сохранение...' : 'Сохранить'}
          </button>
        </DialogFooter>
      )}
    </Dialog>
  );
}
