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

const STATUS_COLORS = {
  draft:         { bg: "var(--bg-card-hover)",    color: "var(--text-secondary)" },
  confirmed:     { bg: "var(--badge-blue-bg)",    color: "var(--badge-blue-text)" },
  in_production: { bg: "#fff7ed",                 color: "#9a3412" },
  shipped:       { bg: "#f5f3ff",                 color: "#6d28d9" },
  delivered:     { bg: "var(--success-bg)",       color: "var(--success-text)" },
  cancelled:     { bg: "var(--danger-bg)",        color: "var(--danger-text)" },
};

const PAYMENT_COLORS = {
  pending: { bg: "#fef9c3", color: "#854d0e" },
  partial: { bg: "#fff7ed", color: "#9a3412" },
  paid:    { bg: "var(--success-bg)", color: "var(--success-text)" },
};

const inputStyle = {
  backgroundColor: "var(--bg-input)",
  borderColor: "var(--border-primary)",
  color: "var(--text-primary)",
};

const ORDER_STATUSES = ["draft", "confirmed", "in_production", "shipped", "delivered", "cancelled"];
const PAYMENT_STATUSES = ["pending", "partial", "paid"];

export default function OrderList() {
  const [orders, setOrders] = useState([]);
  const [customerMap, setCustomerMap] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [paymentFilter, setPaymentFilter] = useState("");
  const [hoveredRow, setHoveredRow] = useState(null);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("crm", "edit");

  useEffect(() => {
    api.get("/crm/customers")
      .then((data) => {
        const map = {};
        (data.customers || []).forEach((c) => { map[c.id] = c; });
        setCustomerMap(map);
      })
      .catch(() => {});
  }, []);

  const fetchOrders = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (statusFilter) params.set("status", statusFilter);
      if (paymentFilter) params.set("payment_status", paymentFilter);
      const qs = params.toString();
      const data = await api.get(`/crm/orders${qs ? `?${qs}` : ""}`);
      setOrders(data.orders || []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, [statusFilter, paymentFilter]);

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Orders Manager</h1>
        {canEdit && (
          <button
            onClick={() => navigate("/crm/orders/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 Order
          </button>
        )}
      </div>

      <div className="flex gap-3 mb-4">
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-3 py-2 text-sm rounded-md border"
          style={inputStyle}
        >
          <option value="">All Statuses</option>
          {ORDER_STATUSES.map((s) => (
            <option key={s} value={s}>{s.replace("_", " ")}</option>
          ))}
        </select>
        <select
          value={paymentFilter}
          onChange={(e) => setPaymentFilter(e.target.value)}
          className="px-3 py-2 text-sm rounded-md border"
          style={inputStyle}
        >
          <option value="">All Payment Statuses</option>
          {PAYMENT_STATUSES.map((s) => (
            <option key={s} value={s}>{s}</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>
      ) : orders.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 orders 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-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Order #</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Customer</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Total</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Payment</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Date</th>
                </tr>
              </thead>
              <tbody>
                {orders.map((o, index) => {
                  const statusStyle = STATUS_COLORS[o.status] || STATUS_COLORS.draft;
                  const payStyle = PAYMENT_COLORS[o.payment_status] || PAYMENT_COLORS.pending;
                  const customer = customerMap[o.customer_id];
                  const customerName = customer
                    ? customer.organization
                      ? `${customer.name} / ${customer.organization}`
                      : customer.name
                    : o.customer_id || "—";

                  return (
                    <tr
                      key={o.id}
                      onClick={() => navigate(`/crm/orders/${o.id}`)}
                      className="cursor-pointer"
                      style={{
                        borderBottom: index < orders.length - 1 ? "1px solid var(--border-secondary)" : "none",
                        backgroundColor: hoveredRow === o.id ? "var(--bg-card-hover)" : index % 2 === 1 ? "var(--bg-row-alt)" : "transparent",
                      }}
                      onMouseEnter={() => setHoveredRow(o.id)}
                      onMouseLeave={() => setHoveredRow(null)}
                    >
                      <td className="px-4 py-3 font-mono text-xs font-medium" style={{ color: "var(--text-heading)" }}>
                        {o.order_number}
                      </td>
                      <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{customerName}</td>
                      <td className="px-4 py-3">
                        <span
                          className="px-2 py-0.5 text-xs rounded-full capitalize"
                          style={{ backgroundColor: statusStyle.bg, color: statusStyle.color }}
                        >
                          {(o.status || "draft").replace("_", " ")}
                        </span>
                      </td>
                      <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                        {o.currency || "EUR"} {Number(o.total_price || 0).toFixed(2)}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className="px-2 py-0.5 text-xs rounded-full capitalize"
                          style={{ backgroundColor: payStyle.bg, color: payStyle.color }}
                        >
                          {o.payment_status || "pending"}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                        {o.created_at ? new Date(o.created_at).toLocaleDateString() : "—"}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
