import React, { useState, useEffect } from 'react';
import { Flame, Plus, Trash2, Check } from 'lucide-react';

interface Habit {
  id: number;
  habit_name: string;
  frequency: string;
  current_streak: number;
  longest_streak: number;
  total_completions: number;
  created_at: string;
  updated_at: string;
}

const HabitTracker: React.FC = () => {
  const [habits, setHabits] = useState<Habit[]>([]);
  const [loading, setLoading] = useState(false);
  const [showAddForm, setShowAddForm] = useState(false);
  const [newHabitName, setNewHabitName] = useState('');
  const [newHabitFrequency, setNewHabitFrequency] = useState('daily');

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

  const loadHabits = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/daily-helper/habits');
      if (response.ok) {
        const data = await response.json();
        setHabits(data);
      }
    } catch (err) {
      console.error('Failed to load habits:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleAddHabit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newHabitName.trim()) return;

    try {
      const response = await fetch('/api/daily-helper/habits', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          habit_name: newHabitName,
          frequency: newHabitFrequency,
        }),
      });

      if (response.ok) {
        setNewHabitName('');
        setShowAddForm(false);
        loadHabits();
      }
    } catch (err) {
      console.error('Failed to create habit:', err);
    }
  };

  const handleLogCompletion = async (habitId: number) => {
    try {
      const response = await fetch(`/api/daily-helper/habits/${habitId}/log`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          habit_id: habitId,
          completion_date: new Date().toISOString().split('T')[0],
        }),
      });

      if (response.ok) {
        loadHabits();
      }
    } catch (err) {
      console.error('Failed to log completion:', err);
    }
  };

  const handleDeleteHabit = async (habitId: number) => {
    if (!confirm('Delete this habit?')) return;

    try {
      const response = await fetch(`/api/daily-helper/habits/${habitId}`, {
        method: 'DELETE',
      });

      if (response.ok) {
        loadHabits();
      }
    } catch (err) {
      console.error('Failed to delete habit:', err);
    }
  };

  const getStreakColor = (streak: number) => {
    if (streak >= 30) return 'text-red-400';
    if (streak >= 14) return 'text-orange-400';
    if (streak >= 7) return 'text-yellow-400';
    return 'text-blue-400';
  };

  const getStreakBadge = (streak: number) => {
    if (streak === 0) return null;
    if (streak >= 30) return '🔥🔥🔥';
    if (streak >= 14) return '🔥🔥';
    if (streak >= 7) return '🔥';
    return '';
  };

  return (
    <div className="bg-gray-900 rounded-lg border border-gray-700 p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Flame className="text-orange-500" size={28} />
          <h2 className="text-2xl font-bold text-white">Habit Tracker</h2>
        </div>
        <button
          onClick={() => setShowAddForm(!showAddForm)}
          className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded flex items-center gap-2 transition-colors"
        >
          <Plus size={20} />
          Add Habit
        </button>
      </div>

      {/* Add Habit Form */}
      {showAddForm && (
        <form onSubmit={handleAddHabit} className="mb-6 p-4 bg-gray-800 rounded-lg border border-gray-700">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            <input
              type="text"
              value={newHabitName}
              onChange={(e) => setNewHabitName(e.target.value)}
              placeholder="Habit name (e.g., Daily Planning, Trading Journal)"
              className="col-span-2 bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white placeholder-gray-500 focus:outline-none focus:border-blue-500"
              autoFocus
            />
            <select
              value={newHabitFrequency}
              onChange={(e) => setNewHabitFrequency(e.target.value)}
              className="bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-blue-500"
            >
              <option value="daily">Daily</option>
              <option value="weekly">Weekly</option>
            </select>
          </div>
          <div className="flex gap-2">
            <button
              type="submit"
              className="flex-1 bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded transition-colors"
            >
              Create Habit
            </button>
            <button
              type="button"
              onClick={() => setShowAddForm(false)}
              className="flex-1 bg-gray-700 hover:bg-gray-600 text-white font-medium py-2 px-4 rounded transition-colors"
            >
              Cancel
            </button>
          </div>
        </form>
      )}

      {/* Habits List */}
      <div className="space-y-4">
        {loading ? (
          <div className="text-center text-gray-400 py-8">Loading habits...</div>
        ) : habits.length === 0 ? (
          <div className="text-center text-gray-400 py-8">
            <p>No habits yet. Create one to get started!</p>
          </div>
        ) : (
          habits.map((habit) => (
            <div
              key={habit.id}
              className="p-4 bg-gray-800 rounded-lg border border-gray-700 hover:border-gray-600 transition-colors"
            >
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-white mb-2">
                    {habit.habit_name}
                  </h3>

                  <div className="flex flex-wrap gap-6 text-sm">
                    {/* Current Streak */}
                    <div>
                      <p className="text-gray-400 mb-1">Current Streak</p>
                      <div className="flex items-center gap-2">
                        <span className={`text-2xl font-bold ${getStreakColor(habit.current_streak)}`}>
                          {habit.current_streak}
                        </span>
                        {getStreakBadge(habit.current_streak) && (
                          <span className="text-2xl">{getStreakBadge(habit.current_streak)}</span>
                        )}
                      </div>
                    </div>

                    {/* Longest Streak */}
                    <div>
                      <p className="text-gray-400 mb-1">Longest Streak</p>
                      <p className="text-xl font-bold text-purple-400">
                        {habit.longest_streak}
                      </p>
                    </div>

                    {/* Total Completions */}
                    <div>
                      <p className="text-gray-400 mb-1">Total Completions</p>
                      <p className="text-xl font-bold text-green-400">
                        {habit.total_completions}
                      </p>
                    </div>

                    {/* Frequency */}
                    <div>
                      <p className="text-gray-400 mb-1">Frequency</p>
                      <p className="text-sm font-medium text-blue-400 capitalize">
                        {habit.frequency}
                      </p>
                    </div>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="flex flex-col gap-2">
                  <button
                    onClick={() => handleLogCompletion(habit.id)}
                    className="bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded flex items-center gap-2 transition-colors whitespace-nowrap"
                  >
                    <Check size={18} />
                    Log Today
                  </button>
                  <button
                    onClick={() => handleDeleteHabit(habit.id)}
                    className="bg-red-600 hover:bg-red-700 text-white font-medium py-2 px-4 rounded flex items-center gap-2 transition-colors"
                  >
                    <Trash2 size={18} />
                  </button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Motivational Message */}
      {habits.length > 0 && (
        <div className="mt-6 p-4 bg-blue-900 bg-opacity-30 border border-blue-600 rounded-lg">
          <p className="text-blue-200 text-sm">
            💡 <strong>Tip:</strong> Consistency is key! Maintain your streaks by completing your habits every day. Even 5 minutes of planning or journaling can transform your trading!
          </p>
        </div>
      )}
    </div>
  );
};

export default HabitTracker;
