import React, { useEffect, useState } from 'react';
import './DailyMessage.css';

interface Message {
  id: string | null;
  message_text: string;
  icon: string;
  message_type: string;
  priority: number;
}

interface DailyMessageProps {
  userId: string;
}

const DailyMessage: React.FC<DailyMessageProps> = ({ userId }) => {
  const [message, setMessage] = useState<Message | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetchDailyMessage();
  }, [userId]);

  const fetchDailyMessage = async () => {
    try {
      const backendUrl = `${window.location.protocol}//${window.location.host}`;
      
      const response = await fetch(
        `${backendUrl}/api/v1/messages/daily?user_id=${userId}`
      );
      
      if (!response.ok) throw new Error('Erro ao buscar mensagem');
      
      const data = await response.json();
      setMessage(data.message);
      setLoading(false);
    } catch (err) {
      console.error('Erro ao carregar mensagem:', err);
      setError(true);
      setLoading(false);
    }
  };

  const handleClick = async () => {
    if (message?.id) {
      try {
        const backendUrl = `${window.location.protocol}//${window.location.host}`;
        
        await fetch(
          `${backendUrl}/api/v1/messages/click/${message.id}?user_id=${userId}`,
          { method: 'POST' }
        );
      } catch (err) {
        console.error('Erro ao registrar click:', err);
      }
    }
  };

  if (loading) {
    return (
      <div className="daily-message loading">
        <div className="loading-spinner">⏳</div>
        <p>Carregando mensagem...</p>
      </div>
    );
  }

  if (error || !message) {
    return (
      <div className="daily-message">
        <span className="icon">💪</span>
        <p className="message-text">A transformação acontece um dia de cada vez!</p>
      </div>
    );
  }

  return (
    <div 
      className={`daily-message ${message.message_type}`}
      onClick={handleClick}
    >
      <span className="icon">{message.icon}</span>
      <p className="message-text">{message.message_text}</p>
      <div className="message-badge">{getMessageTypeBadge(message.message_type)}</div>
    </div>
  );
};

const getMessageTypeBadge = (type: string): string => {
  const badges: { [key: string]: string } = {
    'streak_achievement': '🏆 Conquista',
    'reminder': '🔔 Lembrete',
    'progress_milestone': '📈 Progresso',
    'time_based': '⏰ Momento',
    'special_milestone': '⭐ Especial',
    'recovery': '💙 Retorno',
    'daily_motivation': '💪 Motivação'
  };
  return badges[type] || '✨ Mensagem';
};

export default DailyMessage;
