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

export function TaskRow({
  task,
  onToggle,
  onEdit,
  onDelete,
  onClick,
  hideBreadcrumb,
  layoutId,
}: {
  task: TaskItem;
  onToggle: (id: string, status: string | null) => 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 checkboxState: boolean | 'indeterminate' =
    task.status === 'done' ? true :
    task.status === 'in_progress' ? 'indeterminate' : false;

  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 hasMetadata =
    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-1.5 px-4 py-3 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)}
        >
          {/* Row 1: checkbox + title + description */}
          <div className="flex items-start gap-3">
            <Checkbox
              checked={checkboxState}
              onCheckedChange={() => onToggle(task.id, task.status)}
              onClick={(e) => e.stopPropagation()}
              className="mt-0.5 shrink-0"
            />
            <div className="flex-1 min-w-0">
              <div className={cn('flex items-center gap-1 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 truncate">
                  {task.description}
                </div>
              )}
            </div>
          </div>

          {/* Row 2: metadata, indented to align with title text */}
          {hasMetadata && (
            <div className="flex flex-wrap items-center gap-2 pl-7">
              <PriorityBadge priority={task.priority} />

              {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>
          )}
        </Wrapper>
      </ContextMenuTrigger>

      <ContextMenuContent>
        <ContextMenuItem onSelect={() => onEdit?.(task)}>
          <Pencil className="h-4 w-4 mr-2" />
          {t('common.edit')}
        </ContextMenuItem>
        <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>
  );
}
