'use client';

import { useState, useEffect } from 'react';
import { Task } from '@/lib/types';
import { Button } from '@/components/ui/Button';
import { Search, X, CheckSquare2 } from 'lucide-react';

// Données mock pour le showcase
const mockTasks: Task[] = [
  {
    id: '1',
    title: 'Implement user authentication',
    description: 'Add login and registration functionality',
    priority: 'high',
    status: 'in_progress',
    dueDate: new Date(Date.now() + 3 * 86400000),
    tags: ['auth', 'security'],
    createdAt: new Date(),
    updatedAt: new Date(),
    source: 'manual',
    sourceId: '1',
    tagDetails: [],
    ownerId: 'mock-user-1',
  },
  {
    id: '2',
    title: 'Design new dashboard',
    description: 'Create a modern dashboard interface',
    priority: 'medium',
    status: 'todo',
    dueDate: new Date(Date.now() + 7 * 86400000),
    tags: ['design', 'ui'],
    createdAt: new Date(),
    updatedAt: new Date(),
    source: 'manual',
    sourceId: '2',
    tagDetails: [],
    ownerId: 'mock-user-1',
  },
  {
    id: '3',
    title: 'Fix critical bug in payment system',
    description: 'Resolve issue with payment processing',
    priority: 'high',
    status: 'todo',
    dueDate: new Date(Date.now() + 1 * 86400000),
    tags: ['bug', 'payment'],
    createdAt: new Date(),
    updatedAt: new Date(),
    source: 'manual',
    sourceId: '3',
    tagDetails: [],
    ownerId: 'mock-user-1',
  },
  {
    id: '4',
    title: 'Write unit tests',
    description: 'Add comprehensive test coverage',
    priority: 'medium',
    status: 'done',
    dueDate: new Date(Date.now() - 2 * 86400000),
    tags: ['testing', 'quality'],
    createdAt: new Date(),
    updatedAt: new Date(),
    source: 'manual',
    sourceId: '4',
    tagDetails: [],
    ownerId: 'mock-user-1',
  },
  {
    id: '5',
    title: 'Update documentation',
    description: 'Refresh API documentation',
    priority: 'low',
    status: 'todo',
    dueDate: new Date(Date.now() + 14 * 86400000),
    tags: ['documentation'],
    createdAt: new Date(),
    updatedAt: new Date(),
    source: 'manual',
    sourceId: '5',
    tagDetails: [],
    ownerId: 'mock-user-1',
  },
];

// Composant TaskSelector mock pour le showcase
interface MockTaskSelectorProps {
  selectedTaskId?: string;
  onTaskSelect: (task: Task | null) => void;
  placeholder?: string;
  className?: string;
}

