import { cn } from "@xtablo/shared";
import type { Etape, TaskStatus } from "@xtablo/shared-types";
import {
  EtapesSection,
  RoadmapSection,
  type SingleTabloTabId,
  SingleTabloView,
  TabloEventsSection,
  TabloFilesSection,
  TabloTasksSection,
} from "@xtablo/tablo-views";
import { FolderIcon } from "lucide-react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import {
  useClientCreateFile,
  useClientCreateFolder,
  useClientCreateTask,
  useClientDeleteFolder,
  useClientDeleteTask,
  useClientDownloadFile,
  useClientTablo,
  useClientTabloEtapes,
  useClientTabloEvents,
  useClientTabloFiles,
  useClientTabloFolders,
  useClientTabloMembers,
  useClientTabloTasks,
  useClientUpdateFolder,
  useClientUpdateTask,
  useClientUpdateTaskPositions,
} from "../hooks/useClientPortal";
import { useClientSession } from "../hooks/useClientSession";

function getStatusConfig(status: string) {
  switch (status) {
    case "in_progress":
      return {
        label: "En cours",
        badgeClass:
          "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800",
      };
    case "done":
      return {
        label: "Terminé",
        badgeClass:
          "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800",
      };
    default:
      return {
        label: "À faire",
        badgeClass:
          "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800",
      };
  }
}

function getEtapeProgressStats(etapes: Etape[]) {
  const total = etapes.length;
  const done = etapes.filter((etape) => etape.status === "done").length;
  const started = etapes.filter((etape) =>
    new Set(["in_progress", "in_review", "done"]).has(etape.status ?? "todo")
  ).length;

  if (total === 0) {
    return {
      startedPercentage: 0,
      donePercentage: 0,
    };
  }

  return {
    startedPercentage: Math.round((started / total) * 100),
    donePercentage: Math.round((done / total) * 100),
  };
}

