import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useQuery } from '../../api/useQuery';
import { TodoWithStats, DailyTodoSummary, CreateTodoRequest, UpdateTodoRequest, CompleteTodoRequest, todoApi } from '../../api/controller/todo';
import TodoCard from './components/TodoCard';
import TodoForm from './components/TodoForm';
import ActivityLog from './components/ActivityLog';
import Button from '@greatness/components/src/Button';

export default function WorkPage() {
  const queryClient = useQueryClient();
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isActivityLogOpen, setIsActivityLogOpen] = useState(false);
  const [editingTodo, setEditingTodo] = useState<TodoWithStats | undefined>();

  // Queries
  const { data: todos = [], isLoading: todosLoading, error: todosError } = useQuery<TodoWithStats[]>({
    queryKey: '/todo/list',
  });

  const { data: summary, isLoading: summaryLoading, error: summaryError } = useQuery<DailyTodoSummary>({
    queryKey: '/todo/today',
  });

  // Mutations
  const createTodoMutation = useMutation({
    mutationFn: (data: CreateTodoRequest) => todoApi.createTodo(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/todo/list'] });
      queryClient.invalidateQueries({ queryKey: ['/todo/today'] });
      setIsFormOpen(false);
    },
    onError: (error) => {
      console.error('Failed to create todo:', error);
    },
  });

  const updateTodoMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateTodoRequest }) => 
      todoApi.updateTodo(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/todo/list'] });
      queryClient.invalidateQueries({ queryKey: ['/todo/today'] });
      setEditingTodo(undefined);
    },
    onError: (error) => {
      console.error('Failed to update todo:', error);
    },
  });

  const completeTodoMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: CompleteTodoRequest }) => 
      todoApi.completeTodo(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/todo/list'] });
      queryClient.invalidateQueries({ queryKey: ['/todo/today'] });
    },
    onError: (error) => {
      console.error('Failed to complete todo:', error);
    },
  });

  const deleteTodoMutation = useMutation({
    mutationFn: (id: string) => todoApi.deleteTodo(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['/todo/list'] });
      queryClient.invalidateQueries({ queryKey: ['/todo/today'] });
    },
    onError: (error) => {
      console.error('Failed to delete todo:', error);
    },
  });

  // Handlers
  const handleCreateTodo = async (data: CreateTodoRequest) => {
    await createTodoMutation.mutateAsync(data);
  };

  const handleUpdateTodo = async (data: UpdateTodoRequest) => {
    if (!editingTodo) return;
    await updateTodoMutation.mutateAsync({ id: editingTodo.id, data });
  };

  const handleCompleteTodo = async (id: string, data: CompleteTodoRequest) => {
    await completeTodoMutation.mutateAsync({ id, data });
  };

  const handleDeleteTodo = async (id: string) => {
    if (!confirm('Are you sure you want to delete this todo?')) return;
    await deleteTodoMutation.mutateAsync(id);
  };

  const handleEditTodo = (todo: TodoWithStats) => {
    setEditingTodo(todo);
    setIsFormOpen(true);
  };

  const handleCloseForm = () => {
    setIsFormOpen(false);
    setEditingTodo(undefined);
  };

  const getProgressPercentage = () => {
    if (!summary || summary.totalCount === 0) return 0;
    return Math.round((summary.completedCount / summary.totalCount) * 100);
  };

  const getProgressColor = () => {
    const percentage = getProgressPercentage();
    if (percentage === 100) return 'bg-green-500';
    if (percentage >= 75) return 'bg-blue-500';
    if (percentage >= 50) return 'bg-yellow-500';
    if (percentage >= 25) return 'bg-orange-500';
    return 'bg-red-500';
  };

  const isLoading = todosLoading || summaryLoading;
  const hasError = todosError || summaryError;

  if (isLoading) {
    return (
      <div className="flex flex-col gap-m py-xxl">
        <div className="flex justify-center items-center h-64">
          <div className="text-gray-500">Loading your todos...</div>
        </div>
      </div>
    );
  }

  if (hasError) {
    return (
      <div className="flex flex-col gap-m py-xxl">
        <div className="flex justify-center items-center h-64">
          <div className="text-red-500">
            Error loading todos: {todosError?.message || summaryError?.message}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-m py-xxl max-w-6xl mx-auto px-4">
      {/* Header with daily summary */}
      <div className="bg-greyOpacity rounded-lg shadow-sm border p-6">
        <div className="flex justify-between items-start mb-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">Work & Habits</h1>
            <p className="text-gray-600 mt-1">
              {new Date().toLocaleDateString('en-US', { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric' 
              })}
            </p>
          </div>
          
          <div className="flex gap-3">
            <Button
              onClick={() => setIsActivityLogOpen(true)}
              className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 flex items-center gap-2"
              label="📊 Activity Log"
            >
            </Button>
            <Button
              onClick={() => setIsFormOpen(true)}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md flex items-center gap-2"
              label="➕ Add Todo"
            >
            </Button>
          </div>
        </div>

        {/* Progress summary */}
        {summary && (
          <div className="bg-greyOpacity rounded-lg p-4">
            <div className="flex justify-between items-center mb-2">
              <span className="text-sm font-medium text-white">
                Today's Progress
              </span>
              <span className="text-sm text-white">
                {summary.completedCount} of {summary.totalCount} completed
              </span>
            </div>
            
            <div className="w-full bg-gray-200 rounded-full h-3 mb-2">
              <div
                className={`h-3 rounded-full transition-all duration-300 ${getProgressColor()}`}
                style={{ width: `${getProgressPercentage()}%` }}
              />
            </div>
            
            <div className="flex justify-between text-xs text-white">
              <span>{getProgressPercentage()}% complete</span>
              {getProgressPercentage() === 100 && (
                <span className="text-green-600 font-medium">🎉 All done!</span>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Todos grid */}
      {!Array.isArray(todos) || todos.length === 0 ? (
        <div className="bg-greyOpacity rounded-lg shadow-sm border p-12 text-center">
          <div className="text-6xl mb-4">📝</div>
          <h3 className="text-lg font-medium text-white mb-2">No todos yet</h3>
          <p className="text-white mb-6">
            Create your first todo to start building healthy daily habits!
          </p>
          <Button
            onClick={() => setIsFormOpen(true)}
            className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-md"
            label="Create Your First Todo"
          >
          </Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {todos.map((todo) => (
            <TodoCard
              key={todo.id}
              todo={todo}
              onComplete={handleCompleteTodo}
              onEdit={handleEditTodo}
              onDelete={handleDeleteTodo}
              isLoading={completeTodoMutation.isPending || deleteTodoMutation.isPending}
            />
          ))}
        </div>
      )}

      {/* Todo Form Modal */}
      <TodoForm
        isOpen={isFormOpen}
        onClose={handleCloseForm}
        onSubmit={editingTodo ? handleUpdateTodo : handleCreateTodo}
        todo={editingTodo}
        isLoading={createTodoMutation.isPending || updateTodoMutation.isPending}
      />

      {/* Activity Log Modal */}
      <ActivityLog
        isOpen={isActivityLogOpen}
        onClose={() => setIsActivityLogOpen(false)}
      />
    </div>
  );
};
