File size: 1,880 Bytes
7d51e81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"use client";

import { useState } from "react";
import { FiTrash2 } from "react-icons/fi";
import "./styles/DeleteButton.css";

export default function DeleteTopicButton({ usn, subject, topic, onDelete }) {
  const [confirming, setConfirming] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleDelete = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/topic/delete", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ usn, subject, topic }),
      });

      const data = await res.json();

      if (!res.ok) {
        alert(data.error || "Failed to delete topic");
      } else {
        if (onDelete) onDelete(data.subjects); // parent gets updated subjects
      }
    } catch (err) {
      console.error(err);
      alert("Error deleting topic");
    } finally {
      setLoading(false);
      setConfirming(false);
    }
  };

  return (
    <div className="delete-button-container">

      {!confirming ? (

        <button

          className="delete-btn"

          onClick={() => setConfirming(true)}

          disabled={loading}

        >

          <FiTrash2 size={18} />

        </button>

      ) : (

        <div className="confirm-box">

          <p>Delete topic?</p>

          <div className="confirm-actions">

            <button

              className="confirm-yes"

              onClick={handleDelete}

              disabled={loading}

            >

              {loading ? "..." : "Yes"}

            </button>

            <button

              className="confirm-no"

              onClick={() => setConfirming(false)}

              disabled={loading}

            >

              No

            </button>

          </div>

        </div>

      )}

    </div>
  );
}