'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { format, isPast, isToday } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import {
  CheckCircle2,
  Circle,
  Clock,
  AlertCircle,
  User,
  Calendar,
  Pencil,
  Trash2,
  X,
  Check,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { getInitials } from '@tos/shared';
import { cn } from '@/lib/utils';
import type {
  MorningMeetingAction,
  ActionStatus,
  Priority,
  UpdateActionDto,
} from '@/types/lean';
import { PRIORITY_COLORS, ACTION_STATUS_COLORS } from '@/types/lean';

interface ActionItemProps {
  /** The action item data */
  action: MorningMeetingAction;
  /** Whether editing is allowed */
  editable?: boolean;
  /** Callback when action is updated */
  onUpdate?: (id: string, dto: UpdateActionDto) => void;
  /** Callback when action is completed */
  onComplete?: (id: string) => void;
  /** Callback when action is deleted */
  onDelete?: (id: string) => void;
  /** Loading state */
  isLoading?: boolean;
  /** Locale for date formatting */
  locale?: string;
}

/**
 * Status icon component
 */
function StatusIcon({ status }: { status: ActionStatus }) {
  switch (status) {
    case 'COMPLETED':
      return <CheckCircle2 className="h-4 w-4 text-green-600" />;
    case 'IN_PROGRESS':
      return <Clock className="h-4 w-4 text-blue-600" />;
    case 'CANCELLED':
      return <X className="h-4 w-4 text-red-600" />;
    case 'OPEN':
    default:
      return <Circle className="h-4 w-4 text-gray-400" />;
  }
}

/**
 * Action Item component for displaying a single action with status and assignee
 */
