import { LoadingSpinner } from "@ui/components/LoadingSpinner";
import { cn } from "@xtablo/shared";
import type { UserTablo } from "@xtablo/shared/types/tablos.types";
import {
  CalendarIcon,
  Compass,
  FilterIcon,
  Flame,
  FolderIcon,
  Gem,
  Grid3x3Icon,
  Heart,
  Leaf,
  ListIcon,
  PlusIcon,
  SearchIcon,
  Sparkles,
  Star,
  Sun,
  Trash2Icon,
  Waves,
  Zap,
} from "lucide-react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useSearchParams } from "react-router-dom";
import { CreateTabloModal } from "../components/CreateTabloModal";
import { DeleteTabloModal } from "../components/DeleteTabloModal";
import { useCreateTablo, useDeleteTablo, useTablosList } from "../hooks/tablos";

// ─── Icon helpers ─────────────────────────────────────────────────────────────

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";
  }
}

// ─── Status helpers ───────────────────────────────────────────────────────────

function getStatusConfig(status: string) {
  switch (status) {
    case "in_progress":
      return {
        label: "En cours",
        badgeClass: "bg-[#FFF4E2] text-[#DB9729] border border-[#DB9729]",
        progress: 50,
      };
    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",
        progress: 100,
      };
    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",
        progress: 0,
      };
  }
}

function formatDate(dateStr: string) {
  return new Intl.DateTimeFormat("fr-FR", {
    month: "short",
    day: "2-digit",
    year: "numeric",
  }).format(new Date(dateStr));
}

// ─── Card view ────────────────────────────────────────────────────────────────

function TabloCard({
  tablo,
  onClick,
  onDelete,
}: {
  tablo: UserTablo;
  onClick: (id: string) => void;
  onDelete: (id: string) => void;
}) {
  const { t } = useTranslation("pages");
  const { label, badgeClass, progress } = getStatusConfig(tablo.status);
  const TabloIcon = getTabloIcon(tablo.color);
  const iconColor = getTabloIconColor(tablo.color);

  return (
    <div
      className="bg-white dark:bg-gray-800 rounded-xl p-6 border border-[#EAECF0] dark:border-gray-700 hover:shadow-md transition-shadow cursor-pointer"
      onClick={() => onClick(tablo.id)}
    >
      {/* Status + delete */}
      <div className="flex items-start justify-between mb-4">
        <span className={cn("px-3 py-1 rounded-full text-sm font-medium", badgeClass)}>
          {label}
        </span>
        <button
          type="button"
          className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
          onClick={(e) => {
            e.stopPropagation();
            onDelete(tablo.id);
          }}
        >
          <Trash2Icon className="w-4 h-4" />
        </button>
      </div>

      {/* Icon + name */}
      <div className="flex items-center gap-3 mb-4">
        <div
          className={cn(
            "w-8 h-8 rounded-lg flex items-center justify-center shrink-0 overflow-hidden",
            !tablo.image && (tablo.color || "bg-gray-400")
          )}
        >
          {tablo.image ? (
            <img src={tablo.image} alt={tablo.name} className="w-full h-full object-cover" />
          ) : (
            <TabloIcon className={cn("w-4 h-4", iconColor)} />
          )}
        </div>
        <h3 className="text-base font-semibold text-gray-900 dark:text-gray-100 flex-1 line-clamp-2">
          {tablo.name}
        </h3>
      </div>

      {/* Date */}
      <div className="flex items-center gap-2 text-gray-600 dark:text-gray-400 mb-4">
        <CalendarIcon className="w-4 h-4 shrink-0" />
        <span className="text-sm">{formatDate(tablo.created_at)}</span>
      </div>

      {/* Progress */}
      <div className="mb-4">
        <div className="flex justify-between items-center mb-2">
          <span className="text-sm text-gray-600 dark:text-gray-400">
            {t("tablo.card.progress")} :
          </span>
          <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
            {progress}%
          </span>
        </div>
        <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
          <div
            className="bg-green-500 h-2 rounded-full transition-all"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>

      {/* Footer */}
      <div className="pt-4 border-t border-dashed border-[#D0D5DD] dark:border-gray-600">
        <span className="text-sm text-gray-500 dark:text-gray-400">
          Créé le{" "}
          <span className="font-semibold text-gray-900 dark:text-gray-100">
            {formatDate(tablo.created_at)}
          </span>
        </span>
      </div>
    </div>
  );
}

