import { cn } from "@xtablo/shared";
import type { KanbanTask } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import {
  FileIcon,
  GripVerticalIcon,
  LayoutPanelTopIcon,
  ListChecksIcon,
  RotateCcwIcon,
} from "lucide-react";
import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout";

interface DraggedBlock {
  zone: "left" | "right";
  index: number;
}

interface SingleTabloOverviewProps {
  roleLabel?: string;
  statusLabel?: string;
  statusBadgeClass?: string;
  description: string;
  tasks: KanbanTask[];
  projectTaskCount: number;
  personalTaskCount: number;
  fileNames: string[];
  showFileMenu?: boolean;
  onOpenTasks: () => void;
  onOpenFiles: () => void;
  onCreateTask: () => void;
  onToggleTaskDone: (taskId: string) => void;
  showAllTasks: boolean;
  onToggleShowAllTasks: () => void;
  layout: OverviewLayoutV1;
  canEditLayout: boolean;
  isLayoutEditMode: boolean;
  draggedBlock: DraggedBlock | null;
  onToggleLayoutEditMode: () => void;
  onResetLayout: () => void;
  onBlockDragStart: (
    event: React.DragEvent<HTMLDivElement>,
    zone: "left" | "right",
    index: number
  ) => void;
  onBlockDragOver: (event: React.DragEvent<HTMLDivElement>) => void;
  onBlockDrop: (zone: "left" | "right", index: number) => void;
  onBlockDragEnd: () => void;
}

function OverviewCard({
  title,
  actions,
  children,
  draggable = false,
  onDragStart,
  onDragOver,
  onDrop,
  onDragEnd,
  isDragged = false,
}: {
  title: string;
  actions?: React.ReactNode;
  children: React.ReactNode;
  draggable?: boolean;
  onDragStart?: (event: React.DragEvent<HTMLDivElement>) => void;
  onDragOver?: (event: React.DragEvent<HTMLDivElement>) => void;
  onDrop?: (event: React.DragEvent<HTMLDivElement>) => void;
  onDragEnd?: () => void;
  isDragged?: boolean;
}) {
  return (
    <div
      draggable={draggable}
      onDragStart={onDragStart}
      onDragOver={onDragOver}
      onDrop={onDrop}
      onDragEnd={onDragEnd}
      className={cn(
        "bg-white dark:bg-card rounded-xl border border-border p-6 shadow-sm",
        draggable && "cursor-grab active:cursor-grabbing",
        isDragged && "opacity-60"
      )}
    >
      <div className="mb-4 flex items-start justify-between gap-3">
        <div className="flex items-center gap-2">
          {draggable && <GripVerticalIcon className="h-4 w-4 text-muted-foreground" />}
          <h2 className="text-xl sm:text-2xl font-bold text-foreground">{title}</h2>
        </div>
        {actions}
      </div>
      {children}
    </div>
  );
}

