import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useCountersContext } from '../contexts/CountersContext';
import { useAuth } from '../hooks/useAuth';
import { CounterEntry } from '../types';
import { ArrowLeft, Plus, Minus, Trash2, Calendar } from 'lucide-react';
import { format } from 'date-fns';

export const CounterDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { isAuthenticated } = useAuth();
  const { counters, incrementCounter, deleteCounter, getCounterEntries } = useCountersContext();
  
  // Get the current counter from the useCounters hook
  const counter = counters.find(c => c.id.toString() === id) || null;
  const [entries, setEntries] = useState<CounterEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isIncrementing, setIsIncrementing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load entries when component mounts or counter changes
  useEffect(() => {
    const loadEntries = async () => {
      if (!id || !counter) return;
      
      setIsLoading(true);
      setError(null);
      
      try {
        const counterEntries = await getCounterEntries(id);
        setEntries(counterEntries);
      } catch (err: any) {
        setError(err.message || 'Failed to load counter entries');
      } finally {
        setIsLoading(false);
      }
    };

    loadEntries();
  }, [id, counter, getCounterEntries]);

  const handleIncrement = async (value: number) => {
    if (!counter) return;
    
    setIsIncrementing(true);
    try {
      await incrementCounter(counter.id, value);
      console.log('Counter incremented:', counter.id, value);
      // Entries will be reloaded automatically when counter changes
    } catch (error) {
      console.error('Failed to increment counter:', error);
    } finally {
      setIsIncrementing(false);
    }
  };

  const handleDelete = async () => {
    if (!counter) return;
    
    if (window.confirm('Are you sure you want to delete this counter?')) {
      try {
        await deleteCounter(counter.id);
        navigate('/');
      } catch (error) {
        console.error('Failed to delete counter:', error);
      }
    }
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center py-12">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  if (error || !counter) {
    return (
      <div className="text-center py-12">
        <div className="text-red-600 mb-4">{error || 'Counter not found'}</div>
        <button
          onClick={() => navigate('/')}
          className="btn btn-primary"
        >
          Back to Dashboard
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <button
            onClick={() => navigate('/')}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{counter.name}</h1>
            {counter.description && (
              <p className="text-gray-600 mt-1">{counter.description}</p>
            )}
          </div>
        </div>
        
        <button
          onClick={handleDelete}
          className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
        >
          <Trash2 className="h-5 w-5" />
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="card p-4">
          <div className="text-center">
            <p className="text-sm font-medium text-gray-600">Total Value</p>
            <p className="text-2xl font-bold text-gray-900">{counter.total_value}</p>
          </div>
        </div>
        
        <div className="card p-4">
          <div className="text-center">
            <p className="text-sm font-medium text-gray-600">Today</p>
            <p className="text-2xl font-bold text-gray-900">{counter.today_value}</p>
          </div>
        </div>
        
        <div className="card p-4">
          <div className="text-center">
            <p className="text-sm font-medium text-gray-600">This Week</p>
            <p className="text-2xl font-bold text-gray-900">{counter.week_value}</p>
          </div>
        </div>
        
        <div className="card p-4">
          <div className="text-center">
            <p className="text-sm font-medium text-gray-600">This Month</p>
            <p className="text-2xl font-bold text-gray-900">{counter.month_value}</p>
          </div>
        </div>
      </div>

      {/* Increment Controls */}
      <div className="card p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4">Quick Actions</h2>
        <div className="flex space-x-4">
          <button
            onClick={() => handleIncrement(-1)}
            disabled={isIncrementing}
            className="btn btn-secondary flex items-center space-x-2 disabled:opacity-50"
          >
            <Minus className="h-5 w-5" />
            <span>-1</span>
          </button>
          
          <button
            onClick={() => handleIncrement(1)}
            disabled={isIncrementing}
            className="btn btn-primary flex items-center space-x-2 disabled:opacity-50"
          >
            <Plus className="h-5 w-5" />
            <span>+1</span>
          </button>
          
          <button
            onClick={() => handleIncrement(5)}
            disabled={isIncrementing}
            className="btn btn-primary flex items-center space-x-2 disabled:opacity-50"
          >
            <Plus className="h-5 w-5" />
            <span>+5</span>
          </button>
          
          <button
            onClick={() => handleIncrement(10)}
            disabled={isIncrementing}
            className="btn btn-primary flex items-center space-x-2 disabled:opacity-50"
          >
            <Plus className="h-5 w-5" />
            <span>+10</span>
          </button>
        </div>
      </div>

      {/* Recent Entries */}
      <div className="card p-6">
        <h2 className="text-xl font-semibold text-gray-900 mb-4 flex items-center">
          <Calendar className="h-5 w-5 mr-2" />
          Recent Entries
        </h2>
        
        {(entries?.length || 0) === 0 ? (
          <div className="text-center py-8 text-gray-500">
            No entries yet. Start by incrementing your counter!
          </div>
        ) : (
          <div className="space-y-3">
            {entries?.slice(0, 10).map((entry) => (
              <div
                key={entry.id}
                className="flex justify-between items-center py-2 px-4 bg-gray-50 rounded-lg"
              >
                <div className="flex items-center space-x-3">
                  <div className="text-sm text-gray-600">
                    {format(new Date(entry.date), 'MMM dd, yyyy')}
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                  <span className={`font-medium ${entry.value >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                    {entry.value > 0 ? '+' : ''}{entry.value}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};