"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { X, FileText, Plus, Trash2, Users, User, Search, LayoutGrid } from "lucide-react";
import type { ContentTrack } from "@/lib/types";

const TRACK_COLORS: Record<string, string> = {
  ENTERPRISE: "bg-blue-100 text-blue-700",
  PRODUCT: "bg-indigo-100 text-indigo-700",
  DEVELOPER: "bg-purple-100 text-purple-700",
  THOUGHT_LEADERSHIP: "bg-emerald-100 text-emerald-700",
  EVENT: "bg-orange-100 text-orange-700",
  TI_CULTURAL: "bg-pink-100 text-pink-700",
};

const TRACK_LABELS: Record<string, string> = {
  ENTERPRISE: "Enterprise",
  PRODUCT: "Product",
  DEVELOPER: "Developer",
  THOUGHT_LEADERSHIP: "Thought Leadership",
  EVENT: "Event",
  TI_CULTURAL: "Ti-Cultural",
};

const ALL_TRACKS: ContentTrack[] = [
  "ENTERPRISE",
  "PRODUCT",
  "DEVELOPER",
  "THOUGHT_LEADERSHIP",
  "EVENT",
  "TI_CULTURAL",
];

const RECENT_KEY = "pingcap-social-recent-templates";

function getRecentIds(): string[] {
  if (typeof window === "undefined") return [];
  try {
    return JSON.parse(localStorage.getItem(RECENT_KEY) || "[]").slice(0, 3);
  } catch {
    return [];
  }
}

function trackRecentUse(id: string) {
  const ids = getRecentIds().filter((i) => i !== id);
  ids.unshift(id);
  localStorage.setItem(RECENT_KEY, JSON.stringify(ids.slice(0, 3)));
}

interface Template {
  id: string;
  title: string;
  content: string;
  track: ContentTrack | null;
  hashtags: string[];
  isShared: boolean;
  createdBy: string;
  author: { id: string; name: string | null; email: string };
}

interface TemplateLibraryModalProps {
  open: boolean;
  onClose: () => void;
  /** Insert template content. mode = "append" adds to existing, "replace" overwrites */
  onInsert: (content: string, hashtags: string[], mode: "append" | "replace") => void;
  /** Current compose content, used for "Save current as template" */
  currentContent?: string;
}

