import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Search, Filter, SortAsc } from 'lucide-react';
import { Task } from '@shared/schema';
import TaskCard from './TaskCard';

interface TaskListProps {
  tasks: Task[];
  onTaskUpdate?: (taskId: string, updates: Partial<Task>) => void;
  onTaskEdit?: (task: Task) => void;
}

type SortOption = 'dueDate' | 'priority' | 'title' | 'status';
type FilterOption = 'all' | 'todo' | 'inProgress' | 'done' | 'overdue';

export default function TaskList({ tasks, onTaskUpdate, onTaskEdit }: TaskListProps) {
  const { t } = useTranslation();
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<SortOption>('dueDate');
  const [filterBy, setFilterBy] = useState<FilterOption>('all');

  const isOverdue = (task: Task) => {
    if (!task.dueDate) return false;
    return task.dueDate < new Date() && task.status !== 'done';
  };

  const filteredAndSortedTasks = tasks
    .filter(task => {
      // Search filter
      const matchesSearch = task.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        task.description?.toLowerCase().includes(searchQuery.toLowerCase());

      if (!matchesSearch) return false;

      // Status filter
      switch (filterBy) {
        case 'overdue':
          return isOverdue(task);
        case 'all':
          return true;
        default:
          return task.status === filterBy;
      }
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'dueDate':
          if (!a.dueDate && !b.dueDate) return 0;
          if (!a.dueDate) return 1;
          if (!b.dueDate) return -1;
          return a.dueDate.getTime() - b.dueDate.getTime();

        case 'priority':
          const priorityOrder: Record<string, number> = { high: 3, medium: 2, low: 1 };
          return (priorityOrder[b.priority] || 0) - (priorityOrder[a.priority] || 0);

        case 'title':
          return a.title.localeCompare(b.title);

        case 'status':
          const statusOrder: Record<string, number> = { todo: 1, inProgress: 2, done: 3 };
          return (statusOrder[a.status] || 0) - (statusOrder[b.status] || 0);

        default:
          return 0;
      }
    });

  const getFilterCount = (filter: FilterOption) => {
    switch (filter) {
      case 'overdue':
        return tasks.filter(isOverdue).length;
      case 'all':
        return tasks.length;
      default:
        return tasks.filter(task => task.status === filter).length;
    }
  };

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold" data-testid="text-task-list-title">
          {t('taskList.title')}
        </h2>
        <Badge variant="secondary" data-testid="badge-task-count">
          {t('taskList.taskCount', { count: filteredAndSortedTasks.length })}
        </Badge>
      </div>

      {/* Search and Filters */}
      <div className="space-y-3">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            placeholder={t('taskList.searchPlaceholder')}
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value);
              console.log('Search query:', e.target.value);
            }}
            className="pl-10"
            data-testid="input-search-tasks"
          />
        </div>

        <div className="flex gap-3">
          <Select value={filterBy} onValueChange={(value: FilterOption) => {
            setFilterBy(value);
            console.log('Filter changed to:', value);
          }}>
            <SelectTrigger className="flex-1" data-testid="select-filter">
              <div className="flex items-center gap-2">
                <Filter className="w-4 h-4" />
                <SelectValue />
              </div>
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t('taskList.filter.all')} ({getFilterCount('all')})</SelectItem>
              <SelectItem value="todo">{t('taskList.filter.todo')} ({getFilterCount('todo')})</SelectItem>
              <SelectItem value="inProgress">{t('taskList.filter.inProgress')} ({getFilterCount('inProgress')})</SelectItem>
              <SelectItem value="done">{t('taskList.filter.done')} ({getFilterCount('done')})</SelectItem>
              <SelectItem value="overdue">{t('taskList.filter.overdue')} ({getFilterCount('overdue')})</SelectItem>
            </SelectContent>
          </Select>

          <Select value={sortBy} onValueChange={(value: SortOption) => {
            setSortBy(value);
            console.log('Sort changed to:', value);
          }}>
            <SelectTrigger className="flex-1" data-testid="select-sort">
              <div className="flex items-center gap-2">
                <SortAsc className="w-4 h-4" />
                <SelectValue />
              </div>
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="dueDate">{t('taskList.sort.dueDate')}</SelectItem>
              <SelectItem value="priority">{t('taskList.sort.priority')}</SelectItem>
              <SelectItem value="title">{t('taskList.sort.title')}</SelectItem>
              <SelectItem value="status">{t('taskList.sort.status')}</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Task List */}
      <div className="space-y-3">
        {filteredAndSortedTasks.length === 0 ? (
          <div className="text-center py-8">
            <p className="text-muted-foreground" data-testid="text-no-tasks">
              {searchQuery || filterBy !== 'all'
                ? t('taskList.noMatchingTasks')
                : t('taskList.noTasks')
              }
            </p>
          </div>
        ) : (
          filteredAndSortedTasks.map((task) => (
            <TaskCard
              key={task.id}
              task={task}
              onStartTimer={() => {
                onTaskUpdate?.(task.id, { isTracking: true, timeTracked: task.timeTracked });
                console.log(`Timer started for ${task.title}`);
              }}
              onStopTimer={() => {
                onTaskUpdate?.(task.id, { isTracking: false });
                console.log(`Timer paused for ${task.title}`);
              }}
              onEdit={() => {
                onTaskEdit?.(task);
                console.log(`Edit task ${task.title}`);
              }}
              onStatusChange={(newStatus) => {
                onTaskUpdate?.(task.id, { status: newStatus });
                console.log(`Task ${task.title} status changed to ${newStatus}`);
              }}
            />
          ))
        )}
      </div>
    </div>
  );
}