import React, { useState, useEffect } from 'react';
import { useCountersContext } from '../contexts/CountersContext';
import { useAuth } from '../hooks/useAuth';
import { CreateCounterModal } from './CreateCounterModal';
import { CounterCard } from './CounterCard';
import { Plus, Search, TrendingUp, Calendar, Clock } from 'lucide-react';

export const Dashboard: React.FC = () => {
  console.log('Dashboard: Component rendering...');
  const { counters, isLoading, error, searchCounters, version, incrementCounter, deleteCounter } = useCountersContext();
  const { isAuthenticated } = useAuth();
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const handleSearch = (query: string) => {
    setSearchQuery(query);
    searchCounters(query);
  };

  useEffect(() => {
    console.log('Dashboard: Counters changed:', counters, 'version:', version);
  }, [counters, version]);

  console.log('Dashboard: Current counters:', counters, 'version:', version);
  const totalCounters = counters?.length || 0;
  const totalValue = counters?.reduce((sum, counter) => sum + counter.total_value, 0) || 0;
  const todayValue = counters?.reduce((sum, counter) => sum + counter.today_value, 0) || 0;

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md">
        {error}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Dashboard</h1>
          <p className="text-gray-600 mt-1">
            {isAuthenticated 
              ? 'Maaaanage your counters and track your progress'
              : 'Track your habits and activities (data stored locally)'
            }
          </p>
        </div>
        
        <button
          onClick={() => setShowCreateModal(true)}
          className="btn btn-primary flex items-center space-x-2"
        >
          <Plus className="h-5 w-5" />
          <span>New Counter</span>
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="card p-6">
          <div className="flex items-center">
            <div className="p-2 bg-primary-100 rounded-lg">
              <TrendingUp className="h-6 w-6 text-primary-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Total Counters</p>
              <p className="text-2xl font-bold text-gray-900">{totalCounters}</p>
            </div>
          </div>
        </div>

        <div className="card p-6">
          <div className="flex items-center">
            <div className="p-2 bg-green-100 rounded-lg">
              <Calendar className="h-6 w-6 text-green-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Total Value</p>
              <p className="text-2xl font-bold text-gray-900">{totalValue}</p>
            </div>
          </div>
        </div>

        <div className="card p-6">
          <div className="flex items-center">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Clock className="h-6 w-6 text-blue-600" />
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-600">Today's Value</p>
              <p className="text-2xl font-bold text-gray-900">{todayValue}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <Search className="h-5 w-5 text-gray-400" />
        </div>
        <input
          type="text"
          placeholder="Search counters..."
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          className="input pl-10"
        />
      </div>

      {/* Counters Grid */}
      {isLoading ? (
        <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>
      ) : (counters?.length || 0) === 0 ? (
        <div className="text-center py-12">
          <TrendingUp className="mx-auto h-12 w-12 text-gray-400" />
          <h3 className="mt-2 text-sm font-medium text-gray-900">No counters</h3>
          <p className="mt-1 text-sm text-gray-500">
            Get started by creating your first counter.
          </p>
          <div className="mt-6">
            <button
              onClick={() => setShowCreateModal(true)}
              className="btn btn-primary"
            >
              <Plus className="h-5 w-5 mr-2" />
              New Counter
            </button>
          </div>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {counters?.map((counter) => (
            <CounterCard 
              key={counter.id} 
              counter={counter} 
              onIncrement={incrementCounter}
              onDelete={deleteCounter}
            />
          ))}
        </div>
      )}

      {/* Create Counter Modal */}
      {showCreateModal && (
        <CreateCounterModal
          onClose={() => setShowCreateModal(false)}
        />
      )}
    </div>
  );
};
