'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Plus, ListTodo, Filter, ChevronDown } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
  DropdownMenuCheckboxItem,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  DialogFooter,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { ActionItem } from './action-item';
import type {
  MorningMeetingAction,
  ActionStatus,
  Priority,
  CreateActionDto,
  UpdateActionDto,
} from '@/types/lean';

interface ActionListProps {
  /** List of actions */
  actions: MorningMeetingAction[];
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback when action is added */
  onAddAction?: (dto: CreateActionDto) => void;
  /** Callback when action is updated */
  onUpdateAction?: (id: string, dto: UpdateActionDto) => void;
  /** Callback when action is completed */
  onCompleteAction?: (id: string) => void;
  /** Callback when action is deleted */
  onDeleteAction?: (id: string) => void;
  /** Loading state */
  isLoading?: boolean;
  /** Locale for translations */
  locale?: string;
  /** Maximum height for the list */
  maxHeight?: string;
}

type StatusFilter = ActionStatus | 'ALL';

/**
 * Action List component for displaying and managing meeting action items
 */
export function ActionList({
  actions,
  editable = false,
  onAddAction,
  onUpdateAction,
  onCompleteAction,
  onDeleteAction,
  isLoading = false,
  locale = 'de',
  maxHeight = '400px',
}: ActionListProps) {
  const [statusFilter, setStatusFilter] = useState<StatusFilter>('ALL');
  const [showCompleted, setShowCompleted] = useState(true);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const t = useTranslations('lean.morningMeeting.actions');
  const tCommon = useTranslations('common');
  const [newAction, setNewAction] = useState<CreateActionDto>({
    title: '',
    priority: 'MEDIUM',
  });

  // Filter actions
  const filteredActions = actions.filter((action) => {
    if (statusFilter !== 'ALL' && action.status !== statusFilter) return false;
    if (!showCompleted && action.status === 'COMPLETED') return false;
    return true;
  });

  // Sort: CRITICAL first, then by status (OPEN > IN_PROGRESS > rest), then by due date
  const sortedActions = [...filteredActions].sort((a, b) => {
    // Priority order: CRITICAL > HIGH > MEDIUM > LOW
    const priorityOrder = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3 };
    const statusOrder = { OPEN: 0, IN_PROGRESS: 1, COMPLETED: 2, CANCELLED: 3 };

    const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
    if (priorityDiff !== 0) return priorityDiff;

    const statusDiff = statusOrder[a.status] - statusOrder[b.status];
    if (statusDiff !== 0) return statusDiff;

    // Sort by due date (earliest first, null last)
    if (a.dueDate && b.dueDate) {
      return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
    }
    if (a.dueDate) return -1;
    if (b.dueDate) return 1;

    return 0;
  });

  const handleAddAction = () => {
    if (newAction.title.trim() && onAddAction) {
      onAddAction(newAction);
      setNewAction({ title: '', priority: 'MEDIUM' });
      setIsAddDialogOpen(false);
    }
  };

  // Stats
  const openCount = actions.filter((a) => a.status === 'OPEN').length;
  const inProgressCount = actions.filter((a) => a.status === 'IN_PROGRESS').length;
  const completedCount = actions.filter((a) => a.status === 'COMPLETED').length;

  if (isLoading) {
    return (
      <Card>
        <CardHeader className="pb-3">
          <Skeleton className="h-6 w-32" />
        </CardHeader>
        <CardContent className="space-y-3">
          {[1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-20 w-full" />
          ))}
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="flex flex-col h-full">
      <CardHeader className="pb-3 flex-shrink-0">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <ListTodo className="h-5 w-5 text-muted-foreground" />
            <CardTitle className="text-base">{t('title')}</CardTitle>
          </div>
          <div className="flex items-center gap-2">
            {/* Filter dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm" className="h-8">
                  <Filter className="h-3 w-3 mr-1" />
                  {tCommon('filter')}
                  <ChevronDown className="h-3 w-3 ml-1" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => setStatusFilter('ALL')}>
                  {t('filterAll')} ({actions.length})
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setStatusFilter('OPEN')}>
                  {t('status.open')} ({openCount})
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setStatusFilter('IN_PROGRESS')}>
                  {t('status.inProgress')} ({inProgressCount})
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setStatusFilter('COMPLETED')}>
                  {t('status.completed')} ({completedCount})
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuCheckboxItem
                  checked={showCompleted}
                  onCheckedChange={setShowCompleted}
                >
                  {t('showCompleted')}
                </DropdownMenuCheckboxItem>
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Add action button */}
            {editable && onAddAction && (
              <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                <DialogTrigger asChild>
                  <Button size="sm" className="h-8">
                    <Plus className="h-3 w-3 mr-1" />
                    {t('new')}
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>{t('new')}</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4 py-4">
                    <div className="space-y-2">
                      <Label htmlFor="title">Titel</Label>
                      <Input
                        id="title"
                        value={newAction.title}
                        onChange={(e) =>
                          setNewAction({ ...newAction, title: e.target.value })
                        }
                        placeholder="Massnahme beschreiben..."
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="description">Beschreibung (optional)</Label>
                      <Input
                        id="description"
                        value={newAction.description || ''}
                        onChange={(e) =>
                          setNewAction({
                            ...newAction,
                            description: e.target.value || undefined,
                          })
                        }
                        placeholder="Weitere Details..."
                      />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="priority">Prioritaet</Label>
                        <Select
                          value={newAction.priority}
                          onValueChange={(v) =>
                            setNewAction({ ...newAction, priority: v as Priority })
                          }
                        >
                          <SelectTrigger id="priority">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="LOW">{t('priority.low')}</SelectItem>
                            <SelectItem value="MEDIUM">{t('priority.medium')}</SelectItem>
                            <SelectItem value="HIGH">{t('priority.high')}</SelectItem>
                            <SelectItem value="CRITICAL">{t('priority.critical')}</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label htmlFor="dueDate">Faellig am</Label>
                        <Input
                          id="dueDate"
                          type="date"
                          value={newAction.dueDate || ''}
                          onChange={(e) =>
                            setNewAction({
                              ...newAction,
                              dueDate: e.target.value || undefined,
                            })
                          }
                        />
                      </div>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button
                      variant="outline"
                      onClick={() => setIsAddDialogOpen(false)}
                    >
                      {tCommon('cancel')}
                    </Button>
                    <Button
                      onClick={handleAddAction}
                      disabled={!newAction.title.trim()}
                    >
                      {t('add')}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            )}
          </div>
        </div>

        {/* Stats row */}
        <div className="flex gap-4 text-xs text-muted-foreground mt-2">
          <span>{openCount} {t('open')}</span>
          <span>{inProgressCount} {t('inProgress')}</span>
          <span>{completedCount} {t('completed')}</span>
        </div>
      </CardHeader>

      <CardContent className="flex-1 pt-0 overflow-hidden">
        <ScrollArea className="h-full" style={{ maxHeight }}>
          {sortedActions.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
              <ListTodo className="h-8 w-8 mb-2 opacity-50" />
              <p className="text-sm">
                {statusFilter !== 'ALL'
                  ? t('noActionsFiltered')
                  : t('noActions')}
              </p>
            </div>
          ) : (
            <div className="space-y-2 pr-4">
              {sortedActions.map((action) => (
                <ActionItem
                  key={action.id}
                  action={action}
                  editable={editable}
                  onUpdate={onUpdateAction}
                  onComplete={onCompleteAction}
                  onDelete={onDeleteAction}
                  isLoading={isLoading}
                  locale={locale}
                />
              ))}
            </div>
          )}
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
