import React, { useState } from 'react';
import {Plant, Task, TaskTitles} from '../types';
import { Plus, Calendar, CheckCircle, Clock, Edit, Trash2, FileText, Sprout, Beaker } from 'lucide-react';
import TaskForm from './TaskForm';
import { apiService } from '../services/api';

interface TaskPlannerProps {
  tasks: Task[];
  plants: Plant[];
  onTasksChange: (tasks: Task[]) => void;
}

const TaskPlanner: React.FC<TaskPlannerProps> = ({ tasks, plants, onTasksChange }) => {
  const [showTaskForm, setShowTaskForm] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [filter, setFilter] = useState<'all' | 'pending' | 'completed'>('all');

  const filteredTasks = tasks.filter(task => {
    if (filter === 'pending') return !task.completed;
    if (filter === 'completed') return task.completed;
    return true;
  }).sort((a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime());

  const handleSaveTask = async (taskData: Omit<Task, 'id' | 'createdAt' | 'updatedAt' | 'fertilizerName' | 'chemicalName'>) => {
    try {
      if (editingTask) {
        const updatedTask = await apiService.updateTask(editingTask.id, taskData);
        onTasksChange(tasks.map(t => t.id === editingTask.id ? updatedTask : t));
      } else {
        const newTask = await apiService.createTask(taskData);
        onTasksChange([...tasks, newTask]);
      }
      setShowTaskForm(false);
      setEditingTask(null);
    } catch (error) {
      console.error('Error saving task:', error);
    }
  };

  const handleToggleComplete = async (taskId: number) => {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      try {
        const updatedTask = await apiService.updateTask(taskId, { completed: !task.completed });
        onTasksChange(tasks.map(t => t.id === taskId ? updatedTask : t));
      } catch (error) {
        console.error('Error updating task:', error);
      }
    }
  };

  const handleDeleteTask = async (taskId: number) => {
    if (window.confirm('Are you sure you want to delete this task?')) {
      try {
        await apiService.deleteTask(taskId);
        onTasksChange(tasks.filter(t => t.id !== taskId));
      } catch (error) {
        console.error('Error deleting task:', error);
      }
    }
  };

  const getTaskTypeIcon = (type?: string) => {
    switch (type) {
      case 'fertilizer': return Sprout;
      case 'chemical': return Beaker;
      case 'watering': return FileText;
      case 'pruning': return FileText;
      case 'transplanting': return FileText;
      case 'harvesting': return FileText;
      case 'other': return FileText;
      default: return FileText;
    }
  };

  const getTaskTypeColor = (type?: string) => {
    switch (type) {
      case 'fertilizer': return 'text-green-600';
      case 'chemical': return 'text-red-600';
      case 'watering': return 'text-blue-600';
      case 'pruning': return 'text-purple-600';
      case 'transplanting': return 'text-orange-600';
      case 'harvesting': return 'text-yellow-600';
      case 'other': return 'text-gray-600';
      default: return 'text-gray-600';
    }
  };

  const getTaskStatus = (task: Task) => {
    if (task.completed) return 'completed';
    if (new Date(task.deadline) < new Date()) return 'overdue';
    return 'pending';
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'text-green-600';
      case 'overdue': return 'text-red-600';
      case 'pending': return 'text-yellow-600';
      default: return 'text-gray-600';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return CheckCircle;
      case 'overdue': return Clock;
      case 'pending': return Calendar;
      default: return Calendar;
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-3xl font-bold text-green-800">План работ</h2>
          <p className="text-green-600 mt-1">Планируйте и отслеживайте свои задачи по уходу за садом</p>
        </div>
        <button
          onClick={() => setShowTaskForm(true)}
          className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg flex items-center space-x-2 transition-colors"
        >
          <Plus className="h-4 w-4" />
          <span>Новая работа</span>
        </button>
      </div>

      {/* Filter Tabs */}
      <div className="bg-white rounded-lg shadow-sm border border-green-100">
        <div className="flex border-b border-green-100">
          {[
            { key: 'all', label: 'Все работы', count: tasks.length },
            { key: 'pending', label: 'Отложенные', count: tasks.filter(t => !t.completed).length },
            { key: 'completed', label: 'Выполненные', count: tasks.filter(t => t.completed).length }
          ].map((tab) => (
            <button
              key={tab.key}
              onClick={() => setFilter(tab.key as any)}
              className={`flex-1 px-6 py-4 text-sm font-medium transition-colors ${
                filter === tab.key
                  ? 'text-green-600 border-b-2 border-green-600 bg-green-50'
                  : 'text-gray-600 hover:text-green-600 hover:bg-green-50'
              }`}
            >
              {tab.label} ({tab.count})
            </button>
          ))}
        </div>
      </div>

      {/* Tasks List */}
      <div className="space-y-4">
        {filteredTasks.map((task) => {
          const plant = plants.find(p => p.id === task.plantId);
          const status = getTaskStatus(task);
          const StatusIcon = getStatusIcon(status);
          const TaskTypeIcon = getTaskTypeIcon(task.type);

          return (
            <div
              key={task.id}
              className={`bg-white rounded-lg shadow-sm border border-green-100 p-6 hover:shadow-md transition-shadow ${
                task.completed ? 'opacity-75' : ''
              }`}
            >
              <div className="flex items-start justify-between">
                <div className="flex items-start space-x-4 flex-1">
                  <button
                    onClick={() => handleToggleComplete(task.id)}
                    className={`mt-1 p-1 rounded-full transition-colors ${
                      task.completed 
                        ? 'text-green-600 hover:text-green-700'
                        : 'text-gray-400 hover:text-green-600'
                    }`}
                  >
                    <CheckCircle className={`h-5 w-5 ${task.completed ? 'fill-current' : ''}`} />
                  </button>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-3 mb-2">
                      <div className="flex items-center space-x-2">
                        <TaskTypeIcon className={`h-4 w-4 ${getTaskTypeColor(task.type)}`} />
                        <span className={`text-xs font-medium capitalize ${getTaskTypeColor(task.type)}`}>
                          {TaskTitles[task.type || 'general']}
                        </span>
                      </div>
                      <h3 className={`text-lg font-semibold ${task.completed ? 'line-through text-gray-500' : 'text-gray-900'}`}>
                        {task.title}
                      </h3>
                      <div className="flex items-center space-x-1">
                        <StatusIcon className={`h-4 w-4 ${getStatusColor(status)}`} />
                        <span className={`text-sm font-medium capitalize ${getStatusColor(status)}`}>
                          {status}
                        </span>
                      </div>
                    </div>

                    {plant && (
                      <p className="text-sm text-gray-600 mb-2">
                        Растение: <span className="font-medium">{plant.variety}</span>
                      </p>
                    )}

                    {task.fertilizerName && (
                      <p className="text-sm text-green-600 mb-2">
                        Fertilizer: <span className="font-medium">{task.fertilizerName}</span>
                      </p>
                    )}

                    {task.chemicalName && (
                      <p className="text-sm text-red-600 mb-2">
                        Chemical: <span className="font-medium">{task.chemicalName}</span>
                      </p>
                    )}
                    <p className="text-gray-700 mb-3">{task.description}</p>

                    <div className="flex items-center space-x-4 text-sm text-gray-500">
                      <div className="flex items-center space-x-1">
                        <Calendar className="h-4 w-4" />
                        <span>Due: {new Date(task.deadline).toLocaleDateString()}</span>
                      </div>
                      {new Date(task.deadline) < new Date() && !task.completed && (
                        <span className="text-red-600 font-medium">Overdue</span>
                      )}
                    </div>
                  </div>
                </div>

                <div className="flex space-x-2 ml-4">
                  <button
                    onClick={() => {
                      setEditingTask(task);
                      setShowTaskForm(true);
                    }}
                    className="p-1 text-blue-600 hover:text-blue-700 transition-colors"
                  >
                    <Edit className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => handleDeleteTask(task.id)}
                    className="p-1 text-red-600 hover:text-red-700 transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {filteredTasks.length === 0 && (
        <div className="text-center py-12">
          <p className="text-gray-500 text-lg">
            {filter === 'all' ? 'No tasks created yet.' : `No ${filter} tasks.`}
          </p>
          <button
            onClick={() => setShowTaskForm(true)}
            className="mt-4 text-green-600 hover:text-green-700 transition-colors"
          >
            Create your first task →
          </button>
        </div>
      )}

      {/* Task Form Modal */}
      {showTaskForm && (
        <TaskForm
          isOpen={showTaskForm}
          onClose={() => {
            setShowTaskForm(false);
            setEditingTask(null);
          }}
          onSubmit={handleSaveTask}
          task={editingTask ?? undefined}
        />
      )}
    </div>
  );
};

export default TaskPlanner;