import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import api from "../../api/client";
import { useAuth } from "../../auth/AuthContext";

const CATEGORY_LABELS = {
  controller: "Controller",
  striker: "Striker",
  clock: "Clock",
  part: "Part",
  repair_service: "Repair / Service",
};

const CATEGORIES = Object.keys(CATEGORY_LABELS);

export default function ProductList() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [hoveredRow, setHoveredRow] = useState(null);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("crm", "edit");

  const fetchProducts = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (categoryFilter) params.set("category", categoryFilter);
      const qs = params.toString();
      const data = await api.get(`/crm/products${qs ? `?${qs}` : ""}`);
      setProducts(data.products);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, [categoryFilter]);

  const filtered = search
    ? products.filter(
        (p) =>
          (p.name || "").toLowerCase().includes(search.toLowerCase()) ||
          (p.sku || "").toLowerCase().includes(search.toLowerCase())
      )
    : products;

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          Product Catalog
        </h1>
        {canEdit && (
          <button
            onClick={() => navigate("/crm/products/new")}
            className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
            style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
          >
            New Product
          </button>
        )}
      </div>

      {/* Filters */}
      <div className="flex gap-3 mb-4">
        <input
          type="text"
          placeholder="Search by name or SKU..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="flex-1 px-3 py-2 text-sm rounded-md border"
          style={{
            backgroundColor: "var(--bg-input)",
            borderColor: "var(--border-primary)",
            color: "var(--text-primary)",
          }}
        />
        <select
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
          className="px-3 py-2 text-sm rounded-md border"
          style={{
            backgroundColor: "var(--bg-input)",
            borderColor: "var(--border-primary)",
            color: "var(--text-primary)",
          }}
        >
          <option value="">All Categories</option>
          {CATEGORIES.map((c) => (
            <option key={c} value={c}>{CATEGORY_LABELS[c]}</option>
          ))}
        </select>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : filtered.length === 0 ? (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
        >
          No products found.
        </div>
      ) : (
        <div
          className="rounded-lg overflow-hidden border"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
        >
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                  <th className="px-3 py-3" style={{ width: 48 }} />
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Name</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>SKU</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Category</th>
                  <th className="px-4 py-3 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Price</th>
                  <th className="px-4 py-3 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Mfg. Cost</th>
                  <th className="px-4 py-3 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Margin</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Stock</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((p, index) => {
                  const price = p.price != null ? Number(p.price) : null;
                  const mfgCost = p.costs?.total != null ? Number(p.costs.total) : null;
                  const margin = price != null && mfgCost != null ? price - mfgCost : null;
                  return (
                  <tr
                    key={p.id}
                    onClick={() => navigate(`/crm/products/${p.id}`)}
                    className="cursor-pointer"
                    style={{
                      borderBottom: index < filtered.length - 1 ? "1px solid var(--border-primary)" : "none",
                      backgroundColor: hoveredRow === p.id ? "var(--bg-card-hover)" : index % 2 === 1 ? "var(--bg-row-alt)" : "transparent",
                    }}
                    onMouseEnter={() => setHoveredRow(p.id)}
                    onMouseLeave={() => setHoveredRow(null)}
                  >
                    <td className="px-3 py-2" style={{ width: 48 }}>
                      {p.photo_url ? (
                        <img
                          src={`/api${p.photo_url}`}
                          alt=""
                          style={{ width: 40, height: 40, borderRadius: 6, objectFit: "contain", border: "1px solid var(--border-primary)" }}
                        />
                      ) : (
                        <div style={{ width: 40, height: 40, borderRadius: 6, backgroundColor: "var(--bg-card-hover)", border: "1px solid var(--border-primary)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                          <span style={{ fontSize: 18, opacity: 0.4 }}>📦</span>
                        </div>
                      )}
                    </td>
                    <td className="px-4 py-3 font-medium" style={{ color: "var(--text-heading)" }}>{p.name}</td>
                    <td className="px-4 py-3 font-mono text-xs" style={{ color: "var(--text-muted)" }}>{p.sku || "—"}</td>
                    <td className="px-4 py-3">
                      <span
                        className="px-2 py-0.5 text-xs rounded-full"
                        style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-secondary)" }}
                      >
                        {CATEGORY_LABELS[p.category] || p.category}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-right" style={{ color: "var(--text-primary)" }}>
                      {price != null ? `€${price.toFixed(2)}` : "—"}
                    </td>
                    <td className="px-4 py-3 text-right" style={{ color: "var(--text-muted)" }}>
                      {mfgCost != null ? `€${mfgCost.toFixed(2)}` : "—"}
                    </td>
                    <td className="px-4 py-3 text-right" style={{ color: margin != null ? (margin >= 0 ? "var(--success-text)" : "var(--danger-text)") : "var(--text-muted)" }}>
                      {margin != null ? `€${margin.toFixed(2)}` : "—"}
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                      {p.stock ? p.stock.available : "—"}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className="px-2 py-0.5 text-xs rounded-full"
                        style={
                          p.active
                            ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                            : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
                        }
                      >
                        {p.active ? "Active" : "Inactive"}
                      </span>
                    </td>
                  </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
