import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { adminApi, adminEndpoints } from "../api";
import type { PageRecord } from "../types";
import { Plus, Pencil, Trash2, Copy, X } from "lucide-react";
import {
  closeAdminSwal,
  confirmDeletePage,
  showDeletePageError,
  showDeletePageLoading,
  showDeletePageSuccess,
} from "../lib/adminSwal";

export default function PagesList() {
  const [pages, setPages] = useState<PageRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [copyModalOpen, setCopyModalOpen] = useState(false);
  const [pageToCopy, setPageToCopy] = useState<PageRecord | null>(null);
  const [copyTitle, setCopyTitle] = useState("");
  const [copySaving, setCopySaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);

  const load = async () => {
    setLoading(true);
    try {
      const data = await adminApi.get<{ pages: PageRecord[] }>(adminEndpoints.pages);
      setPages(data.pages ?? []);
    } catch {
      setPages([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const deletePage = async (id: number) => {
    if (deletingId !== null) return;

    const confirmed = await confirmDeletePage();
    if (!confirmed) return;

    setDeletingId(id);
    showDeletePageLoading();

    try {
      await adminApi.delete(adminEndpoints.page(id));
      closeAdminSwal();
      setPages((prev) => prev.filter((p) => p.id !== id));
      await showDeletePageSuccess();
    } catch (e) {
      closeAdminSwal();
      const message = e instanceof Error ? e.message : "Delete failed";
      await showDeletePageError(message);
    } finally {
      setDeletingId(null);
    }
  };

  const openCopyModal = (page: PageRecord) => {
    setPageToCopy(page);
    setCopyTitle(`${page.title} Copy`);
    setCopyModalOpen(true);
  };

  const closeCopyModal = () => {
    setCopyModalOpen(false);
    setPageToCopy(null);
    setCopyTitle("");
    setCopySaving(false);
  };

  const copyPage = async () => {
    if (!pageToCopy) return;
    const trimmedTitle = copyTitle.trim();
    if (!trimmedTitle) {
      setError("Page name is required to create a copy.");
      setTimeout(() => setError(""), 4000);
      return;
    }

    setCopySaving(true);
    try {
      await adminApi.post(adminEndpoints.pageCopy(pageToCopy.id), { title: trimmedTitle });
      closeCopyModal();
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : "Copy failed");
      setTimeout(() => setError(""), 4000);
    } finally {
      setCopySaving(false);
    }
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24, flexWrap: "wrap", gap: 16 }}>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700 }}>Pages</h1>
        <Link
          to="/dashboard/pages/new"
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 8,
            padding: "10px 16px",
            background: "#161c24",
            color: "#fff",
            borderRadius: 8,
            textDecoration: "none",
            fontWeight: 600,
          }}
        >
          <Plus size={18} /> New page
        </Link>
      </div>
      {error && (
        <div style={{ marginBottom: 12, padding: "10px 12px", borderRadius: 10, background: "#fef2f2", border: "1px solid #fecaca", color: "#b91c1c", fontSize: 13 }}>
          {error}
        </div>
      )}
      {loading ? (
        <p style={{ color: "#64748b" }}>Loading...</p>
      ) : pages.length === 0 ? (
        <div style={{ background: "#f8fafc", padding: 32, borderRadius: 12, textAlign: "center", color: "#64748b" }}>
          <p style={{ margin: "0 0 16px" }}>No pages yet.</p>
          <Link to="/dashboard/pages/new" style={{ color: "#161c24", fontWeight: 600 }}>
            Create your first page
          </Link>
        </div>
      ) : (
        <div className="pages-grid">
          {pages.map((p) => (
            <div key={p.id} className="page-card">
              <div style={{ flex: 1 }}>
                <h3 className="page-card__title">{p.title}</h3>
                <p className="page-card__slug">/{p.slug}</p>
                <div className="page-card__meta">
                  <span
                    className={`page-card__status page-card__status--${(p.status || "draft").toLowerCase()}`}
                  >
                    {p.status}
                  </span>
                </div>
              </div>
              <div className="page-card__actions">
                <Link
                  to={`/dashboard/pages/${p.id}/edit`}
                  className="page-card__btn page-card__btn--primary"
                >
                  <Pencil size={16} /> Edit
                </Link>
                <button
                  type="button"
                  onClick={() => openCopyModal(p)}
                  title="Create Copy"
                  className="page-card__btn"
                  disabled={deletingId !== null}
                >
                  <Copy size={16} /> Create Copy
                </button>
                <button
                  type="button"
                  onClick={() => deletePage(p.id)}
                  title="Delete"
                  className="page-card__btn page-card__btn--danger"
                  disabled={deletingId !== null}
                  aria-busy={deletingId === p.id}
                >
                  <Trash2 size={16} /> {deletingId === p.id ? "Deleting…" : "Delete"}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
      {copyModalOpen && pageToCopy && (
        <div
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 40,
            background: "rgba(15, 23, 42, 0.45)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: 20,
          }}
        >
          <div
            style={{
              width: "100%",
              maxWidth: 460,
              background: "#fff",
              borderRadius: 14,
              boxShadow: "0 24px 48px rgba(0,0,0,0.2)",
              overflow: "hidden",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                padding: "14px 18px",
                borderBottom: "1px solid #e2e8f0",
              }}
            >
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>Copy page</h2>
              <button
                type="button"
                onClick={closeCopyModal}
                style={{ border: "none", background: "transparent", cursor: "pointer", color: "#64748b", padding: 4 }}
              >
                <X size={18} />
              </button>
            </div>
            <div style={{ padding: 18 }}>
              <p style={{ margin: "0 0 12px", color: "#475569", fontSize: 14 }}>
                Enter a name for the copied page. The copy will be created as a draft.
              </p>
              <label style={{ display: "block", marginBottom: 8, fontWeight: 600, fontSize: 13, color: "#334155" }}>
                New page name
              </label>
              <input
                type="text"
                value={copyTitle}
                onChange={(e) => setCopyTitle(e.target.value)}
                placeholder="Page name"
                autoFocus
                style={{
                  width: "100%",
                  padding: "10px 12px",
                  border: "1px solid #cbd5e1",
                  borderRadius: 10,
                  fontSize: 14,
                  boxSizing: "border-box",
                }}
              />
            </div>
            <div
              style={{
                display: "flex",
                justifyContent: "flex-end",
                gap: 10,
                padding: "14px 18px",
                borderTop: "1px solid #e2e8f0",
              }}
            >
              <button
                type="button"
                onClick={closeCopyModal}
                style={{
                  border: "1px solid #cbd5e1",
                  background: "#fff",
                  color: "#334155",
                  borderRadius: 10,
                  padding: "9px 14px",
                  fontWeight: 600,
                  cursor: "pointer",
                }}
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={copyPage}
                disabled={copySaving}
                style={{
                  border: "none",
                  background: copySaving ? "#94a3b8" : "#0f172a",
                  color: "#fff",
                  borderRadius: 10,
                  padding: "9px 14px",
                  fontWeight: 600,
                  cursor: copySaving ? "not-allowed" : "pointer",
                }}
              >
                {copySaving ? "Copying..." : "Create copy"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
