"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";

type Note = { id: string; body: string; created_at: string };

export function NotesList({
  initialNotes,
  userId,
}: {
  initialNotes: Note[];
  userId: string;
}) {
  const [notes, setNotes] = useState<Note[]>(initialNotes);
  const [body, setBody] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const supabase = createClient();

  async function addNote() {
    if (!body.trim()) return;
    setLoading(true);
    setError("");

    const { data, error } = await supabase
      .from("notes")
      .insert({ body: body.trim(), user_id: userId })
      .select("id, body, created_at")
      .single();

    if (error) { setError(error.message); setLoading(false); return; }
    setNotes([data, ...notes]);
    setBody("");
    setLoading(false);
  }

  async function deleteNote(id: string) {
    const { error } = await supabase.from("notes").delete().eq("id", id);
    if (error) { setError(error.message); return; }
    setNotes(notes.filter(n => n.id !== id));
  }

  function fmt(ts: string) {
    return new Date(ts).toLocaleString("en-KE", {
      dateStyle: "medium",
      timeStyle: "short",
    });
  }

  return (
    <>
      {error && <div className="error-msg">{error}</div>}

      <div className="note-form">
        <textarea
          value={body}
          onChange={e => setBody(e.target.value)}
          placeholder="Write a note…"
          onKeyDown={e => e.key === "Enter" && e.metaKey && addNote()}
        />
        <button
          className="btn btn-primary"
          onClick={addNote}
          disabled={loading || !body.trim()}
        >
          {loading ? "Saving…" : "Add note"}
        </button>
      </div>

      <div className="notes-list">
        {notes.length === 0 ? (
          <div className="empty-state">
            No notes yet. Add one above to verify the DB write path.
          </div>
        ) : (
          notes.map(note => (
            <div key={note.id} className="note-item">
              <div>
                <p className="note-body">{note.body}</p>
                <p className="note-time">{fmt(note.created_at)}</p>
              </div>
              <button
                className="btn btn-danger"
                onClick={() => deleteNote(note.id)}
              >
                Delete
              </button>
            </div>
          ))
        )}
      </div>
    </>
  );
}
