import { CreateTabloModal } from "@ui/components/CreateTabloModal";
import { DeleteTabloModal } from "@ui/components/DeleteTabloModal";
import { LoadingSpinner } from "@ui/components/LoadingSpinner";
import { toast } from "@xtablo/shared";
import { TabloInsert, UserTablo } from "@xtablo/shared/types/tablos.types";
import { Button } from "@xtablo/ui/components/button";
import {
  Empty,
  EmptyContent,
  EmptyDescription,
  EmptyHeader,
  EmptyTitle,
} from "@xtablo/ui/components/empty";
import { Tooltip, TooltipContent, TooltipTrigger } from "@xtablo/ui/components/tooltip";
import { Text } from "@xtablo/ui/components/typography";
import {
  CheckCircle2,
  Clock,
  Compass,
  Flame,
  FolderIcon,
  Gem,
  Heart,
  Leaf,
  ListTodo,
  MessageSquare,
  Plus,
  Shield,
  Sparkles,
  Star,
  Sun,
  Trash2,
  Users,
  Waves,
  Zap,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } from "react-router-dom";
import { DashboardActionCards } from "src/components/DashboardActionCards";
import { DashboardTaskList } from "src/components/DashboardTaskList";
import { InviteOrganizationModal } from "src/components/InviteOrganizationModal";
import { TaskModal } from "src/components/kanban/TaskModal";
import { ProjectCardList } from "src/components/ProjectCardList";
import { useCanCreateTablo, useCreateTablo, useDeleteTablo, useTablosList } from "../hooks/tablos";
import { useIsReadOnlyUser, useUser } from "../providers/UserStoreProvider";

function getTabloIcon(color: string | null | undefined) {
  switch (color) {
    case "bg-blue-500":
      return Zap;
    case "bg-green-500":
      return Leaf;
    case "bg-purple-500":
      return Gem;
    case "bg-red-500":
      return Flame;
    case "bg-yellow-500":
      return Star;
    case "bg-indigo-500":
      return Compass;
    case "bg-pink-500":
      return Heart;
    case "bg-teal-500":
      return Waves;
    case "bg-orange-500":
      return Sun;
    case "bg-cyan-500":
      return Sparkles;
    default:
      return FolderIcon;
  }
}

function getTabloIconColor(color: string | null | undefined): string {
  switch (color) {
    case "bg-yellow-500":
    case "bg-cyan-500":
      return "text-gray-700";
    default:
      return "text-white";
  }
}

