import { useState } from "react";
import type { PriceAlert } from "@/lib/types";
import { getAlerts, saveAlerts } from "@/lib/storage";

function showToast(msg: string) {
  const t = document.getElementById("toast");
  if (!t) return;
  t.textContent = msg;
  t.className = "toast success";
  setTimeout(() => t.classList.add("show"), 10);
  setTimeout(() => t.classList.remove("show"), 2500);
}

export default function AlertsPanel() {
  const [alerts, setAlerts] = useState<PriceAlert[]>(() => getAlerts());

  const remove = (idx: number) => {
    const next = alerts.filter((_, i) => i !== idx);
    setAlerts(next);
    saveAlerts(next);
    showToast("Alert removed");
  };

  if (alerts.length === 0) {
    return (
      <div className="empty">
        <div className="empty-icon">🔔</div>
        <p>
          No price alerts set.
          <br />
          Set alerts on products to track price drops.
        </p>
      </div>
    );
  }

  return (
    <div>
      {alerts.map((a, i) => (
        <div
          key={a.id}
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "14px 16px",
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--radius-sm)",
            marginBottom: "8px",
          }}
        >
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: "0.9rem", fontWeight: 600 }}>{a.name}</div>
            <div style={{ color: "var(--green)", fontSize: "0.85rem" }}>
              Watching at ${a.price.toFixed(2)} ({a.store})
            </div>
          </div>
          <button className="btn btn-danger btn-sm" onClick={() => remove(i)}>
            Remove
          </button>
        </div>
      ))}
    </div>
  );
}
