import { Fragment } from 'react';
import { useTranslation } from 'react-i18next';
import { motion } from 'framer-motion';
import { Calendar, User, Pencil, Trash2, Sparkles, RefreshCw, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
  Breadcrumb,
  BreadcrumbList,
  BreadcrumbItem,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
  ContextMenuSub,
  ContextMenuSubTrigger,
  ContextMenuSubContent,
} from '@/components/ui/context-menu';
import { PriorityBadge } from './PriorityBadge';
import { StatusBadge } from './StatusBadge';
import { type TaskItem } from './task-types';
import { useFormatPrefs, formatDueDate } from '@/lib/date';
import { parseAssignees } from './task-utils';

const STATUSES = ['todo', 'in_progress', 'done'] as const;

export function TaskCard({
  task,
  onStatusChange,
  onEdit,
  onDelete,
  onClick,
  hideBreadcrumb,
  layoutId,
}: {
  task: TaskItem;
  onStatusChange: (id: string, status: string) => void;
  onEdit?: (task: TaskItem) => void;
  onDelete?: (id: string) => void;
  onClick?: (task: TaskItem) => void;
  hideBreadcrumb?: boolean;
  layoutId?: string;
}) {
  const { t } = useTranslation();
  const prefs = useFormatPrefs();
  const isDone = task.status === 'done';

  const breadcrumb: string[] = [];
  if (!hideBreadcrumb) {
    if (task.clientName) breadcrumb.push(task.clientName);
    if (task.subClientName) breadcrumb.push(task.subClientName);
    if (task.projectName) breadcrumb.push(task.projectName);
  }

  const hasMeta =
    task.priority || task.dueDate || breadcrumb.length > 0 || task.assignee;

  const Wrapper = layoutId ? motion.div : 'div';
  const wrapperProps = layoutId ? { layoutId, layout: true as const } : {};

  return (
    <ContextMenu>
      <ContextMenuTrigger asChild>
        <Wrapper
          {...wrapperProps}
          className={cn(
            'flex flex-col gap-3 p-4 rounded-md border select-none transition-colors',
            isDone
              ? 'bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-900'
              : 'bg-card border-border',
            onClick ? 'cursor-pointer hover:bg-accent/50' : 'cursor-default',
          )}
          onClick={() => onClick?.(task)}
        >
          {/* Header: title (no checkbox) */}
          <div className="flex items-start gap-2">
            <div className="flex-1 min-w-0">
              <div className={cn('flex items-center gap-1.5 text-sm font-medium min-w-0', isDone && 'line-through text-muted-foreground')}>
                {task.isAiSuggested ? <Sparkles className="h-3 w-3 shrink-0 text-amber-500" /> : null}
                <span className="truncate">{task.title}</span>
              </div>
              {task.description && (
                <div className="text-sm text-muted-foreground line-clamp-2 mt-0.5">
                  {task.description}
                </div>
              )}
            </div>
          </div>

          {/* Metadata chips */}
          {hasMeta && (
            <div className="flex flex-wrap items-center gap-2">
              {task.dueDate && (
                <Badge variant="outline" className="text-xs gap-1 shrink-0">
                  <Calendar className="h-3 w-3" />
                  {formatDueDate(task.dueDate, prefs)}
                </Badge>
              )}

              {breadcrumb.length > 0 && (
                <Breadcrumb className="shrink-0">
                  <BreadcrumbList>
                    {breadcrumb.map((part, i) => (
                      <Fragment key={i}>
                        {i > 0 && <BreadcrumbSeparator />}
                        <BreadcrumbItem>
                          <span className="text-xs">{part}</span>
                        </BreadcrumbItem>
                      </Fragment>
                    ))}
                  </BreadcrumbList>
                </Breadcrumb>
              )}

              {task.assignee && (
                <div className="flex items-center gap-1 text-xs text-muted-foreground shrink-0">
                  <User className="h-3 w-3" />
                  {parseAssignees(task.assignee).join(', ')}
                </div>
              )}
            </div>
          )}

          {/* Footer: status + priority */}
          <div className="flex flex-col gap-2 mt-auto">
            <Separator />
            <div className="flex items-center gap-2">
              <StatusBadge status={task.status} />
              <PriorityBadge priority={task.priority} />
            </div>
          </div>
        </Wrapper>
      </ContextMenuTrigger>

      <ContextMenuContent>
        <ContextMenuItem onSelect={() => onEdit?.(task)}>
          <Pencil className="h-4 w-4 mr-2" />
          {t('common.edit')}
        </ContextMenuItem>
        <ContextMenuSub>
          <ContextMenuSubTrigger>
            <RefreshCw className="h-4 w-4 mr-2" />
            {t('tasks.changeStatus')}
          </ContextMenuSubTrigger>
          <ContextMenuSubContent>
            {STATUSES.map((s) => (
              <ContextMenuItem key={s} onSelect={() => onStatusChange(task.id, s)}>
                {task.status === s ? <Check className="h-3 w-3 mr-2" /> : <span className="w-5" />}
                {t(s === 'todo' ? 'tasks.toDo' : s === 'in_progress' ? 'tasks.inProgress' : 'tasks.done')}
              </ContextMenuItem>
            ))}
          </ContextMenuSubContent>
        </ContextMenuSub>
        <ContextMenuItem
          onSelect={() => onDelete?.(task.id)}
          className="text-destructive focus:text-destructive"
        >
          <Trash2 className="h-4 w-4 mr-2" />
          {t('common.delete')}
        </ContextMenuItem>
      </ContextMenuContent>
    </ContextMenu>
  );
}