// ─── List row ─────────────────────────────────────────────────────────────────

function TabloRow({
  tablo,
  onClick,
  onDelete,
}: {
  tablo: UserTablo;
  onClick: (id: string) => void;
  onDelete: (id: string) => void;
}) {
  const { label, badgeClass, progress } = getStatusConfig(tablo.status);
  const TabloIcon = getTabloIcon(tablo.color);
  const iconColor = getTabloIconColor(tablo.color);

  return (
    <tr
      className="border-t border-[#EAECF0] dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer"
      onClick={() => onClick(tablo.id)}
    >
      <td className="px-6 py-4">
        <div className="flex items-center gap-3">
          <div
            className={cn(
              "w-8 h-8 rounded-lg flex items-center justify-center shrink-0 overflow-hidden",
              !tablo.image && (tablo.color || "bg-gray-400")
            )}
          >
            {tablo.image ? (
              <img src={tablo.image} alt={tablo.name} className="w-full h-full object-cover" />
            ) : (
              <TabloIcon className={cn("w-4 h-4", iconColor)} />
            )}
          </div>
          <span className="font-medium text-gray-900 dark:text-gray-100 truncate">
            {tablo.name}
          </span>
        </div>
      </td>
      <td className="px-6 py-4 whitespace-nowrap">
        <span className={cn("px-3 py-1 rounded-full text-sm font-medium", badgeClass)}>
          {label}
        </span>
      </td>
      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
        <div className="flex items-center gap-1.5">
          <CalendarIcon className="w-4 h-4 shrink-0" />
          {formatDate(tablo.created_at)}
        </div>
      </td>
      <td className="px-6 py-4">
        <div className="flex items-center gap-3">
          <div className="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-2 min-w-[80px]">
            <div
              className="bg-green-500 h-2 rounded-full transition-all"
              style={{ width: `${progress}%` }}
            />
          </div>
          <span className="text-sm font-semibold text-gray-900 dark:text-gray-100 w-8 text-right">
            {progress}%
          </span>
        </div>
      </td>
      <td className="px-6 py-4 text-right">
        <button
          type="button"
          className="text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 transition-colors p-1 rounded"
          onClick={(e) => {
            e.stopPropagation();
            onDelete(tablo.id);
          }}
        >
          <Trash2Icon className="w-4 h-4" />
        </button>
      </td>
    </tr>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export function TablosPage() {
  const { t } = useTranslation("pages");
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const searchQuery = searchParams.get("q")?.toLowerCase() ?? "";

  const [viewMode, setViewMode] = useState<"card" | "list">("card");
  const [statusFilter, setStatusFilter] = useState("all");
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [deleteTabloId, setDeleteTabloId] = useState<string | null>(null);

  const { data: tablos = [], isLoading } = useTablosList();
  const createTablo = useCreateTablo();
  const { mutateAsync: deleteTablo, isPending: isDeleting } = useDeleteTablo();

  const deleteTarget = tablos.find((t) => t.id === deleteTabloId) ?? null;

  const filteredTablos = tablos.filter((tablo) => {
    const matchesSearch = !searchQuery || tablo.name.toLowerCase().includes(searchQuery);
    const matchesStatus = statusFilter === "all" || tablo.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const statusFilters = [
    { value: "all", label: t("tablo.filter.all") },
    { value: "todo", label: t("tablo.filter.todo") },
    { value: "in_progress", label: t("tablo.filter.inProgress") },
    { value: "done", label: t("tablo.filter.done") },
  ];

  return (
    <div className="px-4 pt-8 pb-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-8 gap-4">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">
          {t("tablo.projectList.title")}
        </h1>
        <button
          type="button"
          onClick={() => setShowCreateModal(true)}
          className="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg font-medium flex items-center justify-center gap-2 transition-colors"
        >
          <PlusIcon className="w-5 h-5" />
          {t("tablo.createButton")}
        </button>
      </div>

      {/* View tabs */}
      <div className="flex items-center gap-6 mb-6 border-b border-[#EAECF0] dark:border-gray-700">
        {[
          { id: "card" as const, label: t("tablo.view.grid"), Icon: Grid3x3Icon },
          { id: "list" as const, label: t("tablo.view.list"), Icon: ListIcon },
        ].map(({ id, label, Icon }) => (
          <button
            key={id}
            type="button"
            onClick={() => setViewMode(id)}
            className={cn(
              "flex items-center gap-2 pb-3 border-b-2 transition-colors",
              viewMode === id
                ? "border-purple-600 text-purple-600 dark:border-purple-400 dark:text-purple-400 font-semibold"
                : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
            )}
          >
            <Icon className="w-5 h-5" />
            <span className="font-medium">{label}</span>
          </button>
        ))}
      </div>

      {/* Search + status filter */}
      <div className="flex flex-col md:flex-row gap-4 mb-6">
        <div className="relative md:w-[350px]">
          <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
          <input
            type="text"
            readOnly
            value={searchQuery}
            placeholder="Rechercher..."
            className="w-full pl-10 pr-4 py-3 border border-[#EAECF0] dark:border-gray-700 rounded-[8px] focus:outline-none focus:ring-2 focus:ring-purple-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
          />
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          {statusFilters.map((f) => (
            <button
              key={f.value}
              type="button"
              onClick={() => setStatusFilter(f.value)}
              className={cn(
                "flex items-center gap-1.5 px-4 py-2.5 border rounded-[8px] font-medium text-sm transition-colors",
                statusFilter === f.value
                  ? "border-purple-600 bg-purple-50 dark:bg-purple-950/30 text-purple-600 dark:text-purple-400"
                  : "border-[#EAECF0] dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 text-gray-700 dark:text-gray-300"
              )}
            >
              {f.value === "all" && <FilterIcon className="w-4 h-4" />}
              {f.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="flex items-center justify-center py-24">
          <LoadingSpinner />
        </div>
      ) : filteredTablos.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-24 text-center">
          <div className="w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4">
            <Grid3x3Icon className="w-8 h-8 text-gray-400" />
          </div>
          <p className="text-gray-500 dark:text-gray-400 text-lg font-medium">
            Aucun projet trouvé
          </p>
          <p className="text-gray-400 dark:text-gray-500 text-sm mt-1">
            {searchQuery ? "Essayez un autre terme de recherche" : "Créez votre premier projet"}
          </p>
        </div>
      ) : viewMode === "card" ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {filteredTablos.map((tablo) => (
            <TabloCard
              key={tablo.id}
              tablo={tablo}
              onClick={(id) => navigate(`/tablos/${id}`)}
              onDelete={setDeleteTabloId}
            />
          ))}
        </div>
      ) : (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-[#EAECF0] dark:border-gray-700 overflow-hidden">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-800/80 border-b border-[#EAECF0] dark:border-gray-700">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
                  Projet
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
                  Statut
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
                  Créé le
                </th>
                <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
                  Progression
                </th>
                <th className="px-6 py-3 w-12" />
              </tr>
            </thead>
            <tbody>
              {filteredTablos.map((tablo) => (
                <TabloRow
                  key={tablo.id}
                  tablo={tablo}
                  onClick={(id) => navigate(`/tablos/${id}`)}
                  onDelete={setDeleteTabloId}
                />
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Create modal */}
      {showCreateModal && (
        <CreateTabloModal
          onClose={() => setShowCreateModal(false)}
          onCreate={(tabloData) => {
            createTablo.mutate({ ...tabloData, status: "todo" });
            setShowCreateModal(false);
          }}
        />
      )}

      {/* Delete modal */}
      <DeleteTabloModal
        tablo={deleteTarget}
        onClose={() => setDeleteTabloId(null)}
        onConfirm={async (id) => {
          await deleteTablo(id);
          setDeleteTabloId(null);
        }}
        isDeleting={isDeleting}
      />
    </div>
  );
}
