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

const ORDER_STATUS_LABELS = {
  negotiating: "Negotiating",
  awaiting_quotation: "Awaiting Quotation",
  awaiting_customer_confirmation: "Awaiting Confirmation",
  awaiting_fulfilment: "Awaiting Fulfilment",
  awaiting_payment: "Awaiting Payment",
  manufacturing: "Manufacturing",
  shipped: "Shipped",
  installed: "Installed",
  declined: "Declined",
  complete: "Complete",
};

const ORDER_STATUSES = Object.keys(ORDER_STATUS_LABELS);

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

export default function OrderList() {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [hoveredRow, setHoveredRow] = useState(null);
  const navigate = useNavigate();

  const fetchOrders = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (statusFilter) params.set("status", statusFilter);
      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]);

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Orders</h1>
      </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}>{ORDER_STATUS_LABELS[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)" }}>Title</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)" }}>Date</th>
                </tr>
              </thead>
              <tbody>
                {orders.map((o, index) => {
                  const statusLabel = ORDER_STATUS_LABELS[o.status] || o.status || "—";
                  const customerName = o.customer_name || o.customer_id || "—";

                  return (
                    <tr
                      key={o.id}
                      onClick={() => navigate(`/crm/customers/${o.customer_id}?tab=Orders`)}
                      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 text-xs" style={{ color: "var(--text-muted)" }}>
                        {o.title || <span style={{ fontStyle: "italic" }}>Untitled</span>}
                      </td>
                      <td className="px-4 py-3">
                        <span className="px-2 py-0.5 text-xs rounded-full"
                          style={{
                            backgroundColor: `var(--crm-ord-${o.status}-bg, var(--bg-card-hover))`,
                            color: `var(--crm-ord-${o.status}-text, var(--text-secondary))`,
                          }}>
                          {statusLabel}
                        </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>
  );
}
