"use client";

import { useState, useEffect } from 'react';

interface TreeStats {
  totalTrees: number;
  activeTrees: number;
  totalJourneys: number;
  activeJourneys: number;
  messagesThisWeek: number;
  avgEngagementScore: number;
  topPerformingTree: {
    name: string;
    completionRate: number;
  } | null;
}

export default function TreeStatsWidget() {
  const [stats, setStats] = useState<TreeStats | null>(null);
  const [loading, setLoading] = useState(true);

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

  const loadStats = async () => {
    try {
      const response = await fetch('/api/admin/tree-stats');
      const data = await response.json();
      setStats(data);
    } catch (error) {
      console.error('Failed to load tree stats:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="animate-pulse">
          <div className="h-6 bg-gray-200 rounded mb-4"></div>
          <div className="grid grid-cols-2 gap-4">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="h-16 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (!stats) {
    return (
      <div className="bg-white rounded-lg shadow-md p-6">
        <div className="text-center text-gray-500">
          <div className="text-4xl mb-2">📊</div>
          <div>No stats available</div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-6">
      <h3 className="text-lg font-semibold mb-6 flex items-center">
        🌳 Tree System Overview
        <button 
          onClick={loadStats}
          className="ml-auto text-sm text-blue-600 hover:text-blue-800"
        >
          🔄 Refresh
        </button>
      </h3>

      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        {/* Total Trees */}
        <div className="text-center p-4 bg-blue-50 rounded-lg">
          <div className="text-2xl font-bold text-blue-600">{stats.totalTrees}</div>
          <div className="text-sm text-gray-600">Total Trees</div>
          <div className="text-xs text-green-600 mt-1">
            {stats.activeTrees} active
          </div>
        </div>

        {/* Active Journeys */}
        <div className="text-center p-4 bg-green-50 rounded-lg">
          <div className="text-2xl font-bold text-green-600">{stats.activeJourneys}</div>
          <div className="text-sm text-gray-600">Active Journeys</div>
          <div className="text-xs text-gray-500 mt-1">
            {stats.totalJourneys} total
          </div>
        </div>

        {/* Messages This Week */}
        <div className="text-center p-4 bg-purple-50 rounded-lg">
          <div className="text-2xl font-bold text-purple-600">{stats.messagesThisWeek}</div>
          <div className="text-sm text-gray-600">Messages/Week</div>
          <div className="text-xs text-purple-600 mt-1">
            📈 Automated
          </div>
        </div>

        {/* Engagement Score */}
        <div className="text-center p-4 bg-yellow-50 rounded-lg">
          <div className="text-2xl font-bold text-yellow-600">
            {stats.avgEngagementScore.toFixed(1)}%
          </div>
          <div className="text-sm text-gray-600">Avg Engagement</div>
          <div className="text-xs text-yellow-600 mt-1">
            🎯 Score
          </div>
        </div>

        {/* Top Performing Tree */}
        <div className="col-span-2 lg:col-span-2 p-4 bg-gradient-to-r from-pink-50 to-purple-50 rounded-lg">
          {stats.topPerformingTree ? (
            <>
              <div className="font-semibold text-gray-800 mb-1">
                🏆 Top Performer
              </div>
              <div className="text-sm font-medium text-gray-700">
                {stats.topPerformingTree.name}
              </div>
              <div className="text-xs text-gray-600 mt-1">
                {stats.topPerformingTree.completionRate.toFixed(1)}% completion rate
              </div>
            </>
          ) : (
            <div className="text-center text-gray-500">
              <div className="text-2xl mb-1">🌱</div>
              <div className="text-sm">Not enough data yet</div>
            </div>
          )}
        </div>
      </div>

      {/* Quick Actions */}
      <div className="border-t pt-4">
        <div className="flex flex-wrap gap-2">
          <a 
            href="/admin/reminder-trees"
            className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
          >
            🌳 Manage Trees
          </a>
          <button 
            onClick={() => window.open('/api/admin/export-tree-data', '_blank')}
            className="px-3 py-1 text-sm bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
          >
            📊 Export Data
          </button>
          <button 
            className="px-3 py-1 text-sm bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
            onClick={() => alert('Tree optimization coming soon!')}
          >
            🎯 Optimize
          </button>
        </div>
      </div>
    </div>
  );
}