import React, { useState, useEffect, ChangeEvent } from 'react';
import { Artist, Epoch, Country } from '../types';

interface ArtistFormProps {
  countries: Country[];
  epochs: Epoch[];
  onSubmit: (artist: Artist) => Promise<void>;
  artist?: Artist | null;
  onCancel?: () => void;
}

const ArtistForm: React.FC<ArtistFormProps> = ({ countries, epochs, onSubmit, artist, onCancel }) => {
  const [formData, setFormData] = useState<Artist>({
    id: '',
    name: '',
    description: '',
    epochId: '',
    countryId: '',
  });
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    console.log('ArtistForm artist prop:', artist);
    if (artist) {
      setFormData({
        id: artist.id,
        name: artist.name,
        description: artist.description,
        epochId: artist.epochId,
        countryId: artist.countryId,
      });
    } else {
      setFormData({
        id: '',
        name: '',
        description: '',
        epochId: '',
        countryId: '',
      });
    }
  }, [artist]);

  const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
  const { name, value } = e.target;
  setFormData(prev => ({
    ...prev,
    [name]: value, 
  }));
};

  const handleSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  if (!formData.name || !formData.description || !formData.epochId || !formData.countryId) {
    setError('Все поля обязательны!');
    return;
  }
  try {
    setError(null);
    if (artist) {
      // Если редактируем существующего артиста, передаем id
      await onSubmit({ ...formData, id: artist.id });
    } else {
      // Если добавляем нового артиста, id не передаем
      await onSubmit(formData);
    }
    setFormData({
      id: '',
      name: '',
      description: '',
      epochId: '',
      countryId: '',
    });
  } catch (err: any) {
    setError(err.message || 'Ошибка при добавлении/редактировании исполнителя');
  }
};

  console.log('Rendering form with formData:', formData);

  return (
    <div className="card bg-dark border-punk">
      <div className="card-body">
        <h3 className="text-punk mb-4">
          <i className={`bi ${artist ? 'bi-pencil-square' : 'bi-person-plus'}`}></i> 
          {artist ? 'Редактировать исполнителя' : 'Добавить исполнителя'}
        </h3>
        
        {error && <div className="alert alert-danger">{error}</div>}
        
        <form onSubmit={handleSubmit}>
          <div className="mb-3">
            <label className="form-label text-light">Название группы</label>
            <input 
              type="text" 
              className="form-control bg-dark text-light border-punk" 
              name="name"
              value={formData.name}
              onChange={handleChange}
              required
            />
          </div>
          
          <div className="mb-3">
            <label className="form-label text-light">Описание</label>
            <textarea 
              className="form-control bg-dark text-light border-punk" 
              name="description"
              value={formData.description}
              onChange={handleChange}
              required
            />
          </div>
          
          <div className="mb-3">
            <label className="form-label text-light">Эпоха</label>
            <select 
              className="form-select bg-dark text-light border-punk" 
              name="epochId"
              value={formData.epochId}
              onChange={handleChange}
              required
            >
              <option value={0}>Выберите эпоху</option>
              {epochs.map(epoch => (
                <option key={epoch.id} value={epoch.id}>{epoch.name}</option>
              ))}
            </select>
          </div>
          
          <div className="mb-3">
            <label className="form-label text-light">Страна</label>
            <select 
              className="form-select bg-dark text-light border-punk" 
              name="countryId"
              value={formData.countryId}
              onChange={handleChange}
              required
            >
              <option value={0}>Выберите страну</option>
              {countries.map(country => (
                <option key={country.id} value={country.id}>{country.name}</option>
              ))}
            </select>
          </div>
          
          <button 
            type="submit" 
            className="btn btn-punk mt-3"
            style={{ zIndex: 1000 }}
          >
            <i className={`bi ${artist ? 'bi-save' : 'bi-plus-circle'}`}></i> 
            {artist ? 'Сохранить изменения' : 'Добавить исполнителя'}
          </button>
          {artist && <button type="button" className="btn btn-secondary mt-3 ms-2" onClick={onCancel}>Отмена</button>}
        </form>
      </div>
    </div>
  );
};

export default ArtistForm;