import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { adminApi, adminEndpoints } from "../api";
import type { ComponentRecord } from "../types";
import { RotateCcw, Trash2, ArrowLeft } from "lucide-react";
import { getBlockComponent } from "@/components/page-blocks";
import { notifyComponentLibraryUpdated } from "@/lib/componentDefaults";
import { resolvePreviewContent } from "@/lib/contentPlaceholders";
import ComponentAccordionItem from "../components/ComponentAccordionItem";

export default function ArchivedComponentsList() {
  const [components, setComponents] = useState<ComponentRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [actionId, setActionId] = useState<number | null>(null);
  const [error, setError] = useState("");
  const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
  const hasInitializedExpanded = useRef(false);

  const load = async () => {
    setLoading(true);
    try {
      const data = await adminApi.get<{ components: ComponentRecord[] }>(adminEndpoints.componentsArchived);
      const nextComponents = data.components ?? [];
      setComponents(nextComponents);
      setExpandedIds((prev) => {
        const allIds = new Set(nextComponents.map((component) => component.id));
        if (!hasInitializedExpanded.current) {
          hasInitializedExpanded.current = true;
          return allIds;
        }

        const next = new Set<number>();
        prev.forEach((id) => {
          if (allIds.has(id)) next.add(id);
        });
        return next;
      });
    } catch {
      setComponents([]);
      setExpandedIds(new Set());
    } finally {
      setLoading(false);
    }
  };

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

  const restoreComponent = async (c: ComponentRecord) => {
    setActionId(c.id);
    setError("");
    try {
      await adminApi.post(adminEndpoints.componentRestore(c.id), {});
      notifyComponentLibraryUpdated();
      await load();
    } catch {
      setError("Failed to restore component.");
      setTimeout(() => setError(""), 4000);
    } finally {
      setActionId(null);
    }
  };

  const deleteComponent = async (c: ComponentRecord) => {
    if (!confirm(`Permanently delete "${c.name}"? This cannot be undone.`)) return;
    setActionId(c.id);
    setError("");
    try {
      await adminApi.delete(adminEndpoints.component(c.id));
      await load();
    } catch {
      setError("Failed to delete component.");
      setTimeout(() => setError(""), 4000);
    } finally {
      setActionId(null);
    }
  };

  const toggleComponent = (id: number) => {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const expandAll = () => {
    setExpandedIds(new Set(components.map((component) => component.id)));
  };

  const collapseAll = () => {
    setExpandedIds(new Set());
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Link
          to="/dashboard/components"
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            color: "#64748b",
            fontSize: 14,
            marginBottom: 8,
            textDecoration: "none",
          }}
        >
          <ArrowLeft size={16} />
          Back to Components
        </Link>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700 }}>Archived Components</h1>
          {!loading && components.length > 0 && (
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              <button
                type="button"
                onClick={expandAll}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  padding: "8px 14px",
                  border: "1px solid #e2e8f0",
                  borderRadius: 8,
                  background: "#fff",
                  cursor: "pointer",
                  fontWeight: 500,
                }}
              >
                Expand All
              </button>
              <button
                type="button"
                onClick={collapseAll}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  padding: "8px 14px",
                  border: "1px solid #e2e8f0",
                  borderRadius: 8,
                  background: "#fff",
                  cursor: "pointer",
                  fontWeight: 500,
                }}
              >
                Collapse All
              </button>
            </div>
          )}
        </div>
        <p style={{ color: "#64748b", margin: "8px 0 0", fontSize: 14 }}>
          Restore components to use them again, or delete them permanently.
        </p>
      </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>
      ) : components.length === 0 ? (
        <div style={{ background: "#f8fafc", padding: 32, borderRadius: 12, textAlign: "center", color: "#64748b" }}>
          <p style={{ margin: 0 }}>No archived components.</p>
          <Link to="/dashboard/components" style={{ display: "inline-block", marginTop: 12, color: "#0f172a", fontWeight: 500 }}>
            View active components
          </Link>
        </div>
      ) : (
        <div style={{ display: "grid", gap: 12 }}>
          {components.map((c) => (
            <ComponentAccordionItem
              key={c.id}
              component={c}
              isExpanded={expandedIds.has(c.id)}
              onToggle={() => toggleComponent(c.id)}
              withBorder
              previewMaxHeight={280}
              actions={
                <>
                  <button
                    type="button"
                    onClick={() => restoreComponent(c)}
                    disabled={actionId === c.id}
                    title="Restore to active components"
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 8,
                      padding: "8px 14px",
                      border: "1px solid #22c55e",
                      borderRadius: 8,
                      background: "#f0fdf4",
                      color: "#15803d",
                      cursor: actionId === c.id ? "not-allowed" : "pointer",
                      fontWeight: 500,
                      opacity: actionId === c.id ? 0.7 : 1,
                    }}
                  >
                    <RotateCcw size={18} />
                    {actionId === c.id ? "…" : " Restore"}
                  </button>
                  <button
                    type="button"
                    onClick={() => deleteComponent(c)}
                    disabled={actionId === c.id}
                    title="Delete permanently"
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 8,
                      padding: "8px 14px",
                      border: "1px solid #fecaca",
                      borderRadius: 8,
                      background: "#fef2f2",
                      color: "#b91c1c",
                      cursor: actionId === c.id ? "not-allowed" : "pointer",
                      fontWeight: 500,
                      opacity: actionId === c.id ? 0.7 : 1,
                    }}
                  >
                    <Trash2 size={18} />
                    Delete
                  </button>
                </>
              }
              preview={
                (() => {
                  const BlockComp = getBlockComponent(c.slug);
                  if (!BlockComp) return <span className="text-muted-foreground text-sm italic">No preview</span>;
                  return (
                    <BlockComp
                      content={resolvePreviewContent((c.content ?? {}) as Record<string, unknown>, {
                        blockSlug: c.slug,
                      })}
                    />
                  );
                })()
              }
            />
          ))}
        </div>
      )}
    </div>
  );
}