export const TabloPage = () => {
  const { t } = useTranslation(["pages", "common"]);

  const shouldShowKpis = false;

  const [contextMenuTablo, setContextMenuTablo] = useState<string | null>(null);
  const [contextMenuPosition, setContextMenuPosition] = useState<{
    x: number;
    y: number;
  } | null>(null);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
  const [isInviteTeamModalOpen, setIsInviteTeamModalOpen] = useState(false);
  const [deletingTablo, setDeletingTablo] = useState<UserTablo | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [filterType] = useState<"all" | "todo" | "inProgress" | "done">("all");
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const isReadOnlyUser = useIsReadOnlyUser();
  const canCreateTablo = useCanCreateTablo();

  const user = useUser();
  const isReadOnly = isReadOnlyUser || !canCreateTablo;

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return t("pages:tablo.greeting.morning", "Good Morning");
    if (hour < 18) return t("pages:tablo.greeting.afternoon", "Good Afternoon");
    return t("pages:tablo.greeting.evening", "Good Evening");
  };

  const formattedDate = new Intl.DateTimeFormat(undefined, {
    weekday: "long",
    month: "long",
    day: "numeric",
  }).format(new Date());

  // Get view mode from URL params, default to "list"
  const viewMode = (searchParams.get("view") as "grid" | "list") || "list";
  const searchQuery = searchParams.get("q")?.toLowerCase() ?? "";

  const { data: tablos, isLoading, error } = useTablosList();
  const createTabloMutation = useCreateTablo();
  // const { mutateAsync: updateTablo } = useUpdateTablo();
  const { mutateAsync: deleteTablo } = useDeleteTablo();

  // Filter tablos based on status and search query
  const filteredTablos = tablos?.filter((tablo) => {
    const matchesStatus =
      filterType === "all" ||
      (filterType === "todo" && tablo.status === "todo") ||
      (filterType === "inProgress" && tablo.status === "inProgress") ||
      (filterType === "done" && tablo.status === "done");

    const matchesSearch = !searchQuery || tablo.name.toLowerCase().includes(searchQuery);

    return matchesStatus && matchesSearch;
  });

  const menuItems = [
    {
      name: "Discussions",
      action: (tabloId: string) => navigate(`/chat/${tabloId}`),
    },
    {
      name: "Membres",
      action: (tabloId: string) => navigate(`/tablos/${tabloId}?section=members`),
    },
  ];

  const openCreateModal = () => {
    if (isReadOnly) {
      toast.add(
        {
          title: t("common:error"),
          description: "Vous êtes en mode lecture seule. Vous ne pouvez pas créer de projet.",
          type: "error",
        },
        { timeout: 5000 }
      );
      return;
    }
    setIsCreateModalOpen(true);
  };

  const closeCreateModal = () => {
    setIsCreateModalOpen(false);
  };

  const createNewTablo = async (
    tabloData: Pick<TabloInsert, "name" | "color" | "image" | "status">
  ) => {
    try {
      await createTabloMutation.mutateAsync(tabloData);
      setIsCreateModalOpen(false);
    } catch (error) {
      console.error("Error creating tablo:", error);
    }
  };

  const openTablo = (tabloId: string) => {
    navigate(`/tablos/${tabloId}`);
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case "todo":
        return t("pages:tablo.status.todo");
      case "in_progress":
        return t("pages:tablo.status.inProgress");
      case "done":
        return t("pages:tablo.status.done");
      default:
        return t("pages:tablo.status.todo");
    }
  };

  const getStatusBadgeColor = (status: string) => {
    switch (status) {
      case "todo":
        return "bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-300 dark:border-slate-600";
      case "in_progress":
        return "bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-700";
      case "done":
        return "bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 border border-green-300 dark:border-green-700";
      default:
        return "bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-300 dark:border-slate-600";
    }
  };

  // NOTE: Tablo status is now computed from etapes and cannot be changed directly
  // The status change UI has been removed from the context menu

  const handleDeleteTablo = (tabloId: string) => {
    if (!tablos) return;
    const tablo = tablos.find((t) => t.id === tabloId);
    if (tablo) {
      setDeletingTablo(tablo);
    }
  };

  const confirmDeleteTablo = async (tabloId: string) => {
    setIsDeleting(true);
    try {
      await deleteTablo(tabloId);
      setDeletingTablo(null);
    } catch (error) {
      console.error("Error deleting tablo:", error);
    } finally {
      setIsDeleting(false);
    }
  };

  const cancelDeleteTablo = () => {
    setDeletingTablo(null);
    setIsDeleting(false);
  };

  const getUserRole = (tablo: UserTablo) => {
    return tablo.is_admin ? t("pages:tablo.role.admin") : t("pages:tablo.role.guest");
  };

  const getRoleColor = (tablo: UserTablo) => {
    return tablo.is_admin ? "text-primary" : "text-muted-foreground";
  };

  // Calculate KPIs
  const calculateKPIs = () => {
    if (!tablos || tablos.length === 0) return null;

    const totalTablos = tablos.length;
    const todoCount = tablos.filter((t) => t.status === "todo").length;
    const inProgressCount = tablos.filter((t) => t.status === "inProgress").length;
    const doneCount = tablos.filter((t) => t.status === "done").length;
    const adminCount = tablos.filter((t) => t.is_admin).length;
    const guestCount = tablos.filter((t) => !t.is_admin).length;
    const completionRate = totalTablos > 0 ? Math.round((doneCount / totalTablos) * 100) : 0;

    return {
      totalTablos,
      todoCount,
      inProgressCount,
      doneCount,
      adminCount,
      guestCount,
      completionRate,
    };
  };

  const kpis = calculateKPIs();

  const createTabloButton = () => {
    const isCreateDisabled = createTabloMutation.isPending || isReadOnly;

    const button = (
      <Button id="create-tablo-button" onClick={openCreateModal} disabled={isCreateDisabled}>
        <Plus />
        {createTabloMutation.isPending ? t("common:actions.saving") : t("pages:tablo.createButton")}
      </Button>
    );

    if (!isReadOnly) {
      return button;
    }

    return (
      <Tooltip>
        <TooltipTrigger asChild>
          <span className="inline-flex" role="presentation">
            {button}
          </span>
        </TooltipTrigger>
        <TooltipContent>
          {isReadOnlyUser ? (
            <p>Vous ne pouvez pas créer de tablo car vous êtes en mode lecture seule.</p>
          ) : (
            <p>Vous ne pouvez pas créer de tablo car vous avez atteint votre limite de tablos.</p>
          )}
        </TooltipContent>
      </Tooltip>
    );
  };

  // Show loading state
  if (isLoading) {
    return (
      <div className="min-h-screen">
        <header className="bg-card shadow-sm border-b border-border">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-3xl font-bold text-foreground">{t("pages:tablo.title")}</h1>
                <Text className="text-muted-foreground mt-1">{t("pages:tablo.subtitle")}</Text>
              </div>
              {createTabloButton()}
            </div>
          </div>
        </header>
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex justify-center items-center min-h-64">
            <LoadingSpinner />
          </div>
        </main>
      </div>
    );
  }

  // Show error state
  if (error) {
    return (
      <div className="min-h-screen">
        <header className="bg-card shadow-sm border-b border-border">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-3xl font-bold text-foreground">{t("pages:tablo.title")}</h1>
                <Text className="text-muted-foreground mt-1">{t("pages:tablo.subtitle")}</Text>
              </div>
              <Button onClick={openCreateModal} disabled={isReadOnly}>
                <Plus /> Nouveau projet
              </Button>
            </div>
          </div>
        </header>
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex justify-center items-center min-h-64">
            <div className="text-center">
              <p className="text-destructive mb-2">Erreur lors du chargement des projets</p>
              <p className="text-muted-foreground text-sm">
                {error instanceof Error ? error.message : "Une erreur inconnue s'est produite"}
              </p>
            </div>
          </div>
        </main>
      </div>
    );
  }

  const renderTablo = (tablo: UserTablo) => {
    const isAdmin = tablo.is_admin;
    const TabloIcon = getTabloIcon(tablo.color);
    const iconColor = getTabloIconColor(tablo.color);

    return (
      <div
        key={tablo.id}
        className="relative"
        data-tablo-id={tablo.id}
        onContextMenu={(e) => {
          e.preventDefault();
          // Show context menu for all users
          setContextMenuTablo(contextMenuTablo === tablo.id ? null : tablo.id);
          setContextMenuPosition({ x: e.clientX, y: e.clientY });
        }}
      >
        <div
          className={`bg-card rounded-lg shadow-lg transition-all duration-300 w-56 overflow-hidden border border-border ${
            isAdmin ? "hover:shadow-xl cursor-pointer" : "hover:shadow-xl cursor-pointer opacity-75"
          }`}
          onClick={(e) => {
            e.stopPropagation();
            openTablo(tablo.id);
          }}
        >
          {/* Image or Color */}
          <div className="relative h-40 group">
            {tablo.image ? (
              <img src={tablo.image} alt={tablo.name} className="w-full h-full object-cover" />
            ) : (
              <div
                className={`w-full h-full ${
                  tablo.color || "bg-gray-400"
                } flex items-center justify-center`}
              >
                <TabloIcon className={`w-12 h-12 ${iconColor}`} />
              </div>
            )}

            {/* Read-only indicator for non-admins */}
            {!isAdmin && (
              <div className="absolute top-2 right-2 p-1.5 bg-muted text-muted-foreground rounded-full opacity-80">
                <Shield className="w-4 h-4" />
              </div>
            )}
          </div>

          {/* Content */}
          <div className="p-3">
            <div className="space-y-2">
              <div className="flex items-center gap-1">
                <h3 className="text-foreground font-semibold text-base truncate">{tablo.name}</h3>
                {/* Status badge */}
                <div
                  className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusBadgeColor(
                    tablo.status
                  )} shrink-0`}
                >
                  <span>{getStatusLabel(tablo.status)}</span>
                </div>
              </div>
              <div className={`flex items-center gap-1 text-xs font-medium ${getRoleColor(tablo)}`}>
                <Shield className="w-3 h-3" />
                <span>{getUserRole(tablo)}</span>
              </div>
              {/* Action buttons */}
              <div className="flex items-center gap-1 pt-1">
                <Button
                  variant="outline"
                  size="icon-sm"
                  className="p-1.5"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/chat/${tablo.id}`);
                  }}
                  title="Discussions"
                >
                  <MessageSquare className="w-4 h-4" />
                </Button>
                <Button
                  variant="outline"
                  size="icon-sm"
                  className="p-1.5"
                  onClick={(e) => {
                    e.stopPropagation();
                    navigate(`/tablos/${tablo.id}?section=members`);
                  }}
                  title="Members"
                >
                  <Users className="w-4 h-4" />
                </Button>
                <Button
                  variant="outline"
                  size="icon-sm"
                  className="p-1.5 text-destructive hover:text-destructive"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteTablo(tablo.id);
                  }}
                  title={t("pages:tablo.contextMenu.delete")}
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </div>
          </div>
        </div>

        {/* Contextual Menu */}
        {contextMenuTablo === tablo.id && contextMenuPosition && (
          <div
            className="fixed bg-card rounded-lg shadow-lg border border-border py-2 z-30 min-w-36"
            style={{
              left: contextMenuPosition.x,
              top: contextMenuPosition.y,
            }}
            onClick={(e) => e.stopPropagation()}
          >
            {/* Regular menu items - always show */}
            {menuItems.map((item, index) => (
              <button
                key={index}
                className="w-full px-4 py-2 text-left text-sm text-foreground hover:bg-muted"
                onClick={(e) => {
                  e.stopPropagation();
                  item.action(tablo.id);
                }}
              >
                <span>{item.name}</span>
              </button>
            ))}
          </div>
        )}
      </div>
    );
  };

  return (
    <div
      className="min-h-screen"
      onClick={() => {
        setContextMenuTablo(null);
        setContextMenuPosition(null);
      }}
    >
      <header className="px-6 pt-6 pb-4">
        <p className="text-base text-[#475467] dark:text-gray-400 mb-2 font-medium">
          {formattedDate}
        </p>
        <div className="flex items-center justify-between flex-wrap gap-4">
          <h1 className="text-[24px] font-medium text-[#475467] dark:text-gray-400">
            {getGreeting()},{" "}
            <span className="text-gray-900 dark:text-gray-100 font-medium">
              {user.first_name ?? user.name}
            </span>
            !
          </h1>
        </div>
      </header>
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* KPI Section */}
        {shouldShowKpis && kpis && !isReadOnly && (
          <div className="mb-8">
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4">
              {/* Total Tablos */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">Total</p>
                    <p className="text-2xl font-bold text-foreground mt-1">{kpis.totalTablos}</p>
                  </div>
                  <div className="p-2 bg-primary/10 rounded-lg">
                    <Users className="w-5 h-5 text-primary" />
                  </div>
                </div>
              </div>

              {/* Todo Count */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.todo")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">{kpis.todoCount}</p>
                  </div>
                  <div className="p-2 bg-muted rounded-lg">
                    <ListTodo className="w-5 h-5 text-muted-foreground" />
                  </div>
                </div>
              </div>

              {/* In Progress Count */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.inProgress")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">
                      {kpis.inProgressCount}
                    </p>
                  </div>
                  <div className="p-2 bg-primary/10 rounded-lg">
                    <Clock className="w-5 h-5 text-primary" />
                  </div>
                </div>
              </div>

              {/* Done Count */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.done")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">{kpis.doneCount}</p>
                  </div>
                  <div className="p-2 bg-secondary/50 rounded-lg">
                    <CheckCircle2 className="w-5 h-5 text-secondary-foreground" />
                  </div>
                </div>
              </div>

              {/* Completion Rate */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.completionRate")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">
                      {kpis.completionRate}%
                    </p>
                  </div>
                  <div className="p-2 bg-secondary/50 rounded-lg">
                    <CheckCircle2 className="w-5 h-5 text-secondary-foreground" />
                  </div>
                </div>
              </div>

              {/* Admin Count */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.admin")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">{kpis.adminCount}</p>
                  </div>
                  <div className="p-2 bg-primary/10 rounded-lg">
                    <Shield className="w-5 h-5 text-primary" />
                  </div>
                </div>
              </div>

              {/* Guest Count */}
              <div className="bg-card rounded-lg shadow-md p-4 border border-border">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-muted-foreground">
                      {t("pages:tablo.kpis.guest")}
                    </p>
                    <p className="text-2xl font-bold text-foreground mt-1">{kpis.guestCount}</p>
                  </div>
                  <div className="p-2 bg-muted rounded-lg">
                    <Users className="w-5 h-5 text-muted-foreground" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        <DashboardActionCards
          onCreateProject={openCreateModal}
          onCreateTask={() => setIsTaskModalOpen(true)}
          onInviteTeam={() => setIsInviteTeamModalOpen(true)}
          onSendMessage={() => navigate("/chat")}
        />

        <div className="container mx-auto px-4 py-8">
          {filteredTablos && filteredTablos.length > 0 ? (
            viewMode === "grid" ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {filteredTablos.map((tablo) => renderTablo(tablo))}
              </div>
            ) : (
              <ProjectCardList
                tablos={filteredTablos}
                onTabloClick={openTablo}
                onTabloMenuClick={handleDeleteTablo}
              />
            )
          ) : (
            <Empty>
              <EmptyHeader>
                <EmptyTitle>{t("pages:tablo.emptyState.title")}</EmptyTitle>
                <EmptyDescription>
                  {filterType === "all" && t("pages:tablo.emptyState.description")}
                </EmptyDescription>
              </EmptyHeader>
              {filterType === "all" && (
                <EmptyContent>
                  <Button
                    variant="default"
                    size="lg"
                    onClick={openCreateModal}
                    disabled={isReadOnly}
                  >
                    <Plus /> {t("pages:tablo.emptyState.button")}
                  </Button>
                </EmptyContent>
              )}
            </Empty>
          )}
        </div>

        <DashboardTaskList />
      </main>

      {/* Create Tablo Modal */}
      {isCreateModalOpen && (
        <CreateTabloModal onClose={closeCreateModal} onCreate={createNewTablo} />
      )}

      {/* Delete Tablo Modal */}
      {!!deletingTablo && (
        <DeleteTabloModal
          tablo={deletingTablo}
          onClose={cancelDeleteTablo}
          onConfirm={confirmDeleteTablo}
          isDeleting={isDeleting}
        />
      )}

      {/* Create Task Modal */}
      <TaskModal
        isOpen={isTaskModalOpen}
        onClose={() => setIsTaskModalOpen(false)}
        tablos={tablos}
        allowTabloSelection={true}
        initialStatus="todo"
      />
      <InviteOrganizationModal
        isOpen={isInviteTeamModalOpen}
        onOpenChange={setIsInviteTeamModalOpen}
      />
    </div>
  );
};
