import { useState, useCallback } from "react";
import type { ShoppingListItem } from "@/lib/types";
import {
  getShoppingList,
  saveShoppingList,
} 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 ShoppingList() {
  const [list, setList] = useState<ShoppingListItem[]>(() => getShoppingList());

  const save = useCallback((next: ShoppingListItem[]) => {
    setList(next);
    saveShoppingList(next);
  }, []);

  const togglePurchased = (idx: number) => {
    const next = [...list];
    next[idx] = { ...next[idx], purchased: !next[idx].purchased };
    save(next);
  };

  const remove = (idx: number) => {
    const next = list.filter((_, i) => i !== idx);
    save(next);
  };

  const clearPurchased = () => {
    save(list.filter((x) => !x.purchased));
    showToast("Purchased items cleared");
  };

  const clearAll = () => {
    if (list.length === 0) return;
    save([]);
    showToast("Shopping list cleared");
  };

  const unpurchased = list.filter((x) => !x.purchased);
  const total = unpurchased.reduce((s, x) => s + x.price, 0);

  if (list.length === 0) {
    return (
      <div className="empty">
        <div className="empty-icon">🛒</div>
        <p>
          Your shopping list is empty.
          <br />
          Search for products and add them here.
        </p>
      </div>
    );
  }

  return (
    <div>
      <div style={{ display: "flex", gap: "8px", marginBottom: "16px" }}>
        <button className="btn btn-secondary btn-sm" onClick={clearPurchased}>
          Clear Purchased
        </button>
        <button className="btn btn-danger btn-sm" onClick={clearAll}>
          Clear All
        </button>
      </div>

      {list.map((item, i) => (
        <div
          key={item.id}
          style={{
            display: "flex",
            alignItems: "center",
            gap: "12px",
            padding: "14px 16px",
            background: "var(--surface)",
            border: "1px solid var(--border)",
            borderRadius: "var(--radius-sm)",
            marginBottom: "8px",
            opacity: item.purchased ? 0.5 : 1,
          }}
        >
          <div
            onClick={() => togglePurchased(i)}
            style={{
              width: "20px",
              height: "20px",
              borderRadius: "6px",
              border: item.purchased
                ? "2px solid var(--green)"
                : "2px solid var(--border)",
              background: item.purchased ? "var(--green)" : "transparent",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
              fontSize: "0.7rem",
              fontWeight: 700,
              color: "#0f1117",
            }}
          >
            {item.purchased && "✓"}
          </div>
          <span
            style={{
              flex: 1,
              fontSize: "0.9rem",
              textDecoration: item.purchased ? "line-through" : "none",
            }}
          >
            {item.name}
            <br />
            <small style={{ color: "var(--text3)" }}>{item.store}</small>
          </span>
          <span
            style={{
              color: "var(--green)",
              fontWeight: 700,
              fontSize: "0.9rem",
            }}
          >
            ${item.price.toFixed(2)}
          </span>
          <span
            onClick={() => remove(i)}
            style={{
              color: "var(--text3)",
              fontSize: "1.2rem",
              cursor: "pointer",
              padding: "0 4px",
            }}
          >
            ×
          </span>
        </div>
      ))}

      <div
        style={{
          textAlign: "right",
          padding: "16px",
          background: "var(--surface)",
          borderRadius: "var(--radius-sm)",
          marginTop: "8px",
          fontSize: "0.95rem",
          color: "var(--text2)",
        }}
      >
        Remaining: {unpurchased.length} item
        {unpurchased.length !== 1 ? "s" : ""} —{" "}
        <strong style={{ color: "var(--green)", fontSize: "1.1rem" }}>
          ${total.toFixed(2)}
        </strong>
      </div>
    </div>
  );
}
