'use client';

import { useState, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { Task } from '@/lib/types';
import { Search, X, CheckSquare2 } from 'lucide-react';

interface TaskSelectorProps {
  tasks: Task[];
  selectedTaskId?: string;
  onTaskSelect: (task: Task | null) => void;
  placeholder?: string;
  className?: string;
  excludePinnedTasks?: boolean;
  maxHeight?: string;
  loading?: boolean;
}

export function TaskSelector({
  tasks,
  selectedTaskId,
  onTaskSelect,
  placeholder = 'Sélectionner une tâche...',
  className = '',
  excludePinnedTasks = true,
  maxHeight = 'max-h-60',
  loading = false,
}: TaskSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [taskSearch, setTaskSearch] = useState('');
  const [selectedTask, setSelectedTask] = useState<Task | undefined>(undefined);
  const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0 });
  const [positionCalculated, setPositionCalculated] = useState(false);

  const containerRef = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Trouver la tâche sélectionnée
  useEffect(() => {
    if (selectedTaskId) {
      const task = tasks.find((t) => t.id === selectedTaskId);
      setSelectedTask(task);
    } else {
      setSelectedTask(undefined);
    }
  }, [selectedTaskId, tasks]);

  // Calculer la position du dropdown
  useEffect(() => {
    if (isOpen && containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      setDropdownPosition({
        top: rect.bottom + window.scrollY,
        left: rect.left + window.scrollX,
      });
      setPositionCalculated(true);
    } else {
      setPositionCalculated(false);
    }
  }, [isOpen]);

  // Filtrer les tâches selon la recherche et les options
  const filteredTasks = tasks.filter((task) => {
    // Exclure les tâches avec des tags marqués comme "objectif principal" si demandé
    if (
      excludePinnedTasks &&
      task.tagDetails &&
      task.tagDetails.some((tag) => tag.isPinned)
    ) {
      return false;
    }

    // Filtrer selon la recherche
    return (
      task.title.toLowerCase().includes(taskSearch.toLowerCase()) ||
      (task.description &&
        task.description.toLowerCase().includes(taskSearch.toLowerCase()))
    );
  });

  const handleTaskSelect = (task: Task) => {
    setSelectedTask(task);
    onTaskSelect(task);
    setIsOpen(false);
    setTaskSearch('');
  };

  const handleClearTask = () => {
    setSelectedTask(undefined);
    onTaskSelect(null);
  };

  return (
    <div ref={containerRef} className={`relative ${className}`}>
      {/* Trigger Button */}
      <div
        onClick={() => setIsOpen(!isOpen)}
        className="w-full flex items-center justify-between px-3 py-2 text-sm bg-[var(--card)] border border-[var(--border)] rounded-md hover:bg-[var(--card-hover)] transition-colors cursor-pointer"
      >
        <div className="flex items-center gap-2 min-w-0 flex-1">
          {selectedTask ? (
            <>
              <CheckSquare2 className="w-4 h-4 text-[var(--primary)] flex-shrink-0" />
              <span className="truncate text-[var(--foreground)]">
                {selectedTask.title}
              </span>
            </>
          ) : (
            <span className="text-[var(--muted-foreground)]">
              {placeholder}
            </span>
          )}
        </div>
        {selectedTask && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              handleClearTask();
            }}
            className="ml-2 p-1 hover:bg-[var(--destructive)]/10 rounded"
          >
            <X className="w-3 h-3 text-[var(--muted-foreground)]" />
          </button>
        )}
      </div>

      {/* Dropdown Portal */}
      {isOpen &&
        positionCalculated &&
        createPortal(
          <div
            ref={dropdownRef}
            className={`fixed z-[9999] bg-[var(--card)] border border-[var(--border)] rounded-md shadow-lg ${maxHeight} overflow-hidden`}
            style={{
              top: dropdownPosition.top + 4,
              left: dropdownPosition.left,
              width: containerRef.current?.offsetWidth || 300,
            }}
          >
            {/* Search Input */}
            <div className="p-2 border-b border-[var(--border)]">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--muted-foreground)]" />
                <input
                  type="text"
                  placeholder="Rechercher une tâche..."
                  value={taskSearch}
                  onChange={(e) => setTaskSearch(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 text-sm bg-[var(--input)] border border-[var(--border)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--primary)]/20 focus:border-[var(--primary)]"
                  autoFocus
                />
              </div>
            </div>

            {/* Tasks List */}
            <div className="max-h-48 overflow-y-auto">
              {loading ? (
                <div className="p-3 text-center text-[var(--muted-foreground)]">
                  Chargement...
                </div>
              ) : filteredTasks.length === 0 ? (
                <div className="p-3 text-center text-[var(--muted-foreground)]">
                  {taskSearch
                    ? 'Aucune tâche trouvée'
                    : 'Aucune tâche disponible'}
                </div>
              ) : (
                filteredTasks.map((task) => (
                  <button
                    key={task.id}
                    type="button"
                    onClick={() => handleTaskSelect(task)}
                    className="w-full px-3 py-2 text-left hover:bg-[var(--card-hover)] transition-colors flex items-center gap-2"
                  >
                    <CheckSquare2 className="w-4 h-4 text-[var(--primary)] flex-shrink-0" />
                    <div className="min-w-0 flex-1">
                      <div className="text-sm font-medium text-[var(--foreground)] truncate">
                        {task.title}
                      </div>
                      {task.description && (
                        <div className="text-xs text-[var(--muted-foreground)] truncate">
                          {task.description}
                        </div>
                      )}
                    </div>
                    {task.tagDetails && task.tagDetails.length > 0 && (
                      <div className="flex gap-1 flex-shrink-0">
                        {task.tagDetails.slice(0, 2).map((tag) => (
                          <span
                            key={tag.id}
                            className="px-1.5 py-0.5 text-xs rounded"
                            style={{
                              backgroundColor: `${tag.color}20`,
                              color: tag.color,
                            }}
                          >
                            {tag.name}
                          </span>
                        ))}
                      </div>
                    )}
                  </button>
                ))
              )}
            </div>
          </div>,
          document.body
        )}

      {/* Overlay Portal */}
      {isOpen &&
        createPortal(
          <div
            className="fixed inset-0 z-[9998]"
            onClick={() => setIsOpen(false)}
          />,
          document.body
        )}
    </div>
  );
}
