import { useState } from 'react';
import { useQuery } from '../../../api/useQuery';
import { TodoCompletion } from '../../../api/controller/todo';
import Button from '@greatness/components/src/Button';
import Modal from '@greatness/components/src/Modal';

interface ActivityLogProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function ActivityLog({ isOpen, onClose }: ActivityLogProps) {
  const [selectedDate, setSelectedDate] = useState('');
  const [viewMode, setViewMode] = useState<'recent' | 'date'>('recent');

  // Query for recent activities (only enabled when modal is open and in recent mode)
  const { data: recentActivities = [], isLoading: recentLoading, error: recentError } = useQuery<TodoCompletion[]>({
    queryKey: '/todo/activity?limit=100&offset=0',
    isEnabled: isOpen && viewMode === 'recent',
  });

  // Query for activities by date (only enabled when modal is open, in date mode, and date is selected)
  const { data: dateActivities = [], isLoading: dateLoading, error: dateError } = useQuery<TodoCompletion[]>({
    queryKey: selectedDate ? `/todo/activity/${selectedDate}` : '',
    isEnabled: isOpen && viewMode === 'date' && selectedDate !== '',
  });

  const activities = viewMode === 'recent' ? recentActivities : dateActivities;
  const isLoading = viewMode === 'recent' ? recentLoading : dateLoading;
  const error = viewMode === 'recent' ? recentError : dateError;

  const loadRecentActivities = () => {
    setViewMode('recent');
    setSelectedDate('');
  };

  const loadActivitiesByDate = (date: string) => {
    setSelectedDate(date);
    setViewMode('date');
  };

  const handleDateChange = (date: string) => {
    setSelectedDate(date);
    if (date) {
      loadActivitiesByDate(date);
    }
  };

  const formatDateTime = (dateString: string) => {
    const date = new Date(dateString);
    return {
      date: date.toLocaleDateString(),
      time: date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
    };
  };

  const groupActivitiesByDate = (activities: TodoCompletion[]) => {
    const grouped: Record<string, TodoCompletion[]> = {};
    activities.forEach(activity => {
      const date = new Date(activity.completedAt).toDateString();
      if (!grouped[date]) {
        grouped[date] = [];
      }
      grouped[date].push(activity);
    });
    return grouped;
  };

  if (!isOpen) {
    return null;
  };

  const groupedActivities = groupActivitiesByDate(activities);

  return (
    <Modal isOpen={isOpen} handleClose={onClose}>
      <div className="bg-greyOpacity rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex justify-between items-center p-6 border-b">
          <h2 className="text-xl font-semibold">Activity Log</h2>
          <button
            onClick={onClose}
            className="text-white text-xl"
          >
            ×
          </button>
        </div>

        {/* Controls */}
        <div className="p-4 border-b bg-greyOpacity">
          <div className="flex gap-4 items-center">
            <Button
              onClick={loadRecentActivities}
              className={`px-4 py-2 rounded-md ${
                viewMode === 'recent' 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-greyOpacity text-white'
              }`}
              label="Recent Activities"
            >
            </Button>
            
            <div className="flex items-center gap-2 text-white">
              <label htmlFor="date-picker" className="text-sm font-medium">
                View by date:
              </label>
              <input
                id="date-picker"
                type="date"
                value={selectedDate}
                onChange={(e) => handleDateChange(e.target.value)}
                className="px-3 py-1 border border-greyOpacity rounded-md"
                max={new Date().toISOString().split('T')[0]}
              />
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {isLoading ? (
            <div className="flex justify-center items-center h-32">
              <div className="text-white">Loading activities...</div>
            </div>
          ) : error ? (
            <div className="flex justify-center items-center h-32">
              <div className="text-red-500">Error: {error.message}</div>
            </div>
          ) : activities.length === 0 ? (
            <div className="text-center text-white py-12">
              <div className="text-4xl mb-4">📝</div>
              <h3 className="text-lg font-medium mb-2">No activities found</h3>
              <p className="text-sm">
                {viewMode === 'date' 
                  ? 'No todos were completed on this date.' 
                  : 'Start completing todos to see your activity here!'}
              </p>
            </div>
          ) : (
            <div className="space-y-6">
              {Object.entries(groupedActivities).map(([date, dayActivities]) => (
                <div key={date} className="border-l-4 border-blue-500 pl-4">
                  <h3 className="font-semibold text-white mb-3 flex items-center gap-2">
                    <span className="text-blue-600">📅</span>
                    {date}
                    <span className="text-sm text-white ml-2">
                      ({dayActivities.length} completed)
                    </span>
                  </h3>
                  
                  <div className="space-y-3">
                    {dayActivities.map((activity) => {
                      const { time } = formatDateTime(activity.completedAt);
                      return (
                        <div
                          key={activity.id}
                          className="bg-greyOpacity border border-white rounded-lg p-4 shadow-sm"
                        >
                          <div className="flex justify-between items-start mb-2">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-1">
                                <div
                                  className="w-3 h-3 rounded-full"
                                  style={{ backgroundColor: activity.todo.color }}
                                />
                                <h4 className="font-medium text-white">
                                  {activity.todo.title}
                                </h4>
                                <span className="text-xs text-white bg-greyOpacity px-2 py-1 rounded">
                                  {time}
                                </span>
                              </div>
                              
                              {activity.todo.description && (
                                <p className="text-sm text-white mb-2">
                                  {activity.todo.description}
                                </p>
                              )}
                            </div>
                          </div>
                          
                          {activity.description && (
                            <p className="text-sm text-green-800">
                              {activity.description}
                            </p>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t bg-greyOpacity flex justify-end">
          <Button
            onClick={onClose}
            className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md"
            label="Close"
          >
          </Button>
        </div>
      </div>
    </Modal>
  );
}
