import React, { useState } from 'react';
import { X, CheckCircle2, Clock, User, Calendar, Send, Play } from 'lucide-react';
import { toast } from 'react-toastify';
import { Task } from '../services/taskService';
import taskService from '../services/taskService';
import { formatDate } from '../../../shared/utils/format';

interface TaskDetailModalProps {
  task: Task;
  onClose: () => void;
  onUpdate: () => void;
}

const TaskDetailModal: React.FC<TaskDetailModalProps> = ({ task, onClose, onUpdate }) => {
  const [comment, setComment] = useState('');
  const [loading, setLoading] = useState(false);
  const [taskData, setTaskData] = useState<Task>(task);

  const handleAddComment = async () => {
    if (!comment.trim()) return;

    try {
      setLoading(true);
      await taskService.addTaskComment(taskData.id, comment);
      const updatedTask = await taskService.getTask(taskData.id);
      setTaskData(updatedTask.data.data);
      setComment('');
      toast.success('Comment added');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to add comment');
    } finally {
      setLoading(false);
    }
  };

  const handleStartTask = async () => {
    try {
      setLoading(true);
      await taskService.startTask(taskData.id);
      const updatedTask = await taskService.getTask(taskData.id);
      setTaskData(updatedTask.data.data);
      onUpdate();
      toast.success('Task started');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to start task');
    } finally {
      setLoading(false);
    }
  };

  const handleCompleteTask = async () => {
    try {
      setLoading(true);
      await taskService.completeTask(taskData.id);
      const updatedTask = await taskService.getTask(taskData.id);
      setTaskData(updatedTask.data.data);
      onUpdate();
      toast.success('Task completed');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to complete task');
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'text-green-600 bg-green-50 border-green-200';
      case 'in_progress':
        return 'text-blue-600 bg-blue-50 border-blue-200';
      case 'overdue':
        return 'text-red-600 bg-red-50 border-red-200';
      default:
        return 'text-amber-600 bg-amber-50 border-amber-200';
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'urgent':
        return 'text-red-600 bg-red-50 border-red-200';
      case 'high':
        return 'text-orange-600 bg-orange-50 border-orange-200';
      case 'medium':
        return 'text-yellow-600 bg-yellow-50 border-yellow-200';
      default:
        return 'text-gray-600 bg-gray-50 border-gray-200';
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 p-6 flex items-center justify-between">
          <h2 className="text-2xl font-bold text-gray-900">{taskData.title}</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Status and Priority */}
          <div className="flex items-center gap-4">
            <span className={`px-3 py-1 rounded-full text-sm font-semibold border ${getStatusColor(taskData.status)}`}>
              {taskData.status.replace('_', ' ')}
            </span>
            <span className={`px-3 py-1 rounded-full text-sm font-semibold border ${getPriorityColor(taskData.priority)}`}>
              {taskData.priority}
            </span>
          </div>

          {/* Description */}
          {taskData.description && (
            <div>
              <h3 className="text-sm font-semibold text-gray-700 mb-2">Description</h3>
              <p className="text-gray-600">{taskData.description}</p>
            </div>
          )}

          {/* Details Grid */}
          <div className="grid grid-cols-2 gap-4">
            <div className="flex items-center gap-2">
              <User className="w-5 h-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Assigned To</p>
                <p className="text-sm font-medium text-gray-900">
                  {taskData.assigned_to_name || 'Unassigned'}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Calendar className="w-5 h-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Due Date</p>
                <p className="text-sm font-medium text-gray-900">
                  {taskData.due_date ? formatDate(new Date(taskData.due_date), 'short') : 'No due date'}
                </p>
              </div>
            </div>
            {taskData.completed_at && (
              <div className="flex items-center gap-2">
                <CheckCircle2 className="w-5 h-5 text-green-500" />
                <div>
                  <p className="text-xs text-gray-500">Completed At</p>
                  <p className="text-sm font-medium text-gray-900">
                    {formatDate(new Date(taskData.completed_at), 'short')}
                  </p>
                </div>
              </div>
            )}
            {taskData.actual_duration_minutes && (
              <div className="flex items-center gap-2">
                <Clock className="w-5 h-5 text-gray-400" />
                <div>
                  <p className="text-xs text-gray-500">Duration</p>
                  <p className="text-sm font-medium text-gray-900">
                    {taskData.actual_duration_minutes} minutes
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Notes */}
          {taskData.notes && (
            <div>
              <h3 className="text-sm font-semibold text-gray-700 mb-2">Notes</h3>
              <p className="text-gray-600 whitespace-pre-wrap">{taskData.notes}</p>
            </div>
          )}

          {/* Comments */}
          <div>
            <h3 className="text-sm font-semibold text-gray-700 mb-4">Comments</h3>
            <div className="space-y-4">
              {taskData.comments && taskData.comments.length > 0 ? (
                taskData.comments.map((comment) => (
                  <div key={comment.id} className="bg-gray-50 rounded-lg p-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-sm font-semibold text-gray-900">{comment.user_name}</p>
                      <p className="text-xs text-gray-500">
                        {formatDate(new Date(comment.created_at), 'short')}
                      </p>
                    </div>
                    <p className="text-sm text-gray-700">{comment.comment}</p>
                  </div>
                ))
              ) : (
                <p className="text-sm text-gray-500">No comments yet</p>
              )}
            </div>

            {/* Add Comment */}
            <div className="mt-4 flex gap-2">
              <input
                type="text"
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleAddComment()}
                placeholder="Add a comment..."
                className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
              <button
                onClick={handleAddComment}
                disabled={loading || !comment.trim()}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Send className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>

        {/* Footer Actions */}
        <div className="sticky bottom-0 bg-gray-50 border-t border-gray-200 p-6 flex items-center justify-end gap-3">
          {taskData.status === 'assigned' && (
            <button
              onClick={handleStartTask}
              disabled={loading}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
            >
              <Play className="w-4 h-4" />
              Start Task
            </button>
          )}
          {taskData.status === 'in_progress' && (
            <button
              onClick={handleCompleteTask}
              disabled={loading}
              className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2"
            >
              <CheckCircle2 className="w-4 h-4" />
              Complete Task
            </button>
          )}
          <button
            onClick={onClose}
            className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
};

export default TaskDetailModal;

