import React, { useState, useEffect } from 'react';
import { createReview, updateReview } from '../../services/pocketbaseService';
import { FaFire } from 'react-icons/fa';
import RatingChart from '../../components/reviews/RatingChart';
import FlameRatingInput from '../../components/reviews/FlameRatingInput';

const watchedStatusLabels = {
  not_watched: 'Не просмотрено',
  watched: 'Просмотрено',
};

const completedStatusLabels = {
  not_completed: 'Не пройдено',
  completed: 'Пройдено',
};

function MobileReviewForm({ 
  mediaId, 
  seasonId, 
  mediaType, 
  progress_type,
  onSubmit, 
  onEdit, 
  onDelete, 
  characteristics = {}, 
  existingReview, 
  seasons = [], 
  selectedSeasonId 
}) {
  const initialRatings = Object.keys(characteristics).reduce((acc, key) => {
    acc[key] = 5;
    return acc;
  }, {});

  const [ratings, setRatings] = useState(initialRatings);
  const [content, setContent] = useState('');
  const [hasSpoilers, setHasSpoilers] = useState(false);
  const [progress, setProgress] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [formSeasonId, setFormSeasonId] = useState(selectedSeasonId);

  const getProgressOptions = () => {
    if (progress_type === 'hours') {
      return null;
    } else if (progress_type === 'watched') {
      return watchedStatusLabels;
    } else if (progress_type === 'completed') {
      return completedStatusLabels;
    }
    return watchedStatusLabels;
  };

  const progressOptions = getProgressOptions();
  const isProgressSelect = progressOptions !== null;
  const supportsSeasons = mediaType === 'tv' || mediaType === 'anime';

  useEffect(() => {
    if (existingReview) {
      const populatedRatings = Object.keys(characteristics).reduce((acc, key) => {
        acc[key] = typeof existingReview.ratings?.[key] === 'number' ? existingReview.ratings[key] : 5;
        return acc;
      }, {});

      setRatings(populatedRatings);
      setContent(existingReview.content || '');
      setHasSpoilers(existingReview.has_spoilers ?? false);
      setProgress(existingReview.progress || '');
      setFormSeasonId(existingReview.season_id || null);
      setIsEditing(false);
    } else {
      const newInitialRatings = Object.keys(characteristics).reduce((acc, key) => {
        acc[key] = 5;
        return acc;
      }, {});
      setRatings(newInitialRatings);
      setContent('');
      setHasSpoilers(false);
      if (isProgressSelect) {
        setProgress(Object.keys(progressOptions)[0] || '');
      } else {
        setProgress('');
      }
      setFormSeasonId(selectedSeasonId);
      setIsEditing(false);
    }
  }, [characteristics, existingReview, progress_type, isProgressSelect, selectedSeasonId, seasons]);

  const handleRatingChange = (category, value) => {
    const newRatings = {
      ...ratings,
      [category]: value
    };
    
    const validRatings = Object.values(newRatings).filter(rating => typeof rating === 'number');
    const overallRating = validRatings.length > 0 
      ? validRatings.reduce((sum, rating) => sum + rating, 0) / validRatings.length 
      : 0;
    
    setRatings({
      ...newRatings,
      overall: overallRating
    });
  };

  const handleProgressChange = (value) => {
    setProgress(value);
  };

  const handleFormSeasonChange = (e) => {
    const value = e.target.value === '' ? null : e.target.value;
    setFormSeasonId(value);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      const validRatings = Object.entries(ratings)
        .filter(([key, value]) => key !== 'overall' && typeof value === 'number');
      const overallRating = validRatings.length > 0 
        ? validRatings.reduce((sum, [_, rating]) => sum + rating, 0) / validRatings.length 
        : 0;

      const reviewData = {
        media_id: mediaId,
        season_id: formSeasonId,
        media_type: mediaType,
        content,
        ratings: {
          ...ratings,
          overall: overallRating
        },
        overall_rating: overallRating,
        has_spoilers: hasSpoilers,
        progress: progress,
        progress_type: progress_type
      };

      if (existingReview && isEditing) {
        await onEdit(existingReview.id, reviewData);
        setIsEditing(false);
      } else {
        await onSubmit(reviewData);
      }
    } catch (error) {
      console.error('Error submitting review:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (window.confirm('Вы уверены, что хотите удалить эту рецензию?')) {
      setIsSubmitting(true);
      try {
        await onDelete(existingReview.id, mediaId);
      } catch (error) {
        console.error('Error deleting review:', error);
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const isFormValid = content.trim() !== '' &&
    Object.keys(characteristics).length > 0 &&
    Object.keys(characteristics).every(key =>
      typeof ratings[key] === 'number' && ratings[key] >= 1 && ratings[key] <= 10
    ) &&
    (isProgressSelect ? Object.keys(progressOptions).includes(progress) : progress.trim() !== '') &&
    (supportsSeasons ? (formSeasonId === null || seasons.some(s => s.id === formSeasonId)) : true);

  if (existingReview && !isEditing) {
    return (
      <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4 text-center">
        <p className="text-campfire-light mb-4">Вы уже написали рецензию на это произведение.</p>
        <div className="flex justify-center space-x-4">
          <button
            onClick={() => setIsEditing(true)}
            className="btn-secondary flex items-center"
            disabled={isSubmitting}
          >
            Редактировать
          </button>
          <button
            onClick={handleDelete}
            className="btn-danger flex items-center text-white"
            disabled={isSubmitting}
          >
            Удалить
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-4">
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">
          {supportsSeasons && seasons.length > 0 && (
            <div>
              <label htmlFor="season-select" className="block mb-2 text-campfire-light">
                Сезон <span className="text-red-500">*</span>
              </label>
              <select
                id="season-select"
                value={formSeasonId === null ? '' : formSeasonId}
                onChange={handleFormSeasonChange}
                className="w-full p-3 bg-campfire-dark border border-campfire-ash/30 rounded-xl text-campfire-light"
                required={supportsSeasons && formSeasonId === undefined}
              >
                <option value="">Общее</option>
                {seasons.map(season => (
                  <option key={season.id} value={season.id}>
                    Сезон {season.season_number} {season.title ? ` - ${season.title}` : ''}
                  </option>
                ))}
              </select>
            </div>
          )}

          <div>
            <label className="block mb-2 text-campfire-light">
              {progress_type === 'hours'
                ? 'Часов проведено'
                : progress_type === 'watched'
                  ? 'Статус просмотра'
                  : progress_type === 'completed'
                    ? 'Статус прохождения'
                    : 'Прогресс'
              } <span className="text-red-500">*</span>
            </label>
            {isProgressSelect ? (
              <div className="flex rounded-xl overflow-hidden border border-campfire-ash/30">
                {Object.entries(progressOptions).map(([key, label]) => (
                  <button
                    key={key}
                    type="button"
                    onClick={() => handleProgressChange(key)}
                    className={`flex-1 text-center py-3 text-sm font-medium ${
                      progress === key
                        ? 'bg-campfire-amber text-campfire-dark'
                        : 'bg-campfire-dark text-campfire-ash'
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>
            ) : (
              <input
                type="number"
                min="0"
                step="0.5"
                placeholder="Введите количество часов..."
                value={progress}
                onChange={(e) => handleProgressChange(e.target.value)}
                className="w-full p-3 bg-campfire-dark border border-campfire-ash/30 rounded-xl text-campfire-light"
                required
              />
            )}
          </div>

          <div className="space-y-4">
            {Object.entries(characteristics).map(([key, label]) => (
              <div key={key} className="space-y-2">
                <div className="flex justify-between items-center mb-1">
                  <label className="block text-sm font-medium text-campfire-light">{label}</label>
                  <span className="flex items-center text-campfire-amber font-bold text-lg">
                    <FaFire className="mr-1 text-base" />
                    {ratings[key] !== undefined ? ratings[key] : 5}
                  </span>
                </div>
                <FlameRatingInput
                  value={ratings[key] !== undefined ? ratings[key] : 5}
                  onChange={(value) => handleRatingChange(key, value)}
                />
              </div>
            ))}
          </div>

          <div>
            <label className="block mb-2 text-campfire-light text-sm font-medium">
              Ваша рецензия <span className="text-red-500">*</span>
            </label>
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder="Поделитесь своими мыслями об этом произведении..."
              className="w-full p-3 bg-campfire-dark border border-campfire-ash/30 rounded-xl text-campfire-light min-h-[200px] resize-y"
              required
            />
          </div>

          <div className="flex items-center">
            <input
              type="checkbox"
              id="spoiler-check"
              checked={hasSpoilers}
              onChange={(e) => setHasSpoilers(e.target.checked)}
              className="w-4 h-4 text-campfire-amber bg-campfire-dark border-campfire-ash rounded focus:ring-campfire-amber focus:ring-2"
            />
            <label htmlFor="spoiler-check" className="ml-2 text-campfire-light text-sm">
              Эта рецензия содержит спойлеры
            </label>
          </div>

          <div>
            <p className="text-center text-campfire-light mb-4 font-semibold">Предварительный просмотр вашей оценки</p>
            <RatingChart
              ratings={Object.entries(ratings).reduce((acc, [key, value]) => {
                if (characteristics.hasOwnProperty(key) && typeof value === 'number' && value >= 1 && value <= 10) {
                  acc[key] = value;
                }
                return acc;
              }, {})}
              labels={characteristics}
              size="medium"
            />
          </div>
        </div>

        <div className="flex justify-end mt-6">
          <button
            type="submit"
            disabled={isSubmitting || !isFormValid}
            className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isSubmitting ? (existingReview ? 'Сохранение...' : 'Отправка...') : (existingReview ? 'Сохранить изменения' : 'Отправить рецензию')}
          </button>
        </div>

        {!isFormValid && (
          <p className="text-status-error text-sm mt-2 text-right">
            Пожалуйста, заполните все обязательные поля (рецензия, прогресс, все оценки от 1 до 10{supportsSeasons ? ', сезон' : ''}).
          </p>
        )}
        {Object.keys(characteristics).length === 0 && (
          <p className="text-status-error text-sm mt-2 text-right">
            Характеристики для этого произведения не загружены.
          </p>
        )}
      </form>
    </div>
  );
}

export default MobileReviewForm; 