export function SingleTabloOverview({
  description,
  tasks,
  projectTaskCount,
  personalTaskCount,
  fileNames,
  onOpenTasks,
  onOpenFiles,
  onCreateTask,
  onToggleTaskDone,
  showAllTasks,
  onToggleShowAllTasks,
  layout,
  canEditLayout,
  isLayoutEditMode,
  draggedBlock,
  onToggleLayoutEditMode,
  onResetLayout,
  onBlockDragStart,
  onBlockDragOver,
  onBlockDrop,
  onBlockDragEnd,
}: SingleTabloOverviewProps) {
  const renderBlockContent = (blockId: OverviewBlockId) => {
    switch (blockId) {
      case "description":
        return {
          title: "Description du projet",
          children: (
            <p className="text-muted-foreground leading-relaxed text-sm sm:text-base">
              {description}
            </p>
          ),
        };
      case "myTasks":
        return {
          title: "Mes tâches",
          actions: (
            <div className="flex items-center gap-2">
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="text-[#804EEC] hover:bg-[#804EEC]/10 hover:text-[#804EEC]"
                onClick={onOpenTasks}
              >
                Voir tout
              </Button>
              <Button
                type="button"
                size="sm"
                className="bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
                onClick={onCreateTask}
              >
                Ajouter
              </Button>
            </div>
          ),
          children: (
            <div className="space-y-3">
              {tasks.length === 0 ? (
                <p className="text-sm text-muted-foreground">Aucune tâche.</p>
              ) : (
                tasks.map((task) => (
                  <button
                    key={task.id}
                    type="button"
                    onClick={() => onToggleTaskDone(task.id)}
                    className="flex w-full items-center gap-3 rounded-lg border border-border px-3 py-2 text-left"
                  >
                    <span
                      className={cn(
                        "h-4 w-4 rounded-full border border-border",
                        task.status === "done" && "bg-green-500 border-green-500"
                      )}
                    />
                    <span className="truncate text-sm font-medium text-foreground">
                      {task.title}
                    </span>
                  </button>
                ))
              )}
              {personalTaskCount > 5 && (
                <Button
                  type="button"
                  variant="link"
                  className="px-0"
                  onClick={onToggleShowAllTasks}
                >
                  {showAllTasks ? "Afficher moins" : "Afficher plus"}
                </Button>
              )}
            </div>
          ),
        };
      case "files":
        return {
          title: "Fichiers",
          actions: (
            <Button
              type="button"
              variant="ghost"
              size="sm"
              className="text-[#804EEC] hover:bg-[#804EEC]/10 hover:text-[#804EEC]"
              onClick={onOpenFiles}
            >
              Ouvrir
            </Button>
          ),
          children: (
            <div className="space-y-3">
              {fileNames.length === 0 ? (
                <p className="text-sm text-muted-foreground">Aucun fichier.</p>
              ) : (
                fileNames.slice(0, 5).map((fileName) => (
                  <div key={fileName} className="flex items-center gap-2 text-sm text-foreground">
                    <FileIcon className="h-4 w-4 text-muted-foreground" />
                    <span className="truncate">{fileName}</span>
                  </div>
                ))
              )}
            </div>
          ),
        };
      case "info":
        return {
          title: "Informations",
          children: (
            <div className="space-y-3 text-sm text-muted-foreground">
              <div className="flex items-center gap-2">
                <ListChecksIcon className="h-4 w-4" />
                <span>{projectTaskCount} tâches sur le projet</span>
              </div>
              <div className="flex items-center gap-2">
                <LayoutPanelTopIcon className="h-4 w-4" />
                <span>{personalTaskCount} tâches pour vous</span>
              </div>
            </div>
          ),
        };
    }
  };

  const renderZone = (zone: "left" | "right", blocks: OverviewBlockId[]) => (
    <div className="space-y-6">
      {blocks.map((blockId, index) => {
        const block = renderBlockContent(blockId);

        return (
          <div key={blockId} onDragOver={onBlockDragOver} onDrop={() => onBlockDrop(zone, index)}>
            <OverviewCard
              title={block.title}
              actions={block.actions}
              draggable={isLayoutEditMode}
              onDragStart={(event) => onBlockDragStart(event, zone, index)}
              onDragOver={onBlockDragOver}
              onDrop={() => onBlockDrop(zone, index)}
              onDragEnd={onBlockDragEnd}
              isDragged={draggedBlock?.zone === zone && draggedBlock.index === index}
            >
              {block.children}
            </OverviewCard>
          </div>
        );
      })}
    </div>
  );

  return (
    <div className="space-y-6">
      {canEditLayout && (
        <div className="flex flex-wrap items-center gap-2">
          <Button
            type="button"
            variant="outline"
            className="border border-[#804EEC] text-[#804EEC] hover:bg-[#804EEC]/10"
            onClick={onToggleLayoutEditMode}
          >
            Modifier la mise en page
          </Button>
          {isLayoutEditMode && (
            <Button type="button" variant="outline" onClick={onResetLayout}>
              <RotateCcwIcon className="h-4 w-4" />
              Réinitialiser
            </Button>
          )}
        </div>
      )}

      <div
        data-testid="single-tablo-overview-grid"
        className="grid w-full grid-cols-1 gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]"
      >
        <div>{renderZone("left", layout.leftZone)}</div>
        <div>{renderZone("right", layout.rightZone)}</div>
      </div>
    </div>
  );
}
