import React, { useEffect, useState } from 'react';
import { useAuth } from '../contexts/AuthContext';
import './Tasks.css';

interface TasksProps {
  onBack: () => void;
}

interface Task {
  id: string;
  title: string;
  description?: string;
  priority: string;
  status: string;
  due_date?: string;
  due_time?: string;
  is_archived: boolean;
}

const Tasks: React.FC<TasksProps> = ({ onBack }) => {
  const { token } = useAuth();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    priority: 'medium',
    status: 'pending',
    due_date: '',
    due_time: ''
  });
  const [stats, setStats] = useState({
    total_tasks: 0,
    pending: 0,
    in_progress: 0,
    completed: 0,
    today_tasks: 0,
    today_completed: 0
  });

  const backendUrl = `${window.location.protocol}//${window.location.host}`;

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

  const loadTasks = async () => {
    try {
      const url = filterStatus === 'all' 
        ? `${backendUrl}/api/v1/tasks/`
        : `${backendUrl}/api/v1/tasks/?status_filter=${filterStatus}`;

      const response = await fetch(url, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setTasks(data);
      }
    } catch (error) {
      console.error('Erro ao carregar tarefas:', error);
    }
  };

  const loadStats = async () => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/tasks/stats/summary`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setStats(data);
      }
    } catch (error) {
      console.error('Erro ao carregar estatísticas:', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    const payload: any = {
      title: formData.title,
      description: formData.description || null,
      priority: formData.priority,
      status: formData.status
    };

    if (formData.due_date) payload.due_date = formData.due_date;
    if (formData.due_time) payload.due_time = formData.due_time;

    try {
      const response = await fetch(`${backendUrl}/api/v1/tasks/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      if (response.ok) {
        alert('Tarefa criada com sucesso! 🎉');
        setShowForm(false);
        setFormData({
          title: '',
          description: '',
          priority: 'medium',
          status: 'pending',
          due_date: '',
          due_time: ''
        });
        loadTasks();
        loadStats();
      } else {
        const error = await response.json();
        alert(`Erro: ${error.detail || 'Não foi possível criar tarefa'}`);
      }
    } catch (error) {
      console.error('Erro ao criar tarefa:', error);
      alert('Erro ao criar tarefa');
    }
  };

  const updateTaskStatus = async (taskId: string, newStatus: string) => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/tasks/${taskId}/status?status=${newStatus}`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        loadTasks();
        loadStats();
      }
    } catch (error) {
      console.error('Erro ao atualizar status:', error);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Deseja realmente deletar esta tarefa?')) return;

    try {
      const response = await fetch(`${backendUrl}/api/v1/tasks/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        loadTasks();
        loadStats();
      }
    } catch (error) {
      console.error('Erro ao deletar tarefa:', error);
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return '#ef4444';
      case 'medium': return '#f59e0b';
      case 'low': return '#10b981';
      default: return '#6b7280';
    }
  };

  const getPriorityLabel = (priority: string) => {
    switch (priority) {
      case 'high': return '🔴 Alta';
      case 'medium': return '🟡 Média';
      case 'low': return '🟢 Baixa';
      default: return priority;
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'pending': return '⏳ Pendente';
      case 'in_progress': return '🔄 Em Progresso';
      case 'completed': return '✅ Concluída';
      default: return status;
    }
  };

  return (
    <div className="tasks-page">
      <header className="tasks-header">
        <button onClick={onBack} className="back-button">← Voltar</button>
        <h1>📝 Tarefas</h1>
        <button onClick={() => setShowForm(!showForm)} className="add-button">
          {showForm ? '❌ Cancelar' : '➕ Nova Tarefa'}
        </button>
      </header>

      <div className="tasks-container">
        {/* Stats */}
        <section className="tasks-stats">
          <div className="stat-box">
            <span className="stat-label">Total</span>
            <span className="stat-value">{stats.total_tasks}</span>
          </div>
          <div className="stat-box pending">
            <span className="stat-label">Pendentes</span>
            <span className="stat-value">{stats.pending}</span>
          </div>
          <div className="stat-box progress">
            <span className="stat-label">Em Progresso</span>
            <span className="stat-value">{stats.in_progress}</span>
          </div>
          <div className="stat-box completed">
            <span className="stat-label">Concluídas</span>
            <span className="stat-value">{stats.completed}</span>
          </div>
          <div className="stat-box today">
            <span className="stat-label">Hoje</span>
            <span className="stat-value">{stats.today_completed}/{stats.today_tasks}</span>
          </div>
        </section>

        {/* Formulário */}
        {showForm && (
          <section className="tasks-form">
            <h2>➕ Nova Tarefa</h2>
            <form onSubmit={handleSubmit}>
              <div className="form-group">
                <label>Título *</label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={e => setFormData({ ...formData, title: e.target.value })}
                  placeholder="Ex: Fazer exercícios"
                  required
                />
              </div>

              <div className="form-group">
                <label>Descrição</label>
                <textarea
                  value={formData.description}
                  onChange={e => setFormData({ ...formData, description: e.target.value })}
                  placeholder="Descreva os detalhes da tarefa..."
                  rows={3}
                />
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>Prioridade</label>
                  <select
                    value={formData.priority}
                    onChange={e => setFormData({ ...formData, priority: e.target.value })}
                  >
                    <option value="low">🟢 Baixa</option>
                    <option value="medium">🟡 Média</option>
                    <option value="high">🔴 Alta</option>
                  </select>
                </div>

                <div className="form-group">
                  <label>Status</label>
                  <select
                    value={formData.status}
                    onChange={e => setFormData({ ...formData, status: e.target.value })}
                  >
                    <option value="pending">⏳ Pendente</option>
                    <option value="in_progress">🔄 Em Progresso</option>
                    <option value="completed">✅ Concluída</option>
                  </select>
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>Data</label>
                  <input
                    type="date"
                    value={formData.due_date}
                    onChange={e => setFormData({ ...formData, due_date: e.target.value })}
                  />
                </div>
                <div className="form-group">
                  <label>Horário</label>
                  <input
                    type="time"
                    value={formData.due_time}
                    onChange={e => setFormData({ ...formData, due_time: e.target.value })}
                  />
                </div>
              </div>

              <button type="submit" className="submit-button">
                💾 Criar Tarefa
              </button>
            </form>
          </section>
        )}

        {/* Filtros */}
        <section className="tasks-filters">
          <button 
            className={filterStatus === 'all' ? 'active' : ''}
            onClick={() => setFilterStatus('all')}
          >
            Todas
          </button>
          <button 
            className={filterStatus === 'pending' ? 'active' : ''}
            onClick={() => setFilterStatus('pending')}
          >
            ⏳ Pendentes
          </button>
          <button 
            className={filterStatus === 'in_progress' ? 'active' : ''}
            onClick={() => setFilterStatus('in_progress')}
          >
            🔄 Em Progresso
          </button>
          <button 
            className={filterStatus === 'completed' ? 'active' : ''}
            onClick={() => setFilterStatus('completed')}
          >
            ✅ Concluídas
          </button>
        </section>

        {/* Lista de tarefas */}
        <section className="tasks-list">
          {tasks.length === 0 ? (
            <p className="empty-message">
              Nenhuma tarefa encontrada. Crie sua primeira tarefa! 🚀
            </p>
          ) : (
            <div className="tasks-grid">
              {tasks.map(task => (
                <div key={task.id} className={`task-card ${task.status}`}>
                  <div className="task-header">
                    <h3>{task.title}</h3>
                    <span 
                      className="priority-badge"
                      style={{ background: getPriorityColor(task.priority) }}
                    >
                      {getPriorityLabel(task.priority)}
                    </span>
                  </div>

                  {task.description && (
                    <p className="task-description">{task.description}</p>
                  )}

                  <div className="task-meta">
                    {task.due_date && (
                      <span className="task-date">
                        📅 {new Date(task.due_date).toLocaleDateString('pt-BR')}
                        {task.due_time && ` às ${task.due_time}`}
                      </span>
                    )}
                  </div>

                  <div className="task-actions">
                    <select
                      value={task.status}
                      onChange={(e) => updateTaskStatus(task.id, e.target.value)}
                      className="status-select"
                    >
                      <option value="pending">⏳ Pendente</option>
                      <option value="in_progress">🔄 Em Progresso</option>
                      <option value="completed">✅ Concluída</option>
                    </select>
                    <button 
                      onClick={() => handleDelete(task.id)} 
                      className="delete-btn"
                      title="Deletar"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      </div>
    </div>
  );
};

export default Tasks;

