import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { pb, getFileUrl } from '../../services/pocketbaseService';
import { FaUpload, FaTrash } from 'react-icons/fa';
import { motion } from 'framer-motion';

const MobileMediaForm = () => {
  const navigate = useNavigate();
  const { path } = useParams();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    type: 'movie',
    poster: null,
    characteristics: [
      { name: 'Сюжет', value: 0 },
      { name: 'Актерская игра', value: 0 },
      { name: 'Визуальные эффекты', value: 0 },
      { name: 'Звук', value: 0 },
      { name: 'Музыка', value: 0 }
    ],
    seasons: []
  });

  useEffect(() => {
    if (path) {
      const fetchMedia = async () => {
        try {
          const media = await pb.collection('media').getFirstListItem(`path="${path}"`);
          setFormData({
            ...media,
            poster: null
          });
        } catch (err) {
          console.error('Error fetching media:', err);
          setError('Не удалось загрузить данные');
        }
      };
      fetchMedia();
    }
  }, [path]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleCharacteristicChange = (index, value) => {
    const newCharacteristics = [...formData.characteristics];
    newCharacteristics[index].value = parseInt(value);
    setFormData(prev => ({
      ...prev,
      characteristics: newCharacteristics
    }));
  };

  const handlePosterChange = async (e) => {
    const file = e.target.files[0];
    if (file) {
      setFormData(prev => ({
        ...prev,
        poster: file
      }));
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const data = {
        ...formData,
        path: formData.path || formData.title.toLowerCase().replace(/[^a-z0-9]+/g, '-')
      };

      if (path) {
        // Обновление существующего медиа
        await pb.collection('media').update(path, data);
      } else {
        // Создание нового медиа
        await pb.collection('media').create(data);
      }

      navigate(`/media/${data.path}`);
    } catch (err) {
      console.error('Error saving media:', err);
      setError('Не удалось сохранить данные');
    } finally {
      setLoading(false);
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      className="min-h-screen bg-campfire-dark p-4"
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        <div>
          <label className="block text-campfire-light mb-2">Название</label>
          <input
            type="text"
            name="title"
            value={formData.title}
            onChange={handleInputChange}
            className="w-full bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg p-3 text-campfire-light"
            required
          />
        </div>

        <div>
          <label className="block text-campfire-light mb-2">Описание</label>
          <textarea
            name="description"
            value={formData.description}
            onChange={handleInputChange}
            className="w-full bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg p-3 text-campfire-light h-32"
            required
          />
        </div>

        <div>
          <label className="block text-campfire-light mb-2">Тип</label>
          <select
            name="type"
            value={formData.type}
            onChange={handleInputChange}
            className="w-full bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg p-3 text-campfire-light"
          >
            <option value="movie">Фильм</option>
            <option value="series">Сериал</option>
            <option value="game">Игра</option>
            <option value="anime">Аниме</option>
          </select>
        </div>

        <div>
          <label className="block text-campfire-light mb-2">Постер</label>
          <div className="flex items-center gap-4">
            {formData.poster && (
              <div className="relative w-24 h-36">
                <img
                  src={typeof formData.poster === 'string' ? getFileUrl(formData, 'poster') : URL.createObjectURL(formData.poster)}
                  alt="Poster preview"
                  className="w-full h-full object-cover rounded-lg"
                />
                <button
                  type="button"
                  onClick={() => setFormData(prev => ({ ...prev, poster: null }))}
                  className="absolute -top-2 -right-2 w-6 h-6 bg-campfire-charcoal/80 rounded-full flex items-center justify-center text-campfire-light hover:text-campfire-amber"
                >
                  <FaTrash size={12} />
                </button>
              </div>
            )}
            <label className="flex-1">
              <input
                type="file"
                accept="image/*"
                onChange={handlePosterChange}
                className="hidden"
              />
              <div className="flex items-center justify-center gap-2 px-4 py-3 bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg text-campfire-light hover:bg-campfire-charcoal/30 cursor-pointer">
                <FaUpload />
                <span>Загрузить постер</span>
              </div>
            </label>
          </div>
        </div>

        <div>
          <label className="block text-campfire-light mb-2">Характеристики</label>
          <div className="space-y-4">
            {formData.characteristics.map((char, index) => (
              <div key={char.name}>
                <div className="flex justify-between items-center mb-2">
                  <span className="text-campfire-light">{char.name}</span>
                  <span className="text-campfire-amber">{char.value}/10</span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="10"
                  value={char.value}
                  onChange={(e) => handleCharacteristicChange(index, e.target.value)}
                  className="w-full"
                />
              </div>
            ))}
          </div>
        </div>

        {error && (
          <div className="bg-status-error/20 text-status-error p-4 rounded-lg text-center">
            {error}
          </div>
        )}

        <div className="flex gap-4">
          <button
            type="button"
            onClick={() => navigate(-1)}
            className="flex-1 px-4 py-3 bg-campfire-charcoal/50 text-campfire-light border border-campfire-ash/30 rounded-lg hover:bg-campfire-charcoal/70 transition-colors"
          >
            Отмена
          </button>
          <button
            type="submit"
            disabled={loading}
            className="flex-1 px-4 py-3 bg-campfire-amber text-campfire-dark rounded-lg hover:bg-campfire-amber/80 transition-colors disabled:opacity-50"
          >
            {loading ? 'Сохранение...' : path ? 'Сохранить' : 'Создать'}
          </button>
        </div>
      </form>
    </motion.div>
  );
};

export default MobileMediaForm; 