import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from '@tanstack/react-router';
import { MoreHorizontal, Pencil, Trash2, ChevronRight, Plus, X } from 'lucide-react';
import { Sheet, SheetContent, SheetClose } from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { PriorityBadge } from './PriorityBadge';
import { StatusBadge } from './StatusBadge';
import { type TaskItem } from './task-types';
import { useFormatPrefs, formatDueDate, formatRelative } from '@/lib/date';
import { parseAssignees } from './task-utils';
import { AssigneeStack } from './AssigneeStack';
import { TaskAttachmentChip } from './TaskAttachmentChip';
import { useTaskAttachments } from './useTaskAttachments';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { ChatInputBox } from '@/components/ai/ChatInputBox';

interface Props {
  task: TaskItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onEdit: (task: TaskItem) => void;
  onDelete: (id: string) => void;
}

export function TaskDetailSheet({ task, open, onOpenChange, onEdit, onDelete }: Props) {
  const { t } = useTranslation();
  const prefs = useFormatPrefs();
  const navigate = useNavigate();
  const attachments = useTaskAttachments(task?.id ?? null);
  const utils = trpc.useUtils();
  const { notifyError } = useNotify();
  const { data: comments } = trpc.taskComments.list.useQuery(
    { taskId: task?.id ?? '' },
    { enabled: !!task },
  );
  const { data: fresh } = trpc.tasks.byIds.useQuery(
    { ids: task ? [task.id] : [] },
    { enabled: !!task },
  );
  const addComment = trpc.taskComments.create.useMutation({
    onSuccess: () => {
      if (task) void utils.taskComments.list.invalidate({ taskId: task.id });
    },
    onError: (err) => notifyError('toast.comment.createError', err),
  });
  const deleteComment = trpc.taskComments.delete.useMutation({
    onSuccess: () => task && void utils.taskComments.list.invalidate({ taskId: task.id }),
  });
  const updateTask = trpc.tasks.update.useMutation({
    onSuccess: () => {
      void utils.tasks.list.invalidate();
      void utils.tasks.byIds.invalidate();
    },
    onError: (err) => notifyError('toast.task.updateError', err),
  });
  const [priorityOpen, setPriorityOpen] = useState(false);
  const [statusOpen, setStatusOpen] = useState(false);
  if (!task) return null;
  const liveTask = (fresh?.[0] as TaskItem | undefined) ?? task;
  return (
    <Sheet open={open} onOpenChange={onOpenChange}>
      <SheetContent
        side="right"
        showCloseButton={false}
        className="w-[480px] !max-w-[480px] flex flex-col p-0 gap-0 bg-card/85 backdrop-blur-xl border-border/50"
      >
        {/* Sticky header */}
        <div className="px-6 pt-6 pb-4 border-b border-border/40 shrink-0">
          <div className="flex items-center justify-between gap-2">
            <button
              type="button"
              onClick={() => {
                if (liveTask.projectId) {
                  onOpenChange(false);
                  navigate({ to: '/projects', search: { projectId: liveTask.projectId } });
                }
              }}
              disabled={!liveTask.projectId}
              className="text-xs text-muted-foreground flex items-center gap-1 min-w-0 hover:text-foreground transition-colors disabled:cursor-default disabled:hover:text-muted-foreground"
            >
              {liveTask.clientName && <span className="truncate">{liveTask.clientName}</span>}
              {liveTask.clientName && liveTask.projectName && <ChevronRight className="h-3 w-3 shrink-0" />}
              {liveTask.projectName && <span className="text-foreground font-medium truncate">{liveTask.projectName}</span>}
            </button>
            <div className="flex items-center gap-1 shrink-0">
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" className="h-7 w-7">
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem onSelect={() => onEdit(liveTask)}>
                    <Pencil className="h-4 w-4 mr-2" />
                    {t('common.edit')}
                  </DropdownMenuItem>
                  <DropdownMenuItem onSelect={() => onDelete(liveTask.id)} className="text-destructive focus:text-destructive">
                    <Trash2 className="h-4 w-4 mr-2" />
                    {t('common.delete')}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
              <SheetClose asChild>
                <Button variant="ghost" size="icon" className="h-7 w-7">
                  <X className="h-4 w-4" />
                </Button>
              </SheetClose>
            </div>
          </div>
          <div className="text-lg font-semibold leading-tight mt-1">{liveTask.title}</div>
          <div className="flex items-center gap-2 mt-2">
            <Popover open={priorityOpen} onOpenChange={setPriorityOpen}>
              <PopoverTrigger asChild>
                <button type="button" className="rounded hover:bg-accent/50 px-1 -mx-1">
                  <PriorityBadge priority={liveTask.priority} />
                </button>
              </PopoverTrigger>
              <PopoverContent className="w-40 p-1" align="start">
                {(['high', 'medium', 'low'] as const).map((p) => (
                  <button
                    key={p}
                    type="button"
                    onClick={() => {
                      updateTask.mutate({ id: liveTask.id, priority: p });
                      setPriorityOpen(false);
                    }}
                    className="w-full text-left px-2 py-1.5 text-sm rounded hover:bg-accent/50"
                  >
                    {t(`tasks.${p}`)}
                  </button>
                ))}
              </PopoverContent>
            </Popover>
            <Popover open={statusOpen} onOpenChange={setStatusOpen}>
              <PopoverTrigger asChild>
                <button type="button" className="rounded hover:bg-accent/50 px-1 -mx-1">
                  <StatusBadge status={liveTask.status} />
                </button>
              </PopoverTrigger>
              <PopoverContent className="w-40 p-1" align="start">
                {(['todo', 'in_progress', 'done'] as const).map((s) => (
                  <button
                    key={s}
                    type="button"
                    onClick={() => {
                      updateTask.mutate({ id: liveTask.id, status: s });
                      setStatusOpen(false);
                    }}
                    className="w-full text-left px-2 py-1.5 text-sm rounded hover:bg-accent/50"
                  >
                    {t(s === 'todo' ? 'tasks.toDo' : s === 'in_progress' ? 'tasks.inProgress' : 'tasks.done')}
                  </button>
                ))}
              </PopoverContent>
            </Popover>
          </div>
        </div>

        {/* Scrolling body */}
        <div className="flex-1 overflow-y-auto">
          <div className="mx-6 mt-4 rounded-lg border border-border/40 bg-background/40 p-4">
            <div className="grid grid-cols-2 gap-x-6 gap-y-4">
              <PropRow label={t('tasks.assignee')}>
                <AssigneeStack assignees={parseAssignees(liveTask.assignee)} />
              </PropRow>
              <PropRow label={t('tasks.colDue')}>
                {liveTask.dueDate ? formatDueDate(liveTask.dueDate, prefs) : <span className="text-muted-foreground">—</span>}
              </PropRow>
              <PropRow label={t('tasks.estimate')}>
                <span className="text-muted-foreground">—</span>
              </PropRow>
              <PropRow label={t('tasks.created')}>
                {liveTask.createdAt ? formatRelative(liveTask.createdAt) : <span className="text-muted-foreground">—</span>}
              </PropRow>
              <div className="col-span-2">
                <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-2">
                  {t('tasks.attachments')}
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  {(attachments.list.data ?? []).map((a) => (
                    <TaskAttachmentChip
                      key={a.id}
                      filename={a.filename}
                      sizeBytes={a.sizeBytes}
                      onOpen={() => attachments.open.mutate({ id: a.id })}
                      onDelete={() => attachments.remove.mutate({ id: a.id })}
                    />
                  ))}
                  <button
                    type="button"
                    onClick={() => attachments.addFiles()}
                    className="inline-flex items-center gap-1 rounded-full border border-dashed border-border px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground hover:border-foreground/50"
                  >
                    <Plus className="h-3 w-3" />
                    {t('tasks.addFile')}
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div className="px-6 py-4">
            <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-2">
              {t('tasks.description')}
            </div>
            {liveTask.description ? (
              <div className="text-sm whitespace-pre-wrap">{liveTask.description}</div>
            ) : (
              <div className="text-sm italic text-muted-foreground">{t('tasks.noDescription')}</div>
            )}
          </div>

          <div className="h-px bg-border/40 mx-6" />

          <div className="px-6 py-4">
            <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-2">
              {t('tasks.comments')} · {comments?.length ?? 0}
            </div>
            <div className="flex flex-col gap-3">
              {(comments ?? []).map((c) => (
                <div key={c.id} className="flex gap-3">
                  <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-medium">
                    {c.author.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? '').join('')}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs font-medium">{c.author}</span>
                      <span className="text-[10px] text-muted-foreground">{formatRelative(c.createdAt)}</span>
                    </div>
                    <div className="rounded-md bg-background/60 px-3 py-2 text-sm">{c.content}</div>
                    <button
                      type="button"
                      onClick={() => deleteComment.mutate({ id: c.id })}
                      className="mt-1 text-[10px] text-muted-foreground hover:text-destructive"
                    >
                      {t('common.delete')}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Sticky composer */}
        <div className="px-6 py-3 border-t border-border/40 shrink-0">
          <div className="rounded-2xl bg-background/70 backdrop-blur-xl border border-border/50 shadow-lg ring-1 ring-border/20 transition-shadow focus-within:shadow-xl focus-within:border-ring/50">
            <ChatInputBox
              cacheKey={`task-comment-${liveTask.id}`}
              isStreaming={false}
              variant="comment"
              placeholder={t('tasks.writeComment')}
              onSend={(text) => addComment.mutate({ taskId: liveTask.id, author: 'Me', content: text })}
            />
          </div>
        </div>
      </SheetContent>
    </Sheet>
  );
}

function PropRow({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <div className="text-[10px] uppercase tracking-wider text-muted-foreground mb-1">{label}</div>
      <div className="text-sm">{children}</div>
    </div>
  );
}