export function ClientTabloPage() {
  const { tabloId } = useParams<{ tabloId: string }>();
  const [activeTab, setActiveTab] = useState<SingleTabloTabId>("overview");
  const { data: client } = useClientSession();

  const currentUserId = client?.id ?? "";
  const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? "");
  const { data: tasks = [] } = useClientTabloTasks(tabloId ?? "");
  const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? "");
  const {
    data: events,
    isLoading: eventsLoading,
    error: eventsError,
  } = useClientTabloEvents(tabloId ?? "");
  const { data: members = [] } = useClientTabloMembers(tabloId ?? "");
  const {
    data: filesData,
    isLoading: filesLoading,
    error: filesError,
  } = useClientTabloFiles(tabloId ?? "");
  const {
    data: folders = [],
    isLoading: foldersLoading,
    error: foldersError,
  } = useClientTabloFolders(tabloId ?? "");
  const { mutate: createTask } = useClientCreateTask(tabloId ?? "");
  const { mutate: updateTask } = useClientUpdateTask(tabloId ?? "");
  const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? "");
  const { mutate: updateTaskPositions } = useClientUpdateTaskPositions(tabloId ?? "");
  const { mutateAsync: createFile } = useClientCreateFile(tabloId ?? "");
  const { mutateAsync: downloadFile } = useClientDownloadFile();
  const { mutateAsync: createFolder } = useClientCreateFolder(tabloId ?? "");
  const { mutateAsync: updateFolder } = useClientUpdateFolder(tabloId ?? "");
  const { mutateAsync: deleteFolder } = useClientDeleteFolder(tabloId ?? "");

  const fileNames = (filesData?.fileNames ?? []).filter((fileName) => !fileName.startsWith("."));
  const currentUser = { id: currentUserId, avatar_url: null };

  if (tabloLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (!tablo) {
    return (
      <div className="text-center py-16">
        <p className="text-muted-foreground">Projet introuvable.</p>
      </div>
    );
  }

  const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status);
  const progress = getEtapeProgressStats(etapes);

  return (
    <SingleTabloView
      tablo={tablo}
      roleLabel="Invité"
      statusLabel={statusLabel}
      statusBadgeClass={badgeClass}
      progress={progress}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      hiddenTabs={["discussion"]}
    >
      {activeTab === "overview" && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-white dark:bg-card rounded-xl border border-border p-6 sm:p-8 shadow-sm">
              <h2 className="text-xl sm:text-2xl font-bold text-foreground mb-4">
                Description du projet
              </h2>
              <p className="text-muted-foreground leading-relaxed text-sm sm:text-base">
                Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets
                ci-dessus pour naviguer entre les différentes sections.
              </p>
            </div>

            <div className="bg-white dark:bg-card rounded-xl border border-gray-100 dark:border-gray-700 shadow-sm overflow-hidden">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between px-4 sm:px-6 py-4 border-b border-gray-200 dark:border-gray-700 gap-3">
                <h2 className="text-xl sm:text-2xl font-semibold text-gray-900 dark:text-gray-100">
                  Mes tâches
                </h2>
              </div>
              <div className="divide-y divide-gray-200 dark:divide-gray-700">
                {tasks.length === 0 ? (
                  <div className="p-6 text-center text-muted-foreground text-sm">Aucune tâche</div>
                ) : (
                  tasks.slice(0, 5).map((task) => (
                    <button
                      key={task.id}
                      type="button"
                      onClick={() =>
                        updateTask({
                          id: task.id,
                          status: task.status === "done" ? "todo" : "done",
                        })
                      }
                      className="flex w-full items-center gap-3 p-4 text-left transition-colors hover:bg-gray-50 dark:hover:bg-gray-800"
                    >
                      <div
                        className={cn(
                          "w-5 h-5 rounded-full border-2 shrink-0",
                          task.status === "done"
                            ? "bg-green-500 border-green-500"
                            : "border-gray-300 dark:border-gray-600"
                        )}
                      />
                      <p
                        className={cn(
                          "text-sm font-medium truncate",
                          task.status === "done"
                            ? "text-gray-400 line-through"
                            : "text-gray-900 dark:text-gray-100"
                        )}
                      >
                        {task.title}
                      </p>
                    </button>
                  ))
                )}
              </div>
            </div>
          </div>

          <div className="space-y-6">
            <div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-bold text-foreground">Fichiers</h3>
              </div>
              <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-start gap-3 p-3 rounded-lg transition-colors"
                    >
                      <div className="w-10 h-10 bg-red-100 dark:bg-red-900/30 rounded-lg flex items-center justify-center shrink-0">
                        <FolderIcon className="w-4 h-4 text-red-500" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-foreground text-sm truncate">{fileName}</p>
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>

            <div className="bg-white dark:bg-card rounded-xl border border-border p-5 sm:p-6 shadow-sm">
              <h3 className="text-lg font-bold text-foreground mb-4">Informations</h3>
              <dl className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Tâches</dt>
                  <dd className="font-medium text-foreground">{tasks.length}</dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Fichiers</dt>
                  <dd className="font-medium text-foreground">{fileNames.length}</dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Statut</dt>
                  <dd className={cn("px-2 py-0.5 rounded-full text-xs font-medium", badgeClass)}>
                    {statusLabel}
                  </dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-muted-foreground">Rôle</dt>
                  <dd className="font-medium text-foreground">Invité</dd>
                </div>
              </dl>
            </div>
          </div>
        </div>
      )}

      {activeTab === "etapes" && (
        <EtapesSection
          etapes={etapes}
          tabloTasks={tasks}
          tabloId={tablo.id}
          isAdmin={false}
          onCreateTask={(task) => createTask(task)}
          onCreateEtape={async () => undefined}
          onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })}
        />
      )}

      {activeTab === "tasks" && (
        <TabloTasksSection
          tablo={tablo}
          isAdmin={false}
          tasks={tasks}
          members={members}
          etapes={etapes}
          currentUser={currentUser}
          onCreateTask={(task) => createTask(task)}
          onUpdateTask={(task) => updateTask(task)}
          onDeleteTask={(taskId) => deleteTask(taskId)}
          onUpdateTaskPositions={(updates) => updateTaskPositions(updates)}
        />
      )}

      {activeTab === "files" && (
        <TabloFilesSection
          tablo={tablo}
          isAdmin={false}
          isReadOnly={false}
          canUploadFiles={true}
          canManageFolders={true}
          canDeleteFiles={false}
          currentUserId={currentUserId}
          fileNames={fileNames}
          filesLoading={filesLoading}
          filesError={filesError instanceof Error ? filesError : null}
          folders={folders}
          foldersLoading={foldersLoading}
          foldersError={foldersError instanceof Error ? foldersError : null}
          currentUser={currentUser}
          members={members}
          onCreateFile={(params) => createFile(params)}
          onDownloadFile={(params) => downloadFile(params)}
          onCreateFolder={(params) => createFolder(params)}
          onUpdateFolder={(params) => updateFolder(params)}
          onDeleteFolder={(params) => deleteFolder(params)}
        />
      )}

      {activeTab === "events" && (
        <TabloEventsSection
          tablo={tablo}
          isAdmin={false}
          isReadOnly={true}
          events={events as Parameters<typeof TabloEventsSection>[0]["events"]}
          isLoading={eventsLoading}
          error={eventsError instanceof Error ? eventsError : null}
          currentUser={currentUser}
          members={members}
        />
      )}

      {activeTab === "roadmap" && (
        <RoadmapSection
          tabloTasks={tasks}
          onDateClick={() => undefined}
          onTaskStatusChange={(taskId, status) =>
            updateTask({ id: taskId, status: status as TaskStatus })
          }
        />
      )}
    </SingleTabloView>
  );
}
