"use client";

import { useState, useEffect } from "react";

interface ClientNoteProps {
  clientId: number;
}

export default function ClientNote({ clientId }: ClientNoteProps) {
  const [open, setOpen] = useState(false);
  const [note, setNote] = useState("");
  const [saving, setSaving] = useState(false);
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (open && !loaded) {
      fetch("/api/client-notes")
        .then((r) => r.json())
        .then((data) => {
          const existing = data.notes?.find(
            (n: { client_id: number }) => n.client_id === clientId
          );
          if (existing) setNote(existing.note);
          setLoaded(true);
        })
        .catch(() => setLoaded(true));
    }
  }, [open, loaded, clientId]);

  async function handleSave() {
    setSaving(true);
    try {
      await fetch("/api/client-notes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ client_id: clientId, note }),
      });
      setOpen(false);
    } catch {
      // handle silently
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="text-text-muted hover:text-gold transition-colors"
        title="Private notes about this client"
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
        </svg>
      </button>

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60">
          <div className="bg-surface rounded-lg p-6 w-full max-w-md mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-text">Private Note</h3>
              <button
                onClick={() => setOpen(false)}
                className="text-text-muted hover:text-text transition-colors"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <p className="text-text-muted text-sm mb-3">
              Add private notes about this client. Only you can see these.
            </p>
            <textarea
              rows={5}
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="Add your private notes here..."
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-3 text-text focus:outline-none focus:ring-2 focus:ring-primary resize-none"
            />
            <div className="flex justify-end gap-3 mt-4">
              <button
                onClick={() => setOpen(false)}
                className="px-4 py-2 text-text-muted hover:text-text text-sm transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={saving}
                className="bg-gold hover:bg-gold/90 text-black px-5 py-2 rounded-lg font-semibold text-sm transition-colors disabled:opacity-50"
              >
                {saving ? "Saving..." : "Save Note"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
