import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { LayoutGrid, Calendar as CalendarIcon, ChevronLeft, ChevronRight, Filter, X, Tag, AlertTriangle } from 'lucide-react';
import { Task, Label } from '@shared/schema';
import TaskCard from './TaskCard';
import { useQuery } from '@tanstack/react-query';
import { format, startOfWeek, endOfWeek, startOfMonth, endOfMonth, addWeeks, addMonths, isWithinInterval } from 'date-fns';
import { de, enUS } from 'date-fns/locale';

interface KanbanBoardProps {
  tasks: Task[];
  onTaskStatusChange?: (taskId: string, newStatus: Task['status']) => void;
  onTaskUpdate?: (taskId: string, updates: Partial<Task>) => void;
  onTaskClick?: (task: Task) => void;
  onTaskEdit?: (task: Task) => void;
  onTaskDelete?: (taskId: string) => void;
  onStartTimer?: (taskId: string) => void;
  onStopTimer?: (taskId: string) => void;
}

type ViewMode = 'traditional' | 'weekly' | 'monthly';

export default function KanbanBoard({ tasks, onTaskStatusChange, onTaskUpdate, onTaskClick, onTaskDelete, onStartTimer, onStopTimer }: KanbanBoardProps) {
  const { t, i18n } = useTranslation();
  const [viewMode, setViewMode] = useState<ViewMode>('traditional');
  const [currentDate, setCurrentDate] = useState(new Date());
  const [draggedTask, setDraggedTask] = useState<string | null>(null);

  // Filter state
  const [selectedLabels, setSelectedLabels] = useState<string[]>([]);
  const [selectedPriorities, setSelectedPriorities] = useState<string[]>([]);

  // Get date-fns locale based on current language
  const dateLocale = i18n.language === 'de' ? de : enUS;

  // Fetch labels to get label colors
  const { data: labels = [] } = useQuery<Label[]>({
    queryKey: ['/api/labels'],
    staleTime: 5 * 60 * 1000, // 5 minutes cache
    refetchOnWindowFocus: false,
  });

  const columns = [
    { id: 'todo', title: t('kanban.todo'), status: 'todo' as const },
    { id: 'inProgress', title: t('kanban.inProgress'), status: 'inProgress' as const },
    { id: 'done', title: t('kanban.done'), status: 'done' as const }
  ];

  const getTasksForColumn = (status: Task['status']) => {
    let filteredTasks = tasks.filter(task => task.status === status);

    // Apply label filtering
    if (selectedLabels.length > 0) {
      filteredTasks = filteredTasks.filter(task =>
        task.labelId && selectedLabels.includes(task.labelId)
      );
    }

    // Apply priority filtering
    if (selectedPriorities.length > 0) {
      filteredTasks = filteredTasks.filter(task =>
        selectedPriorities.includes(task.priority)
      );
    }

    // Apply date filtering for weekly/monthly views
    if (viewMode === 'weekly') {
      const weekStart = startOfWeek(currentDate, { weekStartsOn: 1 }); // Monday = 1
      const weekEnd = endOfWeek(currentDate, { weekStartsOn: 1 });
      filteredTasks = filteredTasks.filter(task =>
        task.dueDate && isWithinInterval(task.dueDate, { start: weekStart, end: weekEnd })
      );
    } else if (viewMode === 'monthly') {
      const monthStart = startOfMonth(currentDate);
      const monthEnd = endOfMonth(currentDate);
      filteredTasks = filteredTasks.filter(task =>
        task.dueDate && isWithinInterval(task.dueDate, { start: monthStart, end: monthEnd })
      );
    }

    return filteredTasks;
  };

  const handleDragStart = (taskId: string) => {
    setDraggedTask(taskId);
  };

  const handleDragEnd = () => {
    setDraggedTask(null);
  };

  const handleDrop = (status: Task['status']) => {
    if (draggedTask) {
      onTaskStatusChange?.(draggedTask, status);
      console.log(`Task ${draggedTask} moved to ${status}`);
      setDraggedTask(null);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const navigatePeriod = (direction: 'prev' | 'next') => {
    if (viewMode === 'weekly') {
      setCurrentDate(addWeeks(currentDate, direction === 'next' ? 1 : -1));
      console.log(`Navigating to week of ${format(addWeeks(currentDate, direction === 'next' ? 1 : -1), 'd.M.yyyy')}`);
    } else if (viewMode === 'monthly') {
      setCurrentDate(addMonths(currentDate, direction === 'next' ? 1 : -1));
      console.log(`Navigating to month of ${format(addMonths(currentDate, direction === 'next' ? 1 : -1), 'MMM yyyy')}`);
    }
  };

  const getPeriodTitle = () => {
    if (viewMode === 'weekly') {
      return t('kanban.weekOf', { date: format(startOfWeek(currentDate, { weekStartsOn: 1 }), 'MMM d', { locale: dateLocale }) });
    } else if (viewMode === 'monthly') {
      return format(currentDate, 'MMMM yyyy', { locale: dateLocale });
    }
    return t('kanban.allTasks');
  };

  // Filter management functions
  const toggleLabel = (labelId: string) => {
    setSelectedLabels(prev =>
      prev.includes(labelId)
        ? prev.filter(id => id !== labelId)
        : [...prev, labelId]
    );
  };

  const togglePriority = (priority: string) => {
    setSelectedPriorities(prev =>
      prev.includes(priority)
        ? prev.filter(p => p !== priority)
        : [...prev, priority]
    );
  };

  const clearAllFilters = () => {
    setSelectedLabels([]);
    setSelectedPriorities([]);
  };

  const hasActiveFilters = selectedLabels.length > 0 || selectedPriorities.length > 0;

  const priorities = ['high', 'medium', 'low'];

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'bg-destructive text-destructive-foreground';
      case 'medium': return 'bg-yellow-500 text-white';
      default: return 'bg-muted text-muted-foreground';
    }
  };


  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="sticky top-0 z-40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b pb-2 sm:pb-3 mb-3 sm:mb-4 pt-4">
        <div className="flex items-center justify-between mb-3 sm:mb-4">
          <div className="flex items-center gap-2">
            <LayoutGrid className="w-4 h-4 sm:w-5 sm:h-5 text-primary" />
            <h2 className="text-base sm:text-lg font-semibold" data-testid="text-kanban-title">
              {t('kanban.title')}
            </h2>
          </div>

          {viewMode !== 'traditional' && (
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={() => navigatePeriod('prev')}
                data-testid="button-prev-period"
                className="h-11 w-11"
              >
                <ChevronLeft className="w-4 h-4" />
              </Button>

              <span className="text-sm font-medium min-w-[120px] text-center">
                {getPeriodTitle()}
              </span>

              <Button
                variant="outline"
                size="icon"
                onClick={() => navigatePeriod('next')}
                data-testid="button-next-period"
                className="h-11 w-11"
              >
                <ChevronRight className="w-4 h-4" />
              </Button>
            </div>
          )}
        </div>

        {/* Filter Bar */}
        <Card className="p-3 sm:p-4">
          <div className="flex items-center justify-between flex-wrap gap-3 sm:gap-4">
            <div className="flex items-center gap-2">
              <Filter className="w-4 h-4 text-muted-foreground" />
              <span className="text-sm font-medium">{t('kanban.filters')}</span>
              {hasActiveFilters && (
                <Badge variant="secondary" className="text-xs">
                  {selectedLabels.length + selectedPriorities.length}
                </Badge>
              )}
            </div>

            <div className="flex items-center gap-3 flex-wrap">
              {/* Labels Filter */}
              <div className="flex items-center gap-2">
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="justify-start"
                      data-testid="button-filter-labels"
                    >
                      <Tag className="w-4 h-4 mr-2" />
                      {t('kanban.labels')}
                      {selectedLabels.length > 0 && (
                        <Badge variant="secondary" className="ml-2 text-xs">
                          {selectedLabels.length}
                        </Badge>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-56" align="start">
                    <div className="space-y-2">
                      <h4 className="text-sm font-medium">{t('kanban.filterByLabels')}</h4>
                      <Separator />
                      <div className="space-y-2 max-h-48 overflow-y-auto">
                        {labels.length > 0 ? (
                          labels.map((label) => (
                            <div
                              key={label.id}
                              className="flex items-center space-x-2"
                            >
                              <Checkbox
                                id={`label-${label.id}`}
                                checked={selectedLabels.includes(label.id)}
                                onCheckedChange={() => toggleLabel(label.id)}
                                data-testid={`checkbox-label-${label.id}`}
                              />
                              <label
                                htmlFor={`label-${label.id}`}
                                className="flex items-center space-x-2 text-sm cursor-pointer flex-1"
                              >
                                <div
                                  className="w-3 h-3 rounded-full"
                                  style={{ backgroundColor: label.color }}
                                />
                                <span>{label.name}</span>
                              </label>
                            </div>
                          ))
                        ) : (
                          <p className="text-sm text-muted-foreground">{t('kanban.noLabelsAvailable')}</p>
                        )}
                      </div>
                    </div>
                  </PopoverContent>
                </Popover>
              </div>

              {/* Priorities Filter */}
              <div className="flex items-center gap-2">
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="justify-start"
                      data-testid="button-filter-priorities"
                    >
                      <AlertTriangle className="w-4 h-4 mr-2" />
                      {t('kanban.priorities')}
                      {selectedPriorities.length > 0 && (
                        <Badge variant="secondary" className="ml-2 text-xs">
                          {selectedPriorities.length}
                        </Badge>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-48" align="start">
                    <div className="space-y-2">
                      <h4 className="text-sm font-medium">{t('kanban.filterByPriority')}</h4>
                      <Separator />
                      <div className="space-y-2">
                        {priorities.map((priority) => (
                          <div
                            key={priority}
                            className="flex items-center space-x-2"
                          >
                            <Checkbox
                              id={`priority-${priority}`}
                              checked={selectedPriorities.includes(priority)}
                              onCheckedChange={() => togglePriority(priority)}
                              data-testid={`checkbox-priority-${priority}`}
                            />
                            <label
                              htmlFor={`priority-${priority}`}
                              className="flex items-center space-x-2 text-sm cursor-pointer flex-1"
                            >
                              <Badge
                                variant="secondary"
                                className={`text-xs ${getPriorityColor(priority)}`}
                              >
                                {t(`priority.${priority}`)}
                              </Badge>
                            </label>
                          </div>
                        ))}
                      </div>
                    </div>
                  </PopoverContent>
                </Popover>
              </div>

              {/* Clear Filters */}
              {hasActiveFilters && (
                <>
                  <Separator orientation="vertical" className="h-6" />
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={clearAllFilters}
                    data-testid="button-clear-filters"
                    className="text-muted-foreground hover:text-foreground"
                  >
                    <X className="w-4 h-4 mr-2" />
                    {t('kanban.clearAll')}
                  </Button>
                </>
              )}
            </div>
          </div>

          {/* Active Filters Display */}
          {hasActiveFilters && (
            <div className="mt-3 pt-3 border-t">
              <div className="flex items-center gap-2 flex-wrap">
                <span className="text-xs text-muted-foreground">{t('kanban.activeFilters')}</span>
                {selectedLabels.map((labelId) => {
                  const label = labels.find(l => l.id === labelId);
                  return label ? (
                    <Badge
                      key={labelId}
                      variant="outline"
                      className="text-xs"
                      data-testid={`active-filter-label-${labelId}`}
                    >
                      <div
                        className="w-2 h-2 rounded-full mr-1"
                        style={{ backgroundColor: label.color }}
                      />
                      {label.name}
                      <X
                        className="w-3 h-3 ml-1 cursor-pointer"
                        onClick={() => toggleLabel(labelId)}
                      />
                    </Badge>
                  ) : null;
                })}
                {selectedPriorities.map((priority) => (
                  <Badge
                    key={priority}
                    variant="outline"
                    className={`text-xs ${getPriorityColor(priority)}`}
                    data-testid={`active-filter-priority-${priority}`}
                  >
                    {t(`priority.${priority}`)}
                    <X
                      className="w-3 h-3 ml-1 cursor-pointer"
                      onClick={() => togglePriority(priority)}
                    />
                  </Badge>
                ))}
              </div>
            </div>
          )}
        </Card>
      </div>

      {/* View Mode Tabs */}
      <Tabs value={viewMode} onValueChange={(value) => setViewMode(value as ViewMode)}>
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="traditional" data-testid="tab-traditional">
            <LayoutGrid className="w-4 h-4 mr-2" />
            {t('kanban.traditional')}
          </TabsTrigger>
          <TabsTrigger value="weekly" data-testid="tab-weekly">
            <CalendarIcon className="w-4 h-4 mr-2" />
            {t('kanban.weekly')}
          </TabsTrigger>
          <TabsTrigger value="monthly" data-testid="tab-monthly">
            <CalendarIcon className="w-4 h-4 mr-2" />
            {t('kanban.monthly')}
          </TabsTrigger>
        </TabsList>

        {/* All view modes use the same kanban layout, just with different filtering */}
        <TabsContent value="traditional" className="mt-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4">
            {columns.map((column) => {
              const columnTasks = getTasksForColumn(column.status);

              return (
                <Card
                  key={column.id}
                  className="p-3 sm:p-4 min-w-0 overflow-hidden"
                  onDragOver={handleDragOver}
                  onDrop={() => handleDrop(column.status)}
                  data-testid={`column-${column.id}`}
                >
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-sm" data-testid={`text-column-title-${column.id}`}>
                      {column.title}
                    </h3>
                    <Badge variant="secondary" className="text-xs">
                      {columnTasks.length}
                    </Badge>
                  </div>

                  <div className="space-y-2 sm:space-y-3 min-h-[150px] sm:min-h-[200px]">
                    {columnTasks.map((task) => (
                      <div
                        key={task.id}
                        draggable
                        onDragStart={() => handleDragStart(task.id)}
                        onDragEnd={handleDragEnd}
                        className={`cursor-move ${draggedTask === task.id ? 'opacity-50' : ''}`}
                      >
                        <TaskCard
                          task={task}
                          onStartTimer={() => onStartTimer?.(task.id)}
                          onStopTimer={() => onStopTimer?.(task.id)}
                          onEdit={() => {
                            onTaskClick?.(task);
                            console.log(`Task clicked from board: ${task.title}`);
                          }}
                          onDelete={() => {
                            onTaskDelete?.(task.id);
                            console.log(`Delete task from board: ${task.title}`);
                          }}
                          onStatusChange={(newStatus) => {
                            onTaskStatusChange?.(task.id, newStatus);
                            console.log(`Task ${task.title} status changed to ${newStatus}`);
                          }}
                          isDragging={draggedTask === task.id}
                        />
                      </div>
                    ))}

                    {columnTasks.length === 0 && (
                      <div className="text-center text-muted-foreground text-sm py-8">
                        {t('kanban.noTasksInColumn', { column: column.title.toLowerCase() })}
                      </div>
                    )}
                  </div>
                </Card>
              );
            })}
          </div>
        </TabsContent>

        <TabsContent value="weekly" className="mt-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4">
            {columns.map((column) => {
              const columnTasks = getTasksForColumn(column.status);

              return (
                <Card
                  key={column.id}
                  className="p-3 sm:p-4 min-w-0 overflow-hidden"
                  onDragOver={handleDragOver}
                  onDrop={() => handleDrop(column.status)}
                  data-testid={`column-${column.id}`}
                >
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-sm" data-testid={`text-column-title-${column.id}`}>
                      {column.title}
                    </h3>
                    <Badge variant="secondary" className="text-xs">
                      {columnTasks.length}
                    </Badge>
                  </div>

                  <div className="space-y-2 sm:space-y-3 min-h-[150px] sm:min-h-[200px]">
                    {columnTasks.map((task) => (
                      <div
                        key={task.id}
                        draggable
                        onDragStart={() => handleDragStart(task.id)}
                        onDragEnd={handleDragEnd}
                        className={`cursor-move ${draggedTask === task.id ? 'opacity-50' : ''}`}
                      >
                        <TaskCard
                          task={task}
                          onStartTimer={() => onStartTimer?.(task.id)}
                          onStopTimer={() => onStopTimer?.(task.id)}
                          onEdit={() => {
                            onTaskClick?.(task);
                            console.log(`Task clicked from board: ${task.title}`);
                          }}
                          onDelete={() => {
                            onTaskDelete?.(task.id);
                            console.log(`Delete task from board: ${task.title}`);
                          }}
                          onStatusChange={(newStatus) => {
                            onTaskStatusChange?.(task.id, newStatus);
                            console.log(`Task ${task.title} status changed to ${newStatus}`);
                          }}
                          isDragging={draggedTask === task.id}
                        />
                      </div>
                    ))}

                    {columnTasks.length === 0 && (
                      <div className="text-center text-muted-foreground text-sm py-8">
                        {t('kanban.noTasksInColumnForWeek', { column: column.title.toLowerCase() })}
                      </div>
                    )}
                  </div>
                </Card>
              );
            })}
          </div>
        </TabsContent>

        <TabsContent value="monthly" className="mt-4">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4">
            {columns.map((column) => {
              const columnTasks = getTasksForColumn(column.status);

              return (
                <Card
                  key={column.id}
                  className="p-3 sm:p-4 min-w-0 overflow-hidden"
                  onDragOver={handleDragOver}
                  onDrop={() => handleDrop(column.status)}
                  data-testid={`column-${column.id}`}
                >
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-sm" data-testid={`text-column-title-${column.id}`}>
                      {column.title}
                    </h3>
                    <Badge variant="secondary" className="text-xs">
                      {columnTasks.length}
                    </Badge>
                  </div>

                  <div className="space-y-2 sm:space-y-3 min-h-[150px] sm:min-h-[200px]">
                    {columnTasks.map((task) => (
                      <div
                        key={task.id}
                        draggable
                        onDragStart={() => handleDragStart(task.id)}
                        onDragEnd={handleDragEnd}
                        className={`cursor-move ${draggedTask === task.id ? 'opacity-50' : ''}`}
                      >
                        <TaskCard
                          task={task}
                          onStartTimer={() => onStartTimer?.(task.id)}
                          onStopTimer={() => onStopTimer?.(task.id)}
                          onEdit={() => {
                            onTaskClick?.(task);
                            console.log(`Task clicked from board: ${task.title}`);
                          }}
                          onDelete={() => {
                            onTaskDelete?.(task.id);
                            console.log(`Delete task from board: ${task.title}`);
                          }}
                          onStatusChange={(newStatus) => {
                            onTaskStatusChange?.(task.id, newStatus);
                            console.log(`Task ${task.title} status changed to ${newStatus}`);
                          }}
                          isDragging={draggedTask === task.id}
                        />
                      </div>
                    ))}

                    {columnTasks.length === 0 && (
                      <div className="text-center text-muted-foreground text-sm py-8">
                        {t('kanban.noTasksInColumnForMonth', { column: column.title.toLowerCase() })}
                      </div>
                    )}
                  </div>
                </Card>
              );
            })}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}