'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth, useTasks } from '@/lib/stores';
import { Button, Card, CardContent, CardHeader, CardTitle, Checkbox, Input } from '@/components';
import { Trash2, Edit2, Plus, LogOut } from 'lucide-react';

export default function DashboardPage() {
  const router = useRouter();
  const { user, logout } = useAuth();
  const { tasks, filters, setFilters, fetchTasks, createTask, updateTask, deleteTask, isLoading } = useTasks();

  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newTask, setNewTask] = useState({
    title: '',
    description: '',
    dueDate: '',
  });

  useEffect(() => {
    if (!user) {
      router.push('/auth/login');
      return;
    }
    fetchTasks();
  }, [user, router, fetchTasks]);

  const handleCreateTask = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newTask.title.trim()) return;

    try {
      await createTask({
        title: newTask.title,
        description: newTask.description,
        dueDate: newTask.dueDate ? new Date(newTask.dueDate).toISOString() : undefined,
      });
      setNewTask({ title: '', description: '', dueDate: '' });
      setShowCreateForm(false);
      fetchTasks();
    } catch (err) {
      console.error('Error creating task:', err);
    }
  };

  const handleToggleTask = async (taskId: string, completed: boolean) => {
    try {
      await updateTask(taskId, { completed: !completed });
      fetchTasks();
    } catch (err) {
      console.error('Error updating task:', err);
    }
  };

  const handleDeleteTask = async (taskId: string) => {
    if (!confirm('Tem certeza que deseja deletar essa tarefa?')) return;
    try {
      await deleteTask(taskId);
      fetchTasks();
    } catch (err) {
      console.error('Error deleting task:', err);
    }
  };

  const handleLogout = async () => {
    await logout();
    router.push('/auth/login');
  };

  const filteredTasks = tasks.filter((task) => {
    if (filters.completed !== undefined && task.completed !== filters.completed) {
      return false;
    }
    if (filters.category && task.category !== filters.category) {
      return false;
    }
    if (filters.priority && task.priority !== filters.priority) {
      return false;
    }
    return true;
  });

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">📋 Task Manager</h1>
            <p className="text-sm text-gray-600">Bem-vindo, {user?.email}</p>
          </div>
          <Button
            variant="ghost"
            onClick={handleLogout}
            className="flex items-center gap-2"
          >
            <LogOut size={18} />
            Sair
          </Button>
        </div>
      </div>

      {/* Main Content */}
      <div className="max-w-6xl mx-auto px-4 py-8">
        {/* Filters and Create Button */}
        <div className="flex flex-col gap-4 mb-8">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-semibold text-gray-900">Minhas Tarefas</h2>
            <Button
              variant="primary"
              onClick={() => setShowCreateForm(!showCreateForm)}
              className="flex items-center gap-2"
            >
              <Plus size={18} />
              Nova Tarefa
            </Button>
          </div>

          {/* Filters */}
          <div className="flex gap-4 flex-wrap">
            <select
              value={filters.completed !== undefined ? (filters.completed ? 'completed' : 'pending') : 'all'}
              onChange={(e) => {
                const value = e.target.value;
                setFilters({
                  ...filters,
                  completed: value === 'all' ? undefined : value === 'completed',
                });
              }}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">Todas as Tarefas</option>
              <option value="pending">Pendentes</option>
              <option value="completed">Concluídas</option>
            </select>

            <select
              value={filters.priority || 'all'}
              onChange={(e) => {
                const value = e.target.value;
                setFilters({
                  ...filters,
                  priority: value === 'all' ? undefined : (value as 'low' | 'medium' | 'high'),
                });
              }}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">Todas Prioridades</option>
              <option value="low">Baixa</option>
              <option value="medium">Média</option>
              <option value="high">Alta</option>
            </select>

            <select
              value={filters.category || 'all'}
              onChange={(e) => {
                const value = e.target.value;
                setFilters({
                  ...filters,
                  category: value === 'all' ? undefined : value,
                });
              }}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">Todas Categorias</option>
              <option value="work">Trabalho</option>
              <option value="personal">Pessoal</option>
              <option value="health">Saúde</option>
              <option value="shopping">Compras</option>
            </select>
          </div>
        </div>

        {/* Create Task Form */}
        {showCreateForm && (
          <Card className="mb-8">
            <CardHeader>
              <CardTitle>Criar Nova Tarefa</CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleCreateTask} className="space-y-4">
                <Input
                  label="Título"
                  type="text"
                  value={newTask.title}
                  onChange={(e) => setNewTask({ ...newTask, title: e.target.value })}
                  placeholder="Título da tarefa"
                  required
                />

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Descrição
                  </label>
                  <textarea
                    value={newTask.description}
                    onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
                    placeholder="Descrição da tarefa"
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>

                <Input
                  label="Data de Vencimento"
                  type="date"
                  value={newTask.dueDate}
                  onChange={(e) => setNewTask({ ...newTask, dueDate: e.target.value })}
                />

                <div className="flex gap-2">
                  <Button type="submit" variant="primary">
                    Criar Tarefa
                  </Button>
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={() => setShowCreateForm(false)}
                  >
                    Cancelar
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* Tasks List */}
        {isLoading ? (
          <div className="text-center py-12">
            <p className="text-gray-600">Carregando tarefas...</p>
          </div>
        ) : filteredTasks.length === 0 ? (
          <div className="text-center py-12 bg-white rounded-lg border border-gray-200">
            <p className="text-gray-600">Nenhuma tarefa encontrada</p>
            <Button
              variant="primary"
              onClick={() => setShowCreateForm(true)}
              className="mt-4 mx-auto flex items-center gap-2"
            >
              <Plus size={18} />
              Criar sua primeira tarefa
            </Button>
          </div>
        ) : (
          <div className="grid gap-4">
            {filteredTasks.map((task) => (
              <Card key={task.id}>
                <CardContent className="py-4">
                  <div className="flex items-start gap-4">
                    <Checkbox
                      checked={task.completed}
                      onChange={() => handleToggleTask(task.id, task.completed)}
                    />

                    <div className="flex-1">
                      <h3
                        className={`font-medium ${
                          task.completed
                            ? 'line-through text-gray-500'
                            : 'text-gray-900'
                        }`}
                      >
                        {task.title}
                      </h3>
                      {task.description && (
                        <p className="text-sm text-gray-600 mt-1">
                          {task.description}
                        </p>
                      )}

                      <div className="flex gap-2 mt-2 flex-wrap">
                        {task.category && (
                          <span className="inline-block px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded">
                            {task.category}
                          </span>
                        )}
                        {task.priority && (
                          <span
                            className={`inline-block px-2 py-1 text-xs rounded ${
                              task.priority === 'high'
                                ? 'bg-red-100 text-red-800'
                                : task.priority === 'medium'
                                  ? 'bg-yellow-100 text-yellow-800'
                                  : 'bg-green-100 text-green-800'
                            }`}
                          >
                            {task.priority === 'high'
                              ? 'Alta'
                              : task.priority === 'medium'
                                ? 'Média'
                                : 'Baixa'}
                          </span>
                        )}
                        {task.due_date && (
                          <span className="inline-block px-2 py-1 text-xs bg-gray-100 text-gray-800 rounded">
                            {new Date(task.due_date).toLocaleDateString('pt-BR')}
                          </span>
                        )}
                      </div>
                    </div>

                    <div className="flex gap-2">
                      <button
                        onClick={() => handleDeleteTask(task.id)}
                        className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        title="Deletar tarefa"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