export function ActionItem({
  action,
  editable = false,
  onUpdate,
  onComplete,
  onDelete,
  isLoading = false,
  locale = 'de',
}: ActionItemProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editedTitle, setEditedTitle] = useState(action.title);
  const [editedStatus, setEditedStatus] = useState<ActionStatus>(action.status);
  const [editedPriority, setEditedPriority] = useState<Priority>(action.priority);

  const t = useTranslations('lean.morningMeeting.actions');
  const dateLocale = locale === 'de' ? de : enUS;
  const isOverdue =
    action.dueDate &&
    isPast(new Date(action.dueDate)) &&
    !isToday(new Date(action.dueDate)) &&
    action.status !== 'COMPLETED' &&
    action.status !== 'CANCELLED';

  const handleSave = () => {
    if (onUpdate) {
      onUpdate(action.id, {
        title: editedTitle,
        status: editedStatus,
        priority: editedPriority,
      });
    }
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditedTitle(action.title);
    setEditedStatus(action.status);
    setEditedPriority(action.priority);
    setIsEditing(false);
  };

  const handleToggleComplete = () => {
    if (action.status === 'COMPLETED') {
      onUpdate?.(action.id, { status: 'OPEN' });
    } else {
      onComplete?.(action.id);
    }
  };

  const statusColors = ACTION_STATUS_COLORS[action.status];
  const priorityColors = PRIORITY_COLORS[action.priority];

  if (isEditing && editable) {
    return (
      <div className="p-3 border rounded-lg bg-muted/50 space-y-2">
        <div className="flex items-center justify-between">
          <Input
            value={editedTitle}
            onChange={(e) => setEditedTitle(e.target.value)}
            className="flex-1 h-8"
            placeholder="Titel"
          />
          <div className="flex gap-1 ml-2">
            <Button
              size="icon"
              variant="ghost"
              className="h-7 w-7"
              onClick={handleSave}
              disabled={isLoading}
            >
              <Check className="h-3 w-3" />
            </Button>
            <Button
              size="icon"
              variant="ghost"
              className="h-7 w-7"
              onClick={handleCancel}
              disabled={isLoading}
            >
              <X className="h-3 w-3" />
            </Button>
          </div>
        </div>

        <div className="flex gap-2">
          <Select
            value={editedStatus}
            onValueChange={(v) => setEditedStatus(v as ActionStatus)}
          >
            <SelectTrigger className="h-8 text-xs flex-1">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="OPEN">{t('status.open')}</SelectItem>
              <SelectItem value="IN_PROGRESS">{t('status.inProgress')}</SelectItem>
              <SelectItem value="COMPLETED">{t('status.completed')}</SelectItem>
              <SelectItem value="CANCELLED">{t('status.cancelled')}</SelectItem>
            </SelectContent>
          </Select>

          <Select
            value={editedPriority}
            onValueChange={(v) => setEditedPriority(v as Priority)}
          >
            <SelectTrigger className="h-8 text-xs flex-1">
              <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>
    );
  }

  return (
    <div
      className={cn(
        'group p-3 border rounded-lg transition-colors hover:bg-muted/50',
        action.status === 'COMPLETED' && 'opacity-60',
        isOverdue && 'border-red-300 bg-red-50/50'
      )}
    >
      <div className="flex items-start gap-3">
        {/* Status toggle */}
        <button
          onClick={handleToggleComplete}
          disabled={isLoading || !editable}
          className={cn(
            'mt-0.5 transition-colors',
            editable && 'hover:opacity-70 cursor-pointer'
          )}
        >
          <StatusIcon status={action.status} />
        </button>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <span
              className={cn(
                'text-sm font-medium',
                action.status === 'COMPLETED' && 'line-through text-muted-foreground'
              )}
            >
              {action.title}
            </span>

            {/* Actions */}
            {editable && (
              <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <Button
                  size="icon"
                  variant="ghost"
                  className="h-6 w-6"
                  onClick={() => setIsEditing(true)}
                  disabled={isLoading}
                >
                  <Pencil className="h-3 w-3" />
                </Button>
                {onDelete && (
                  <Button
                    size="icon"
                    variant="ghost"
                    className="h-6 w-6 text-destructive hover:text-destructive"
                    onClick={() => onDelete(action.id)}
                    disabled={isLoading}
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                )}
              </div>
            )}
          </div>

          {action.description && (
            <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
              {action.description}
            </p>
          )}

          {/* Meta row */}
          <div className="flex items-center gap-3 mt-2 flex-wrap">
            {/* Priority badge */}
            <Badge
              variant="outline"
              className={cn('text-xs', priorityColors.bg, priorityColors.text)}
            >
              {action.priority === 'LOW' && t('priority.low')}
              {action.priority === 'MEDIUM' && t('priority.medium')}
              {action.priority === 'HIGH' && t('priority.high')}
              {action.priority === 'CRITICAL' && t('priority.critical')}
            </Badge>

            {/* Status badge */}
            <Badge
              variant="outline"
              className={cn('text-xs', statusColors.bg, statusColors.text)}
            >
              {action.status === 'OPEN' && t('status.open')}
              {action.status === 'IN_PROGRESS' && t('status.inProgress')}
              {action.status === 'COMPLETED' && t('status.completed')}
              {action.status === 'CANCELLED' && t('status.cancelled')}
            </Badge>

            {/* Due date */}
            {action.dueDate && (
              <div
                className={cn(
                  'flex items-center gap-1 text-xs',
                  isOverdue ? 'text-red-600' : 'text-muted-foreground'
                )}
              >
                {isOverdue ? (
                  <AlertCircle className="h-3 w-3" />
                ) : (
                  <Calendar className="h-3 w-3" />
                )}
                <span>
                  {format(new Date(action.dueDate), 'dd.MM.yyyy', {
                    locale: dateLocale,
                  })}
                </span>
              </div>
            )}

            {/* Assignee */}
            {action.assignee && (
              <div className="flex items-center gap-1">
                <Avatar className="h-5 w-5">
                  <AvatarImage src={action.assignee.avatar || undefined} />
                  <AvatarFallback className="text-[10px]">
                    {getInitials(
                      action.assignee.firstName,
                      action.assignee.lastName
                    )}
                  </AvatarFallback>
                </Avatar>
                <span className="text-xs text-muted-foreground">
                  {action.assignee.firstName} {action.assignee.lastName}
                </span>
              </div>
            )}

            {!action.assignee && (
              <div className="flex items-center gap-1 text-xs text-muted-foreground">
                <User className="h-3 w-3" />
                <span>{t('notAssigned')}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
