"use client";

import React, { useEffect, useState } from "react";
import Link from "next/link";
import { FolderKanban, Plus, Lock, MoreVertical, Pencil, Trash2, X, Download } from "lucide-react";
import { useI18n } from "@/lib/i18n/context";
import { useDashboardShell } from "@/components/dashboard/DashboardShellContext";
import {
  ServerProject,
  fetchProjects,
  createProject,
  renameProject,
  deleteProject,
} from "@/lib/storage/server";
import { apiFetch } from "@/lib/csrf/client";

const PROJECT_COLORS: { key: string; hex: string }[] = [
  { key: "slate", hex: "#475569" },
  { key: "blue", hex: "#3b68ff" },
  { key: "emerald", hex: "#10b981" },
  { key: "amber", hex: "#f59e0b" },
  { key: "rose", hex: "#e11d48" },
  { key: "violet", hex: "#7c3aed" },
];

function colorHex(key: string | null): string {
  return PROJECT_COLORS.find((c) => c.key === key)?.hex ?? "#94A3B8";
}

export default function ProjectsPage() {
  const { language } = useI18n();
  const isDe = language === "de";
  const { openPaywall } = useDashboardShell();

  const [isPro, setIsPro] = useState(false);
  const [projectList, setProjectList] = useState<ServerProject[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [newName, setNewName] = useState("");
  const [newColor, setNewColor] = useState(PROJECT_COLORS[1].key);
  const [isSaving, setIsSaving] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const [renamingId, setRenamingId] = useState<string | null>(null);
  const [renameValue, setRenameValue] = useState("");
  const [deleteTarget, setDeleteTarget] = useState<ServerProject | null>(null);

  useEffect(() => {
    let active = true;
    async function load() {
      try {
        const res = await apiFetch("/api/auth/session");
        const data = res.ok ? await res.json() : null;
        if (active) setIsPro(Boolean(data?.user?.isPro));
      } catch {
        if (active) setIsPro(false);
      }
      const rows = await fetchProjects();
      if (active) {
        setProjectList(rows);
        setIsLoading(false);
      }
    }
    load();
    return () => {
      active = false;
    };
  }, []);

  const openCreate = () => {
    if (!isPro) {
      openPaywall();
      return;
    }
    setIsCreateOpen(true);
  };

  const handleCreate = async () => {
    const name = newName.trim();
    if (!name) return;
    setIsSaving(true);
    setErrorMessage(null);
    const created = await createProject(name, newColor);
    setIsSaving(false);
    if (!created) {
      setErrorMessage(
        isDe
          ? "Projekt konnte nicht erstellt werden (Name evtl. bereits vergeben)."
          : "Could not create project (name might already be taken)."
      );
      return;
    }
    setProjectList((prev) => [created, ...prev]);
    setIsCreateOpen(false);
    setNewName("");
    setNewColor(PROJECT_COLORS[1].key);
  };

  const openRename = (p: ServerProject) => {
    setOpenMenuId(null);
    if (!isPro) {
      openPaywall();
      return;
    }
    setRenamingId(p.id);
    setRenameValue(p.name);
  };

  const openDelete = (p: ServerProject) => {
    setOpenMenuId(null);
    if (!isPro) {
      openPaywall();
      return;
    }
    setDeleteTarget(p);
  };

  const handleRename = async (id: string) => {
    const name = renameValue.trim();
    setRenamingId(null);
    if (!name) return;
    const updated = await renameProject(id, { name });
    if (updated) {
      setProjectList((prev) => prev.map((p) => (p.id === id ? { ...p, name: updated.name } : p)));
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    const target = deleteTarget;
    setDeleteTarget(null);
    const ok = await deleteProject(target.id);
    if (ok) {
      setProjectList((prev) => prev.filter((p) => p.id !== target.id));
    }
  };

  return (
    <div className="space-y-8 font-sans">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-6 border-b border-[#E2E8F0]">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="w-2.5 h-2.5 bg-black"></span>
            <span className="font-mono text-xs uppercase tracking-caps font-semibold text-[#475569]">
              {isDe ? "BELEGE ORGANISIEREN" : "ORGANIZE RECEIPTS"}
            </span>
          </div>
          <h1 className="font-display text-3xl sm:text-4xl font-bold tracking-tight text-black">
            {isDe ? "PROJEKTE" : "PROJECTS"}
          </h1>
          <p className="text-xs text-[#64748B] font-mono mt-1">
            {isDe
              ? "Belege in eigenen Ordnern sortieren, statt alles in einer Liste zu sammeln."
              : "Sort receipts into folders instead of one flat list."}
            {!isPro && (
              <span className="text-[#94A3B8]">
                {" · "}
                {isDe
                  ? "Erstellen ist ein Pro-Feature."
                  : "Creating projects is a Pro feature."}
              </span>
            )}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Link
            href="/dashboard/export"
            className="px-4 py-2.5 bg-white border border-[#E2E8F0] hover:border-black text-black font-mono text-xs uppercase tracking-caps transition-colors font-medium flex items-center gap-2"
          >
            <Download className="w-4 h-4" />
            <span>{isDe ? "EXPORTIEREN" : "EXPORT"}</span>
          </Link>
          <button
            type="button"
            onClick={openCreate}
            data-testid="new-project-btn"
            className="px-5 py-2.5 bg-black text-white font-mono text-xs uppercase tracking-caps hover:bg-[#334155] transition-colors font-medium flex items-center gap-2"
          >
            {isPro ? <Plus className="w-4 h-4" /> : <Lock className="w-3.5 h-3.5" />}
            <span>{isDe ? "NEUES PROJEKT" : "NEW PROJECT"}</span>
          </button>
        </div>
      </div>

      {errorMessage && (
        <div className="border border-[#BA1A1A] bg-[#FFDAD6] p-4 text-xs text-[#93000A]">
          {errorMessage}
        </div>
      )}

      {/* Grid */}
      {isLoading ? (
        <div className="text-center py-16 text-[#94A3B8] font-mono text-xs">
          {isDe ? "Lädt…" : "Loading…"}
        </div>
      ) : projectList.length === 0 ? (
        <div className="border border-dashed border-[#CBD5E1] p-12 text-center space-y-3">
          <FolderKanban className="w-8 h-8 mx-auto text-[#94A3B8]" />
          <p className="text-sm text-[#475569]">
            {isDe ? "Noch keine Projekte angelegt." : "No projects yet."}
          </p>
          <button
            type="button"
            onClick={openCreate}
            className="font-mono text-xs uppercase tracking-caps text-black underline"
          >
            {isPro
              ? isDe
                ? "Erstes Projekt anlegen"
                : "Create your first project"
              : isDe
              ? "Auf Pro upgraden, um loszulegen"
              : "Upgrade to Pro to get started"}
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {projectList.map((p) => (
            <div
              key={p.id}
              data-testid={`project-card-${p.id}`}
              className="relative bg-white border border-[#E2E8F0] p-5 hover:border-black transition-colors"
            >
              <div className="flex items-start justify-between gap-2">
                <Link href={`/dashboard/projects/${p.id}`} className="flex items-center gap-2 min-w-0">
                  <span className="w-3 h-3 shrink-0" style={{ backgroundColor: colorHex(p.color) }} />
                  {renamingId === p.id ? (
                    <input
                      autoFocus
                      value={renameValue}
                      onChange={(e) => setRenameValue(e.target.value)}
                      onClick={(e) => e.preventDefault()}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          e.preventDefault();
                          void handleRename(p.id);
                        }
                        if (e.key === "Escape") setRenamingId(null);
                      }}
                      onBlur={() => void handleRename(p.id)}
                      className="font-display text-base font-bold text-black border-b border-black focus:outline-none bg-transparent min-w-0"
                    />
                  ) : (
                    <span className="font-display text-base font-bold text-black truncate">{p.name}</span>
                  )}
                </Link>
                <div className="relative shrink-0">
                  <button
                    type="button"
                    onClick={() => setOpenMenuId(openMenuId === p.id ? null : p.id)}
                    className="p-1 text-[#94A3B8] hover:text-black"
                    aria-label={isDe ? "Menü öffnen" : "Open menu"}
                  >
                    <MoreVertical className="w-4 h-4" />
                  </button>
                  {openMenuId === p.id && (
                    <div className="absolute right-0 top-7 z-10 w-40 bg-white border border-black shadow-lg font-mono text-xs">
                      <button
                        type="button"
                        onClick={() => openRename(p)}
                        className="w-full flex items-center gap-2 px-3 py-2 hover:bg-[#F8FAFC] text-left"
                      >
                        <Pencil className="w-3.5 h-3.5" />
                        {isDe ? "Umbenennen" : "Rename"}
                      </button>
                      <button
                        type="button"
                        onClick={() => openDelete(p)}
                        className="w-full flex items-center gap-2 px-3 py-2 hover:bg-red-50 text-red-600 text-left"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                        {isDe ? "Löschen" : "Delete"}
                      </button>
                    </div>
                  )}
                </div>
              </div>
              <Link href={`/dashboard/projects/${p.id}`} className="block mt-4 pt-4 border-t border-[#E2E8F0]">
                <span className="font-mono text-[11px] uppercase tracking-caps text-[#64748B]">
                  {p.receiptCount}{" "}
                  {isDe
                    ? p.receiptCount === 1
                      ? "Beleg"
                      : "Belege"
                    : p.receiptCount === 1
                    ? "receipt"
                    : "receipts"}
                </span>
              </Link>
            </div>
          ))}
        </div>
      )}

      {/* Create Modal */}
      {isCreateOpen && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 font-sans">
          <div className="bg-white border-2 border-black max-w-md w-full p-6 shadow-2xl">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-display text-lg font-bold text-black">
                {isDe ? "Neues Projekt" : "New Project"}
              </h3>
              <button
                type="button"
                onClick={() => setIsCreateOpen(false)}
                className="p-1 text-[#94A3B8] hover:text-black"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
            <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium mb-1">
              {isDe ? "Name" : "Name"}
            </label>
            <input
              autoFocus
              data-testid="new-project-name-input"
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") void handleCreate();
              }}
              placeholder={isDe ? "z. B. Kunde XY" : "e.g. Client XY"}
              className="w-full bg-[#F8FAFC] border border-[#E2E8F0] px-3 py-2 font-mono text-sm text-black focus:border-black focus:outline-none mb-4"
            />
            <label className="block font-mono text-[11px] uppercase tracking-caps text-[#475569] font-medium mb-2">
              {isDe ? "Farbe" : "Color"}
            </label>
            <div className="flex items-center gap-2 mb-6">
              {PROJECT_COLORS.map((c) => (
                <button
                  key={c.key}
                  type="button"
                  onClick={() => setNewColor(c.key)}
                  className={`w-7 h-7 rounded-full border-2 transition-transform ${
                    newColor === c.key ? "border-black scale-110" : "border-transparent"
                  }`}
                  style={{ backgroundColor: c.hex }}
                  aria-label={c.key}
                />
              ))}
            </div>
            <div className="flex items-center justify-end gap-3 font-mono text-xs uppercase tracking-caps">
              <button
                type="button"
                onClick={() => setIsCreateOpen(false)}
                className="px-4 py-2 border border-[#CBD5E1] bg-white hover:border-black text-black"
              >
                {isDe ? "Abbrechen" : "Cancel"}
              </button>
              <button
                type="button"
                data-testid="new-project-confirm-btn"
                onClick={() => void handleCreate()}
                disabled={isSaving || !newName.trim()}
                className="px-4 py-2 bg-black hover:bg-[#334155] text-white font-bold disabled:opacity-40"
              >
                {isDe ? "Erstellen" : "Create"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirm */}
      {deleteTarget && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 font-sans">
          <div className="bg-white border-2 border-black max-w-md w-full p-6 shadow-2xl">
            <h3 className="font-display text-lg font-bold text-black mb-2">
              {isDe ? `„${deleteTarget.name}“ löschen?` : `Delete "${deleteTarget.name}"?`}
            </h3>
            <p className="text-xs text-[#475569] mb-6">
              {isDe
                ? "Die Belege in diesem Projekt werden nicht gelöscht, sondern nur wieder aus dem Projekt entfernt."
                : "Receipts in this project will not be deleted — they'll just be removed from the project."}
            </p>
            <div className="flex items-center justify-end gap-3 font-mono text-xs uppercase tracking-caps">
              <button
                type="button"
                onClick={() => setDeleteTarget(null)}
                className="px-4 py-2 border border-[#CBD5E1] bg-white hover:border-black text-black"
              >
                {isDe ? "Abbrechen" : "Cancel"}
              </button>
              <button
                type="button"
                onClick={() => void handleDelete()}
                className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-bold"
              >
                {isDe ? "Endgültig löschen" : "Delete Permanently"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