function MockTaskSelector({
  selectedTaskId,
  onTaskSelect,
  placeholder = 'Sélectionner une tâche...',
  className = '',
}: MockTaskSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [taskSearch, setTaskSearch] = useState('');
  const [selectedTask, setSelectedTask] = useState<Task | undefined>(undefined);

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

  // Filtrer les tâches selon la recherche
  const filteredTasks = mockTasks.filter((task) => {
    return (
      task.title.toLowerCase().includes(taskSearch.toLowerCase()) ||
      (task.description &&
        task.description.toLowerCase().includes(taskSearch.toLowerCase()))
    );
  });

  const handleTaskSelect = (task: Task) => {
    console.log('Task selected:', task.title); // Debug
    setSelectedTask(task);
    onTaskSelect(task);
    setIsOpen(false);
    setTaskSearch('');
  };

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

  return (
    <div className={`relative ${className}`}>
      {/* Trigger Button */}
      <div
        onClick={() => {
          console.log('Dropdown clicked, isOpen:', isOpen); // Debug
          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 Simple pour le showcase */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[var(--card)] border border-[var(--border)] rounded-md shadow-lg max-h-60 overflow-hidden z-50">
          {/* 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">
            {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.tags && task.tags.length > 0 && (
                    <div className="flex gap-1 flex-shrink-0">
                      {task.tags.slice(0, 2).map((tag) => (
                        <span
                          key={tag}
                          className="px-1.5 py-0.5 text-xs rounded bg-[var(--primary)]/20 text-[var(--primary)]"
                        >
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export function TaskSelectorSection() {
  const [selectedTask, setSelectedTask] = useState<Task | null>(null);

  const handleTaskSelect = (task: Task | null) => {
    setSelectedTask(task);
  };

  return (
    <section id="task-selector" className="space-y-8">
      <h2 className="text-2xl font-mono font-semibold text-[var(--foreground)] border-b border-[var(--border)] pb-3">
        Task Selector
      </h2>

      <div className="space-y-8">
        {/* Basic Task Selector */}
        <div className="space-y-4">
          <h3 className="text-lg font-medium text-[var(--foreground)]">
            Basic Task Selector
          </h3>
          <div className="space-y-4">
            <MockTaskSelector
              selectedTaskId={selectedTask?.id}
              onTaskSelect={handleTaskSelect}
              placeholder="Sélectionner une tâche..."
              className="max-w-md"
            />

            {selectedTask && (
              <div className="bg-[var(--card)] rounded-lg border border-[var(--border)] p-4">
                <h4 className="font-medium text-[var(--foreground)] mb-2">
                  Tâche sélectionnée
                </h4>
                <div className="text-sm text-[var(--foreground)]">
                  <strong>Titre:</strong> {selectedTask.title}
                </div>
                {selectedTask.description && (
                  <div className="text-sm text-[var(--muted-foreground)] mt-1">
                    <strong>Description:</strong> {selectedTask.description}
                  </div>
                )}
                <div className="text-sm text-[var(--muted-foreground)] mt-1">
                  <strong>Priorité:</strong> {selectedTask.priority}
                </div>
                <div className="text-sm text-[var(--muted-foreground)] mt-1">
                  <strong>Statut:</strong> {selectedTask.status}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Task Selector States */}
        <div className="space-y-4">
          <h3 className="text-lg font-medium text-[var(--foreground)]">
            États du Task Selector
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Avec tâche sélectionnée */}
            <div className="space-y-3">
              <h4 className="text-md font-medium text-[var(--foreground)]">
                Avec sélection
              </h4>
              <MockTaskSelector
                selectedTaskId="1"
                onTaskSelect={() => {}}
                placeholder="Tâche pré-sélectionnée..."
                className="max-w-sm"
              />
            </div>

            {/* Sans sélection */}
            <div className="space-y-3">
              <h4 className="text-md font-medium text-[var(--foreground)]">
                Sans sélection
              </h4>
              <MockTaskSelector
                selectedTaskId={undefined}
                onTaskSelect={() => {}}
                placeholder="Aucune tâche sélectionnée..."
                className="max-w-sm"
              />
            </div>
          </div>
        </div>

        {/* Utilisation dans un formulaire */}
        <div className="space-y-4">
          <h3 className="text-lg font-medium text-[var(--foreground)]">
            Utilisation dans un formulaire
          </h3>
          <div className="bg-[var(--card)] rounded-lg border border-[var(--border)] p-6">
            <form className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-[var(--foreground)] mb-2">
                  Tâche à assigner
                </label>
                <MockTaskSelector
                  selectedTaskId={selectedTask?.id}
                  onTaskSelect={handleTaskSelect}
                  placeholder="Sélectionner une tâche à assigner..."
                  className="max-w-md"
                />
              </div>

              <div className="flex gap-2">
                <Button
                  type="submit"
                  variant="primary"
                  disabled={!selectedTask}
                >
                  Assigner{' '}
                  {selectedTask ? `"${selectedTask.title}"` : 'une tâche'}
                </Button>
                <Button
                  type="button"
                  variant="secondary"
                  onClick={() => setSelectedTask(null)}
                >
                  Effacer la sélection
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}
