"use client";

import { useEffect, useState } from "react";
import { useToastStore } from "@/lib/stores/toast-store";

interface Reply {
  id: number;
  label: string;
  body: string;
  sort_order: number;
}

export default function RepliesClient() {
  const [replies, setReplies] = useState<Reply[]>([]);
  const [loading, setLoading] = useState(true);
  const [label, setLabel] = useState("");
  const [body, setBody] = useState("");
  const [busy, setBusy] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const addToast = useToastStore((s) => s.addToast);

  useEffect(() => {
    fetch("/api/messaging/replies")
      .then((r) => r.json())
      .then((data) => setReplies(Array.isArray(data?.data) ? data.data : []))
      .finally(() => setLoading(false));
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!label.trim() || !body.trim()) {
      addToast("error", "Label and body are required");
      return;
    }
    setBusy(true);
    try {
      if (editingId !== null) {
        const res = await fetch("/api/messaging/replies", {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id: editingId, label, body }),
        });
        const data = await res.json();
        if (!res.ok) {
          addToast("error", data.error || "Failed to update");
          return;
        }
        setReplies((prev) => prev.map((r) => (r.id === editingId ? data.data : r)));
        setEditingId(null);
        addToast("success", "Reply updated");
      } else {
        const res = await fetch("/api/messaging/replies", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ label, body }),
        });
        const data = await res.json();
        if (!res.ok) {
          addToast("error", data.error || "Failed to save");
          return;
        }
        setReplies((prev) => [...prev, data.data]);
        addToast("success", "Reply added");
      }
      setLabel("");
      setBody("");
    } finally {
      setBusy(false);
    }
  }

  async function handleDelete(id: number) {
    if (!confirm("Delete this reply?")) return;
    const res = await fetch(`/api/messaging/replies?id=${id}`, { method: "DELETE" });
    if (res.ok) {
      setReplies((prev) => prev.filter((r) => r.id !== id));
      addToast("success", "Reply deleted");
    } else {
      addToast("error", "Failed to delete");
    }
  }

  function startEdit(reply: Reply) {
    setEditingId(reply.id);
    setLabel(reply.label);
    setBody(reply.body);
  }

  function cancelEdit() {
    setEditingId(null);
    setLabel("");
    setBody("");
  }

  return (
    <div className="space-y-6">
      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-4 space-y-3">
        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Label
          </label>
          <input
            type="text"
            value={label}
            onChange={(e) => setLabel(e.target.value)}
            maxLength={64}
            placeholder="On my way"
            className="w-full bg-background border border-surface-light rounded px-3 py-2 text-text focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">
            Reply text
          </label>
          <textarea
            value={body}
            onChange={(e) => setBody(e.target.value)}
            maxLength={2000}
            rows={3}
            placeholder="Hi! I'm on my way and should be there in 10 minutes."
            className="w-full bg-background border border-surface-light rounded px-3 py-2 text-text focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
        <div className="flex gap-2">
          <button
            type="submit"
            disabled={busy}
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded text-sm font-semibold disabled:opacity-50"
          >
            {editingId !== null ? "Update reply" : "Add reply"}
          </button>
          {editingId !== null && (
            <button
              type="button"
              onClick={cancelEdit}
              className="bg-surface-light hover:bg-surface text-text-muted px-4 py-2 rounded text-sm"
            >
              Cancel
            </button>
          )}
        </div>
      </form>

      <section>
        {loading ? (
          <p className="text-text-muted text-sm">Loading…</p>
        ) : replies.length === 0 ? (
          <p className="text-text-muted text-sm">
            No saved replies yet. Add one above to get started.
          </p>
        ) : (
          <ul className="space-y-2">
            {replies.map((reply) => (
              <li
                key={reply.id}
                className="bg-surface rounded p-3 flex items-start justify-between gap-3"
              >
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-text truncate">{reply.label}</p>
                  <p className="text-sm text-text-muted whitespace-pre-wrap mt-1">
                    {reply.body}
                  </p>
                </div>
                <div className="flex gap-2 flex-shrink-0">
                  <button
                    type="button"
                    onClick={() => startEdit(reply)}
                    className="text-xs text-primary hover:text-primary-dark"
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    onClick={() => handleDelete(reply.id)}
                    className="text-xs text-red-400 hover:text-red-300"
                  >
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