export function TemplateLibraryModal({
  open,
  onClose,
  onInsert,
  currentContent = "",
}: TemplateLibraryModalProps) {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [loading, setLoading] = useState(false);
  const [filterTrack, setFilterTrack] = useState<ContentTrack | "ALL">("ALL");
  const [searchQuery, setSearchQuery] = useState("");
  const [insertMode, setInsertMode] = useState<"append" | "replace">("append");
  const [showCreate, setShowCreate] = useState(false);

  // "Save current as template" form
  const [showSaveCurrent, setShowSaveCurrent] = useState(false);
  const [saveTitle, setSaveTitle] = useState("");
  const [saveTrack, setSaveTrack] = useState<ContentTrack | "">("");
  const [savingCurrent, setSavingCurrent] = useState(false);

  // Create form state
  const [newTitle, setNewTitle] = useState("");
  const [newContent, setNewContent] = useState("");
  const [newTrack, setNewTrack] = useState<ContentTrack | "">("");
  const [newHashtags, setNewHashtags] = useState("");
  const [newShared, setNewShared] = useState(true);
  const [saving, setSaving] = useState(false);

  const fetchTemplates = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/v1/templates");
      if (res.ok) {
        setTemplates(await res.json());
      }
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) {
      fetchTemplates();
      setSearchQuery("");
      setFilterTrack("ALL");
      setShowCreate(false);
      setShowSaveCurrent(false);
    }
  }, [open, fetchTemplates]);

  // Client-side filtering by search + track
  const filtered = useMemo(() => {
    let list = templates;
    if (filterTrack !== "ALL") {
      list = list.filter((t) => t.track === filterTrack);
    }
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      list = list.filter(
        (t) =>
          t.title.toLowerCase().includes(q) ||
          t.content.toLowerCase().includes(q) ||
          t.hashtags.some((h) => h.toLowerCase().includes(q))
      );
    }
    return list;
  }, [templates, filterTrack, searchQuery]);

  // Quick snippets: 3 most recently used
  const recentIds = useMemo(() => getRecentIds(), [open]); // eslint-disable-line react-hooks/exhaustive-deps
  const quickSnippets = useMemo(
    () =>
      recentIds
        .map((id) => templates.find((t) => t.id === id))
        .filter((t): t is Template => !!t)
        .slice(0, 3),
    [templates, recentIds]
  );

  const handleCreate = async () => {
    if (!newTitle.trim() || !newContent.trim()) return;
    setSaving(true);
    try {
      const hashtags = newHashtags
        .split(",")
        .map((h) => h.trim())
        .filter(Boolean);
      const res = await fetch("/api/v1/templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: newTitle.trim(),
          content: newContent.trim(),
          track: newTrack || null,
          hashtags,
          isShared: newShared,
        }),
      });
      if (res.ok) {
        setNewTitle("");
        setNewContent("");
        setNewTrack("");
        setNewHashtags("");
        setNewShared(true);
        setShowCreate(false);
        fetchTemplates();
      }
    } catch {
      // ignore
    } finally {
      setSaving(false);
    }
  };

  const handleSaveCurrent = async () => {
    if (!saveTitle.trim() || !currentContent.trim()) return;
    setSavingCurrent(true);
    try {
      const res = await fetch("/api/v1/templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: saveTitle.trim(),
          content: currentContent,
          track: saveTrack || null,
          isShared: true,
        }),
      });
      if (res.ok) {
        setSaveTitle("");
        setSaveTrack("");
        setShowSaveCurrent(false);
        fetchTemplates();
      }
    } catch {
      // ignore
    } finally {
      setSavingCurrent(false);
    }
  };

  const handleDelete = async (id: string) => {
    const res = await fetch(`/api/v1/templates/${id}`, { method: "DELETE" });
    if (res.ok) {
      setTemplates((prev) => prev.filter((t) => t.id !== id));
    }
  };

  const handleInsert = (template: Template) => {
    trackRecentUse(template.id);
    onInsert(template.content, template.hashtags, insertMode);
    onClose();
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="relative mx-4 flex max-h-[85vh] w-full max-w-2xl flex-col rounded-xl bg-white shadow-xl">
        {/* Header */}
        <div className="flex items-center justify-between border-b px-4 py-3">
          <div className="flex items-center gap-2">
            <LayoutGrid className="h-4 w-4 text-gray-500" />
            <h3 className="text-sm font-semibold text-gray-900">
              Template Library
            </h3>
          </div>
          <button
            onClick={onClose}
            className="rounded-full p-1 text-gray-400 hover:bg-gray-100"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Save current content as template */}
        {currentContent.trim() && (
          <div className="border-b px-4 py-2">
            {!showSaveCurrent ? (
              <button
                type="button"
                onClick={() => setShowSaveCurrent(true)}
                className="inline-flex items-center gap-1.5 text-xs font-medium text-blue-600 hover:text-blue-700"
              >
                <Plus className="h-3.5 w-3.5" />
                Save current content as template
              </button>
            ) : (
              <div className="flex gap-2 items-end">
                <div className="flex-1">
                  <input
                    value={saveTitle}
                    onChange={(e) => setSaveTitle(e.target.value)}
                    placeholder="Template name..."
                    className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-gray-900"
                  />
                </div>
                <select
                  value={saveTrack}
                  onChange={(e) => setSaveTrack(e.target.value as ContentTrack | "")}
                  className="rounded-lg border border-gray-200 px-2 py-1.5 text-xs text-gray-700"
                >
                  <option value="">No track</option>
                  {ALL_TRACKS.map((t) => (
                    <option key={t} value={t}>{TRACK_LABELS[t]}</option>
                  ))}
                </select>
                <button
                  onClick={handleSaveCurrent}
                  disabled={savingCurrent || !saveTitle.trim()}
                  className="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-gray-800 disabled:opacity-50"
                >
                  {savingCurrent ? "Saving..." : "Save"}
                </button>
                <button
                  onClick={() => setShowSaveCurrent(false)}
                  className="rounded-lg border border-gray-200 px-3 py-1.5 text-xs text-gray-700 hover:bg-gray-50"
                >
                  Cancel
                </button>
              </div>
            )}
          </div>
        )}

        {/* Search + filter bar */}
        <div className="border-b px-4 py-2 space-y-2">
          {/* Search input */}
          <div className="relative">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-gray-400" />
            <input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search by name, content, or tag..."
              className="w-full rounded-lg border border-gray-200 pl-8 pr-3 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-gray-900"
            />
          </div>

          {/* Track filter + insert mode */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-1.5 flex-wrap">
              <button
                onClick={() => setFilterTrack("ALL")}
                className={`rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors ${
                  filterTrack === "ALL"
                    ? "bg-gray-900 text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                All
              </button>
              {ALL_TRACKS.map((t) => (
                <button
                  key={t}
                  onClick={() => setFilterTrack(t)}
                  className={`rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors ${
                    filterTrack === t
                      ? TRACK_COLORS[t]
                      : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                  }`}
                >
                  {TRACK_LABELS[t]}
                </button>
              ))}
            </div>

            {/* Append / Replace toggle */}
            <div className="flex items-center gap-1 text-[10px] text-gray-500 shrink-0 ml-2">
              <button
                type="button"
                onClick={() => setInsertMode("append")}
                className={`px-2 py-0.5 rounded transition-colors ${
                  insertMode === "append"
                    ? "bg-gray-900 text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                Append
              </button>
              <button
                type="button"
                onClick={() => setInsertMode("replace")}
                className={`px-2 py-0.5 rounded transition-colors ${
                  insertMode === "replace"
                    ? "bg-gray-900 text-white"
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                Replace
              </button>
            </div>
          </div>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {loading && (
            <p className="text-sm text-gray-400 text-center py-8">
              Loading templates...
            </p>
          )}

          {!loading && filtered.length === 0 && !showCreate && (
            <div className="text-center py-8">
              <FileText className="mx-auto h-8 w-8 text-gray-300" />
              <p className="mt-2 text-sm text-gray-500">
                {searchQuery || filterTrack !== "ALL"
                  ? "No templates match your filters"
                  : "No templates yet"}
              </p>
              {!searchQuery && filterTrack === "ALL" && (
                <button
                  onClick={() => setShowCreate(true)}
                  className="mt-2 text-sm font-medium text-blue-600 hover:text-blue-700"
                >
                  Create your first template
                </button>
              )}
            </div>
          )}

          {/* Template cards */}
          {filtered.map((t) => (
            <div
              key={t.id}
              className="rounded-lg border border-gray-200 p-3 hover:border-gray-300 transition-colors"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <h4 className="text-sm font-medium text-gray-900 truncate">
                      {t.title}
                    </h4>
                    {t.track && (
                      <span
                        className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${TRACK_COLORS[t.track]}`}
                      >
                        {TRACK_LABELS[t.track]}
                      </span>
                    )}
                    {t.isShared ? (
                      <Users className="h-3 w-3 text-gray-400" />
                    ) : (
                      <User className="h-3 w-3 text-gray-300" />
                    )}
                  </div>
                  <p className="text-xs text-gray-600 line-clamp-2">
                    {t.content.slice(0, 120)}
                    {t.content.length > 120 ? "..." : ""}
                  </p>
                  {t.hashtags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-1.5">
                      {t.hashtags.map((h) => (
                        <span
                          key={h}
                          className="text-[10px] text-blue-600 bg-blue-50 rounded px-1.5 py-0.5"
                        >
                          #{h}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  <button
                    onClick={() => handleInsert(t)}
                    className="rounded-lg bg-gray-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-gray-800 transition-colors"
                  >
                    Use
                  </button>
                  <button
                    onClick={() => handleDelete(t.id)}
                    className="rounded p-1 text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                  </button>
                </div>
              </div>
            </div>
          ))}

          {/* Create form */}
          {showCreate && (
            <div className="rounded-lg border-2 border-dashed border-gray-300 p-4 space-y-3">
              <h4 className="text-sm font-medium text-gray-900">
                New Template
              </h4>
              <input
                value={newTitle}
                onChange={(e) => setNewTitle(e.target.value)}
                placeholder="Template title"
                className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
              />
              <textarea
                value={newContent}
                onChange={(e) => setNewContent(e.target.value)}
                placeholder="Template content..."
                className="w-full min-h-[100px] rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900 resize-y"
              />
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">
                    Track (optional)
                  </label>
                  <select
                    value={newTrack}
                    onChange={(e) =>
                      setNewTrack(e.target.value as ContentTrack | "")
                    }
                    className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-sm"
                  >
                    <option value="">None</option>
                    {ALL_TRACKS.map((t) => (
                      <option key={t} value={t}>
                        {TRACK_LABELS[t]}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">
                    Hashtags (comma-separated)
                  </label>
                  <input
                    value={newHashtags}
                    onChange={(e) => setNewHashtags(e.target.value)}
                    placeholder="TiDB, database, cloud"
                    className="w-full rounded-lg border border-gray-200 px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900"
                  />
                </div>
              </div>
              <label className="flex items-center gap-2 text-sm text-gray-700">
                <input
                  type="checkbox"
                  checked={newShared}
                  onChange={(e) => setNewShared(e.target.checked)}
                  className="rounded"
                />
                Share with team
              </label>
              <div className="flex gap-2">
                <button
                  onClick={handleCreate}
                  disabled={!newTitle.trim() || !newContent.trim() || saving}
                  className="rounded-lg bg-gray-900 px-4 py-1.5 text-xs font-medium text-white hover:bg-gray-800 disabled:opacity-50 transition-colors"
                >
                  {saving ? "Saving..." : "Save Template"}
                </button>
                <button
                  onClick={() => setShowCreate(false)}
                  className="rounded-lg border border-gray-200 px-4 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Quick Snippets section */}
        {quickSnippets.length > 0 && (
          <div className="border-t px-4 py-2.5">
            <p className="text-[10px] font-medium text-gray-400 uppercase tracking-wider mb-1.5">
              Quick Snippets (recently used)
            </p>
            <div className="flex flex-wrap gap-1.5">
              {quickSnippets.map((t) => (
                <button
                  key={t.id}
                  type="button"
                  onClick={() => handleInsert(t)}
                  className="inline-flex items-center gap-1 rounded-full bg-gray-100 border border-gray-200 px-3 py-1 text-xs font-medium text-gray-700 hover:bg-gray-200 transition-colors truncate max-w-[200px]"
                >
                  {t.title}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <div className="flex items-center justify-between border-t px-4 py-3">
          <span className="text-xs text-gray-400">
            {filtered.length} of {templates.length} template{templates.length !== 1 ? "s" : ""}
          </span>
          {!showCreate && (
            <button
              onClick={() => setShowCreate(true)}
              className="inline-flex items-center gap-1 rounded-lg bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-200 transition-colors"
            >
              <Plus className="h-3 w-3" />
              New Template
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
