import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import './Habits.css';

interface Habit {
  id: string;
  name: string;
  description?: string;
  frequency_type: string;
  target_count: number;
  is_active: boolean;
  start_date: string;
}

const Habits: React.FC<{ onBack: () => void }> = ({ onBack }) => {
  const { token, user } = useAuth();
  const [habits, setHabits] = useState<Habit[]>([]);
  const [completedToday, setCompletedToday] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [creating, setCreating] = useState(false);
  const [newHabit, setNewHabit] = useState({
    name: '',
    description: '',
    frequency_type: 'daily',
    target_count: 1
  });

  const backendUrl = `${window.location.protocol}//${window.location.host}`;

  useEffect(() => {
    loadHabits();
  }, []);

  const loadHabits = async () => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/habits/`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setHabits(data);
      }
    } catch (error) {
      console.error('Erro ao carregar hábitos:', error);
    } finally {
      setLoading(false);
    }
  };

  const createHabit = async () => {
    if (!newHabit.name.trim()) {
      alert('Nome do hábito é obrigatório!');
      return;
    }

    setCreating(true);

    try {
      const response = await fetch(`${backendUrl}/api/v1/habits/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(newHabit)
      });

      if (response.ok) {
        setNewHabit({ name: '', description: '', frequency_type: 'daily', target_count: 1 });
        setShowModal(false);
        await loadHabits();
        alert('✅ Hábito criado com sucesso!');
      } else {
        const error = await response.json();
        alert('❌ Erro: ' + (error.detail || 'Erro ao criar hábito'));
      }
    } catch (error) {
      console.error('Erro ao criar hábito:', error);
      alert('❌ Erro ao criar hábito');
    } finally {
      setCreating(false);
    }
  };

  const toggleComplete = async (habitId: string) => {
    const isCompleted = completedToday.has(habitId);

    try {
      const url = `${backendUrl}/api/v1/habits/${habitId}/complete`;
      const response = await fetch(url, {
        method: isCompleted ? 'DELETE' : 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const newCompleted = new Set(completedToday);
        if (isCompleted) {
          newCompleted.delete(habitId);
        } else {
          newCompleted.add(habitId);
        }
        setCompletedToday(newCompleted);
      }
    } catch (error) {
      console.error('Erro ao marcar hábito:', error);
    }
  };

  const deleteHabit = async (habitId: string) => {
    if (!confirm('Tem certeza que deseja deletar este hábito?')) return;

    try {
      const response = await fetch(`${backendUrl}/api/v1/habits/${habitId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        loadHabits();
      }
    } catch (error) {
      console.error('Erro ao deletar hábito:', error);
    }
  };

  if (loading) {
    return (
      <div className="habits-page">
        <div className="loading">⏳ Carregando hábitos...</div>
      </div>
    );
  }

  return (
    <div className="habits-page">
      <div className="habits-header">
        <button onClick={onBack} className="back-button">← Voltar</button>
        <h1>🎯 Meus Hábitos</h1>
        <button onClick={() => setShowModal(true)} className="add-button">
          + Novo Hábito
        </button>
      </div>

      <div className="habits-stats">
        <div className="stat">
          <span className="stat-value">{habits.length}</span>
          <span className="stat-label">Total</span>
        </div>
        <div className="stat">
          <span className="stat-value">{completedToday.size}</span>
          <span className="stat-label">Completos Hoje</span>
        </div>
        <div className="stat">
          <span className="stat-value">{habits.length - completedToday.size}</span>
          <span className="stat-label">Pendentes</span>
        </div>
      </div>

      <div className="habits-list">
        {habits.length === 0 ? (
          <div className="empty-state">
            <p>📝 Nenhum hábito criado ainda.</p>
            <p>Comece criando seu primeiro hábito!</p>
          </div>
        ) : (
          habits.map(habit => (
            <div key={habit.id} className="habit-card">
              <div className="habit-checkbox">
                <input
                  type="checkbox"
                  checked={completedToday.has(habit.id)}
                  onChange={() => toggleComplete(habit.id)}
                />
              </div>
              <div className="habit-content">
                <h3>{habit.name}</h3>
                {habit.description && <p>{habit.description}</p>}
                <span className="habit-frequency">{habit.frequency_type}</span>
              </div>
              <button 
                onClick={() => deleteHabit(habit.id)} 
                className="delete-button"
                title="Deletar hábito"
              >
                🗑️
              </button>
            </div>
          ))
        )}
      </div>

      {/* Modal de Criar Hábito */}
      {showModal && (
        <div className="modal-overlay" onClick={() => !creating && setShowModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <h2>🎯 Novo Hábito</h2>
            
            <div className="form-group">
              <label>Nome do Hábito *</label>
              <input
                type="text"
                value={newHabit.name}
                onChange={(e) => setNewHabit({...newHabit, name: e.target.value})}
                placeholder="Ex: Fazer exercícios"
                autoFocus
                disabled={creating}
              />
            </div>

            <div className="form-group">
              <label>Descrição</label>
              <textarea
                value={newHabit.description}
                onChange={(e) => setNewHabit({...newHabit, description: e.target.value})}
                placeholder="Detalhes sobre o hábito..."
                rows={3}
                disabled={creating}
              />
            </div>

            <div className="form-group">
              <label>Frequência</label>
              <select
                value={newHabit.frequency_type}
                onChange={(e) => setNewHabit({...newHabit, frequency_type: e.target.value})}
                disabled={creating}
              >
                <option value="daily">Diário</option>
                <option value="weekly">Semanal</option>
                <option value="custom">Personalizado</option>
              </select>
            </div>

            <div className="modal-actions">
              <button 
                onClick={() => setShowModal(false)} 
                className="cancel-button"
                disabled={creating}
              >
                Cancelar
              </button>
              <button 
                onClick={createHabit} 
                className="create-button"
                disabled={creating}
              >
                {creating ? '⏳ Criando...' : 'Criar Hábito'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Habits;
