import React, { useState, useEffect } from 'react';
import { 
  RefreshCw, 
  Clock, 
  CheckCircle, 
  AlertCircle,
  Calendar,
  Users
} from 'lucide-react';
import HousekeepingManagement from '../../features/hotel_services/components/HousekeepingManagement';
import advancedRoomService from '../../features/rooms/services/advancedRoomService';

const HousekeepingTasksPage: React.FC = () => {
  const [stats, setStats] = useState({
    total: 0,
    pending: 0,
    in_progress: 0,
    completed: 0,
    today: 0,
  });
  const [loadingStats, setLoadingStats] = useState(true);

  useEffect(() => {
    fetchStats();
    // Refresh stats every 30 seconds
    const interval = setInterval(fetchStats, 30000);
    return () => clearInterval(interval);
  }, []);

  const fetchStats = async () => {
    try {
      setLoadingStats(true);
      const response = await advancedRoomService.getHousekeepingTasks({
        limit: 1000, // Get all tasks for stats
      });
      
      if (response.status === 'success' && response.data) {
        const tasks = response.data.tasks || [];
        const today = new Date().toISOString().split('T')[0];
        
        setStats({
          total: tasks.length,
          pending: tasks.filter((t: { status?: string }) => t.status === 'pending').length,
          in_progress: tasks.filter((t: { status?: string }) => t.status === 'in_progress').length,
          completed: tasks.filter((t: { status?: string }) => t.status === 'completed').length,
          today: tasks.filter((t: { status?: string; due_date?: string }) => {
            if (!t.scheduled_time) return false;
            const taskDate = new Date(t.scheduled_time).toISOString().split('T')[0];
            return taskDate === today;
          }).length,
        });
      }
    } catch (error) {
      console.error('Error fetching stats:', error);
    } finally {
      setLoadingStats(false);
    }
  };

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Housekeeping Tasks
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage and track your cleaning tasks</p>
        </div>
        <button
          onClick={fetchStats}
          disabled={loadingStats}
          className="flex items-center gap-2 px-4 py-2 bg-white border-2 border-slate-200 rounded-xl hover:border-amber-400 transition-colors disabled:opacity-50"
          title="Refresh"
        >
          <RefreshCw className={`w-5 h-5 ${loadingStats ? 'animate-spin' : ''}`} />
          <span className="text-sm font-medium">Refresh</span>
        </button>
      </div>

      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-6 animate-fade-in">
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Total Tasks</p>
              <p className="text-3xl font-bold text-slate-900 mt-2">{stats.total}</p>
            </div>
            <Calendar className="w-12 h-12 text-amber-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Pending</p>
              <p className="text-3xl font-bold text-yellow-600 mt-2">{stats.pending}</p>
            </div>
            <Clock className="w-12 h-12 text-yellow-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">In Progress</p>
              <p className="text-3xl font-bold text-blue-600 mt-2">{stats.in_progress}</p>
            </div>
            <Users className="w-12 h-12 text-blue-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Completed</p>
              <p className="text-3xl font-bold text-green-600 mt-2">{stats.completed}</p>
            </div>
            <CheckCircle className="w-12 h-12 text-green-500" />
          </div>
        </div>
        <div className="bg-white/80 backdrop-blur-sm rounded-xl shadow-lg border border-slate-200/60 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-600 text-sm font-medium">Today's Tasks</p>
              <p className="text-3xl font-bold text-purple-600 mt-2">{stats.today}</p>
            </div>
            <AlertCircle className="w-12 h-12 text-purple-500" />
          </div>
        </div>
      </div>

      {/* Enhanced Housekeeping Management Component */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
        <HousekeepingManagement />
      </div>
    </div>
  );
};

export default HousekeepingTasksPage;
