import { cn } from "@xtablo/shared";
import type { Etape, KanbanTask, TaskStatus } from "@xtablo/shared-types";
import { Button } from "@xtablo/ui/components/button";
import { Input } from "@xtablo/ui/components/input";
import {
  CalendarIcon,
  CheckIcon,
  ChevronDownIcon,
  ChevronRightIcon,
  CircleCheckIcon,
  ListChecksIcon,
  PencilIcon,
  PlusIcon,
  Trash2Icon,
  XIcon,
} from "lucide-react";
import { useState } from "react";

interface EtapesSectionProps {
  etapes: Etape[];
  tabloTasks: KanbanTask[];
  tabloId: string;
  isAdmin: boolean;
  onCreateTask: (task: {
    tablo_id: string;
    title: string;
    status: string;
    parent_task_id: string;
    is_parent: boolean;
    position: number;
  }) => void;
  onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise<void>;
  onTaskStatusChange?: (taskId: string, status: TaskStatus) => void;
  onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise<void>;
  onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise<void>;
  isCreatingEtape?: boolean;
  isUpdatingEtape?: boolean;
  isDeletingEtape?: boolean;
}

export function EtapesSection({
  etapes,
  tabloTasks,
  tabloId,
  isAdmin,
  onCreateTask,
  onCreateEtape,
  onTaskStatusChange,
  onUpdateEtape,
  onDeleteEtape,
  isCreatingEtape = false,
  isUpdatingEtape = false,
  isDeletingEtape = false,
}: EtapesSectionProps) {
  const [expandedEtapes, setExpandedEtapes] = useState<Set<string>>(
    new Set(etapes.map((e) => e.id))
  );
  const [addingTaskToEtape, setAddingTaskToEtape] = useState<string | null>(null);
  const [newEtapeTitle, setNewEtapeTitle] = useState("");
  const [newTaskTitle, setNewTaskTitle] = useState("");
  const [editingEtapeId, setEditingEtapeId] = useState<string | null>(null);
  const [editingEtapeTitle, setEditingEtapeTitle] = useState("");

  const toggleEtape = (id: string) => {
    setExpandedEtapes((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const handleAddTask = (etapeId: string) => {
    const title = newTaskTitle.trim();
    if (!title || !tabloId) return;
    onCreateTask({
      tablo_id: tabloId,
      title,
      status: "todo",
      parent_task_id: etapeId,
      is_parent: false,
      position: tabloTasks.filter((t) => t.parent_task_id === etapeId).length,
    });
    setNewTaskTitle("");
    setAddingTaskToEtape(null);
  };

  const handleAddEtape = async () => {
    const title = newEtapeTitle.trim();
    if (!title || !tabloId) {
      return;
    }

    const nextPosition = etapes.reduce((max, etape) => Math.max(max, etape.position), -1) + 1;

    await onCreateEtape({
      tabloId,
      title,
      position: nextPosition,
    });

    setNewEtapeTitle("");
  };

  const startEditingEtape = (etapeId: string, title: string) => {
    setEditingEtapeId(etapeId);
    setEditingEtapeTitle(title);
  };

  const cancelEditingEtape = () => {
    setEditingEtapeId(null);
    setEditingEtapeTitle("");
  };

  const handleUpdateEtape = async (etapeId: string) => {
    const title = editingEtapeTitle.trim();
    if (!title || !tabloId) {
      return;
    }

    await onUpdateEtape?.({
      id: etapeId,
      tabloId,
      title,
    });

    cancelEditingEtape();
  };

  const handleDeleteEtape = async (etapeId: string, title: string) => {
    if (!tabloId) {
      return;
    }

    if (!window.confirm(`Supprimer l'étape "${title}" ?`)) {
      return;
    }

    await onDeleteEtape?.({
      id: etapeId,
      tabloId,
    });
  };

  const statusConfig: Record<string, { label: string; color: string }> = {
    todo: {
      label: "À faire",
      color: "bg-blue-100 text-blue-700 dark:bg-blue-950/30 dark:text-blue-400",
    },
    in_progress: {
      label: "En cours",
      color: "bg-yellow-100 text-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-400",
    },
    in_review: {
      label: "Vérification",
      color: "bg-purple-100 text-purple-700 dark:bg-purple-950/30 dark:text-purple-400",
    },
    done: {
      label: "Terminé",
      color: "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400",
    },
  };

  return (
    <div className="space-y-4">
      {isAdmin && (
        <form
          className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2"
          onSubmit={(event) => {
            event.preventDefault();
            void handleAddEtape();
          }}
        >
          <Input
            value={newEtapeTitle}
            onChange={(event) => setNewEtapeTitle(event.target.value)}
            placeholder="Nom de la nouvelle étape..."
            required
            className="h-11 sm:h-9 sm:w-80"
          />
          <Button type="submit" disabled={isCreatingEtape} className="min-h-[44px] sm:min-h-0">
            <PlusIcon className="w-4 h-4" />
            Ajouter une étape
          </Button>
        </form>
      )}

      {etapes.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-24 text-center">
          <ListChecksIcon className="w-12 h-12 text-gray-300 dark:text-gray-600 mb-4" />
          <p className="text-gray-500 dark:text-gray-400 text-lg font-medium">Aucune étape</p>
          <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">
            Les étapes permettent de structurer votre projet en grandes phases
          </p>
        </div>
      ) : (
        etapes.map((etape, index) => {
          const childTasks = tabloTasks.filter((t) => t.parent_task_id === etape.id);
          const doneCount = childTasks.filter((t) => t.status === "done").length;
          const totalCount = childTasks.length;
          const progressPct = totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0;
          const isExpanded = expandedEtapes.has(etape.id);

          // Derive status from child tasks instead of etape.status
          const derivedStatus =
            totalCount === 0
              ? "todo"
              : doneCount === totalCount
                ? "done"
                : doneCount > 0
                  ? "in_progress"
                  : "todo";
          const status = statusConfig[derivedStatus] ?? statusConfig.todo;
          const isEditing = editingEtapeId === etape.id;

          return (
            <div
              key={etape.id}
              className="bg-white dark:bg-card rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm overflow-hidden"
            >
              {/* Etape header */}
              <div className="flex items-center gap-2 px-3 sm:px-5 py-4 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors min-h-[56px]">
                <button
                  type="button"
                  onClick={() => toggleEtape(etape.id)}
                  className="flex flex-1 items-center gap-3 sm:gap-4 text-left min-w-0"
                >
                  {isExpanded ? (
                    <ChevronDownIcon className="w-5 h-5 text-gray-400 shrink-0" />
                  ) : (
                    <ChevronRightIcon className="w-5 h-5 text-gray-400 shrink-0" />
                  )}

                  <div className="w-8 h-8 rounded-lg bg-[#F4F3FF] dark:bg-purple-900/20 flex items-center justify-center shrink-0">
                    <span className="text-sm font-bold text-[#7F56D9] dark:text-purple-400">
                      {index + 1}
                    </span>
                  </div>

                  <div className="flex-1 min-w-0">
                    {isEditing ? (
                      <Input
                        value={editingEtapeTitle}
                        onChange={(event) => setEditingEtapeTitle(event.target.value)}
                        onClick={(event) => event.stopPropagation()}
                        onKeyDown={(event) => {
                          if (event.key === "Enter") {
                            event.preventDefault();
                            void handleUpdateEtape(etape.id);
                          }

                          if (event.key === "Escape") {
                            event.preventDefault();
                            cancelEditingEtape();
                          }
                        }}
                        placeholder="Nom de l'étape"
                        aria-label="Nom de l'étape"
                        autoFocus
                        className="h-9"
                      />
                    ) : (
                      <>
                        <h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate text-sm sm:text-base">
                          {etape.title}
                        </h3>
                        {etape.description && (
                          <p className="text-xs sm:text-sm text-muted-foreground truncate mt-0.5">
                            {etape.description}
                          </p>
                        )}
                      </>
                    )}
                  </div>
                </button>

                <div className="flex items-center gap-2 shrink-0">
                  {etape.due_date && (
                    <div
                      className={cn(
                        "items-center gap-1 text-xs hidden sm:flex",
                        derivedStatus !== "done" &&
                          new Date(etape.due_date) < new Date(new Date().toDateString())
                          ? "text-red-500"
                          : "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon className="w-3.5 h-3.5" />
                      <span>
                        {new Intl.DateTimeFormat("fr-FR", {
                          day: "2-digit",
                          month: "short",
                        }).format(new Date(etape.due_date))}
                      </span>
                    </div>
                  )}

                  <span
                    className={cn(
                      "px-2 sm:px-2.5 py-1 rounded-full text-[10px] sm:text-xs font-medium",
                      status.color
                    )}
                  >
                    {status.label}
                  </span>

                  {totalCount > 0 && (
                    <div className="hidden sm:flex items-center gap-2">
                      <div className="w-16 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-green-500 rounded-full transition-all"
                          style={{ width: `${progressPct}%` }}
                        />
                      </div>
                      <span className="text-xs text-muted-foreground whitespace-nowrap">
                        {doneCount}/{totalCount}
                      </span>
                    </div>
                  )}

                  {isAdmin && (
                    <div className="flex items-center gap-1">
                      {isEditing ? (
                        <>
                          <Button
                            type="button"
                            size="icon"
                            variant="ghost"
                            aria-label="Annuler la modification de l'étape"
                            onClick={() => cancelEditingEtape()}
                            disabled={isUpdatingEtape}
                          >
                            <XIcon className="w-4 h-4" />
                          </Button>
                          <Button
                            type="button"
                            size="icon"
                            variant="ghost"
                            aria-label="Enregistrer l'étape"
                            onClick={() => void handleUpdateEtape(etape.id)}
                            disabled={isUpdatingEtape}
                          >
                            <CheckIcon className="w-4 h-4" />
                          </Button>
                        </>
                      ) : (
                        <>
                          <Button
                            type="button"
                            size="icon"
                            variant="ghost"
                            aria-label={`Modifier l'étape ${etape.title}`}
                            onClick={() => startEditingEtape(etape.id, etape.title)}
                          >
                            <PencilIcon className="w-4 h-4" />
                          </Button>
                          <Button
                            type="button"
                            size="icon"
                            variant="ghost"
                            aria-label={`Supprimer l'étape ${etape.title}`}
                            onClick={() => void handleDeleteEtape(etape.id, etape.title)}
                            disabled={isDeletingEtape}
                          >
                            <Trash2Icon className="w-4 h-4 text-destructive" />
                          </Button>
                        </>
                      )}
                    </div>
                  )}
                </div>
              </div>

              {/* Child tasks + add task */}
              {isExpanded && (
                <div className="border-t border-gray-100 dark:border-gray-700">
                  {childTasks.length > 0 && (
                    <div className="divide-y divide-gray-100 dark:divide-gray-700">
                      {childTasks.map((task) => (
                        <div
                          key={task.id}
                          className={cn(
                            "flex items-center gap-3 px-3 sm:px-5 py-3 pl-8 sm:pl-16 transition-colors",
                            onTaskStatusChange
                              ? "cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800"
                              : "hover:bg-gray-50 dark:hover:bg-gray-800"
                          )}
                          onClick={() =>
                            onTaskStatusChange?.(task.id, task.status === "done" ? "todo" : "done")
                          }
                        >
                          {task.status === "done" ? (
                            <CircleCheckIcon className="w-4 h-4 text-green-500 shrink-0" />
                          ) : (
                            <div className="w-4 h-4 rounded-full border-2 border-gray-300 dark:border-gray-600 shrink-0" />
                          )}
                          <span
                            className={cn(
                              "text-sm flex-1 truncate",
                              task.status === "done"
                                ? "line-through text-gray-400"
                                : "text-gray-900 dark:text-gray-100"
                            )}
                          >
                            {task.title}
                          </span>
                          {task.due_date && (
                            <div
                              className={cn(
                                "flex items-center gap-1 text-xs shrink-0",
                                task.status !== "done" &&
                                  new Date(task.due_date) < new Date(new Date().toDateString())
                                  ? "text-red-500"
                                  : "text-muted-foreground"
                              )}
                            >
                              <CalendarIcon className="w-3 h-3" />
                              <span>
                                {new Intl.DateTimeFormat("fr-FR", {
                                  day: "2-digit",
                                  month: "short",
                                }).format(new Date(task.due_date))}
                              </span>
                            </div>
                          )}
                          {task.status && (
                            <span
                              className={cn(
                                "px-2 py-0.5 rounded-full text-[10px] font-medium shrink-0",
                                (statusConfig[task.status] ?? statusConfig.todo).color
                              )}
                            >
                              {(statusConfig[task.status] ?? statusConfig.todo).label}
                            </span>
                          )}
                        </div>
                      ))}
                    </div>
                  )}

                  {childTasks.length === 0 && addingTaskToEtape !== etape.id && (
                    <div className="px-3 sm:px-5 py-4 pl-8 sm:pl-16 text-sm text-muted-foreground">
                      Aucune tâche dans cette étape
                    </div>
                  )}

                  {/* Inline add task */}
                  {addingTaskToEtape === etape.id ? (
                    <div className="flex items-center gap-2 px-3 sm:px-5 py-3 pl-8 sm:pl-16 border-t border-gray-100 dark:border-gray-700">
                      <div className="w-4 h-4 rounded-full border-2 border-gray-300 dark:border-gray-600 shrink-0" />
                      <input
                        autoFocus
                        type="text"
                        value={newTaskTitle}
                        onChange={(e) => setNewTaskTitle(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") handleAddTask(etape.id);
                          if (e.key === "Escape") {
                            setAddingTaskToEtape(null);
                            setNewTaskTitle("");
                          }
                        }}
                        placeholder="Nom de la tâche..."
                        className="flex-1 text-sm bg-transparent border-none outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 min-w-0"
                      />
                      <button
                        type="button"
                        onClick={() => handleAddTask(etape.id)}
                        disabled={!newTaskTitle.trim()}
                        className="text-xs font-medium px-3 py-2 rounded-md bg-[#804EEC] text-white hover:bg-[#6f3fd4] disabled:opacity-40 transition-colors min-h-[36px] shrink-0"
                      >
                        Ajouter
                      </button>
                      <button
                        type="button"
                        onClick={() => {
                          setAddingTaskToEtape(null);
                          setNewTaskTitle("");
                        }}
                        className="text-xs text-muted-foreground hover:text-foreground px-2 py-2 min-h-[36px] shrink-0"
                      >
                        Annuler
                      </button>
                    </div>
                  ) : (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        setAddingTaskToEtape(etape.id);
                        setNewTaskTitle("");
                      }}
                      className="flex items-center gap-2 px-3 sm:px-5 py-3 pl-8 sm:pl-16 text-sm text-muted-foreground hover:text-[#804EEC] hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors w-full text-left border-t border-gray-100 dark:border-gray-700 min-h-[44px]"
                    >
                      <PlusIcon className="w-4 h-4" />
                      Ajouter une tâche
                    </button>
                  )}
                </div>
              )}
            </div>
          );
        })
      )}
    </div>
  );
}
