import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { MessageSquare, ChevronDown, ChevronUp } from "lucide-react";
import NotesList from "./NotesList";
import AddNoteForm from "./AddNoteForm";
import { buildUrl } from "@/libs/url";

/**
 * Subscription Notes Panel Component
 *
 * Main container for managing subscription notes in the admin detail page.
 *
 * @param {Object} props Component props
 * @param {number} props.subscriptionId The subscription ID
 * @param {boolean} props.compact If true, hides the header (used when wrapped in detail-card)
 */
const NotesPanel = ({ subscriptionId, compact = false }) => {
  const [notes, setNotes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [addingNote, setAddingNote] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const [error, setError] = useState(null);
  const { env } = window.arraySubs;

  /**
   * Fetch notes from API
   */
  const fetchNotes = useCallback(async () => {
    if (!subscriptionId) return;

    setLoading(true);
    setError(null);

    try {
      const url = buildUrl(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/notes`,
        { type: "all", per_page: 100 },
      );

      const response = await fetch(url, {
        headers: { "X-WP-Nonce": env.nonce },
      });

      if (!response.ok) {
        throw new Error(__("Failed to fetch notes", "arraysubs"));
      }

      const result = await response.json();
      setNotes(result.content?.notes || []);
    } catch (err) {
      console.error("Error fetching notes:", err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [subscriptionId, env.apiBaseUrl, env.nonce]);

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

  /**
   * Handle adding a new note
   */
  const handleAddNote = async ({ content, type }) => {
    setAddingNote(true);
    setError(null);

    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/notes`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({ content, type }),
        },
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(
          errorData.message || __("Failed to add note", "arraysubs"),
        );
      }

      const result = await response.json();

      // Add new note to the beginning of the list
      if (result.content?.note) {
        setNotes((prevNotes) => [result.content.note, ...prevNotes]);
      }

      return true;
    } catch (err) {
      console.error("Error adding note:", err);
      setError(err.message);
      return false;
    } finally {
      setAddingNote(false);
    }
  };

  /**
   * Handle deleting a note
   */
  const handleDeleteNote = async (noteId) => {
    if (
      !confirm(__("Are you sure you want to delete this note?", "arraysubs"))
    ) {
      return;
    }

    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${subscriptionId}/notes/${noteId}`,
        {
          method: "DELETE",
          headers: { "X-WP-Nonce": env.nonce },
        },
      );

      if (!response.ok) {
        throw new Error(__("Failed to delete note", "arraysubs"));
      }

      // Remove note from list
      setNotes((prevNotes) => prevNotes.filter((note) => note.id !== noteId));
    } catch (err) {
      console.error("Error deleting note:", err);
      setError(err.message);
    }
  };

  return (
    <div
      className={`arraysubs-notes-panel${
        compact ? " arraysubs-notes-panel--compact" : ""
      }`}
    >
      {!compact && (
        <div
          className="arraysubs-notes-panel__header"
          onClick={() => setCollapsed(!collapsed)}
        >
          <div className="arraysubs-notes-panel__title">
            <MessageSquare size={20} />
            <h3>{__("Subscription Notes", "arraysubs")}</h3>
            <span className="arraysubs-notes-panel__count">
              ({notes.length})
            </span>
          </div>
          <button
            type="button"
            className="arraysubs-notes-panel__toggle"
            aria-expanded={!collapsed}
          >
            {collapsed ? <ChevronDown size={20} /> : <ChevronUp size={20} />}
          </button>
        </div>
      )}

      {(compact || !collapsed) && (
        <div className="arraysubs-notes-panel__body">
          {error && <div className="arraysubs-notes-panel__error">{error}</div>}

          <NotesList
            notes={notes}
            loading={loading}
            onDelete={handleDeleteNote}
          />

          <AddNoteForm onAdd={handleAddNote} loading={addingNote} />
        </div>
      )}
    </div>
  );
};

export default NotesPanel;
