import { useState, useEffect } from "react";
import { useNavigate, useParams } 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 labelStyle = {
  display: "block",
  marginBottom: 4,
  fontSize: 12,
  color: "var(--text-secondary)",
  fontWeight: 500,
};

function ReadField({ label, value }) {
  return (
    <div>
      <div style={labelStyle}>{label}</div>
      <div className="text-sm" style={{ color: "var(--text-primary)" }}>
        {value || <span style={{ color: "var(--text-muted)" }}>—</span>}
      </div>
    </div>
  );
}

function SectionCard({ title, children }) {
  return (
    <div className="ui-section-card mb-4">
      <h2 className="ui-section-card__header-title mb-4">{title}</h2>
      {children}
    </div>
  );
}

export default function OrderDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("crm", "edit");

  const [order, setOrder] = useState(null);
  const [customer, setCustomer] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    api.get(`/crm/orders/${id}`)
      .then((data) => {
        setOrder(data);
        if (data.customer_id) {
          api.get(`/crm/customers/${data.customer_id}`)
            .then(setCustomer)
            .catch(() => {});
        }
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) {
    return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  }
  if (error) {
    return (
      <div className="text-sm rounded-md p-3 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
        {error}
      </div>
    );
  }
  if (!order) return null;

  const statusStyle = STATUS_COLORS[order.status] || STATUS_COLORS.draft;
  const payStyle = PAYMENT_COLORS[order.payment_status] || PAYMENT_COLORS.pending;
  const shipping = order.shipping || {};

  const subtotal = (order.items || []).reduce((sum, item) => {
    return sum + (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
  }, 0);

  const discount = order.discount || {};
  const discountAmount =
    discount.type === "percentage"
      ? subtotal * ((Number(discount.value) || 0) / 100)
      : Number(discount.value) || 0;

  const total = Number(order.total_price || 0);

  return (
    <div style={{ maxWidth: 900 }}>
      {/* Header */}
      <div className="flex items-start justify-between mb-6">
        <div>
          <div className="flex items-center gap-3 mb-1">
            <h1 className="text-2xl font-bold font-mono" style={{ color: "var(--text-heading)" }}>
              {order.order_number}
            </h1>
            <span
              className="px-2 py-0.5 text-xs rounded-full capitalize"
              style={{ backgroundColor: statusStyle.bg, color: statusStyle.color }}
            >
              {(order.status || "draft").replace("_", " ")}
            </span>
          </div>
          {customer ? (
            <button
              onClick={() => navigate(`/crm/customers/${customer.id}`)}
              className="text-sm hover:underline"
              style={{ color: "var(--accent)", background: "none", border: "none", cursor: "pointer", padding: 0 }}
            >
              {customer.organization ? `${customer.name} / ${customer.organization}` : customer.name} ↗
            </button>
          ) : (
            <span className="text-sm" style={{ color: "var(--text-muted)" }}>{order.customer_id}</span>
          )}
          <p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
            Created {order.created_at ? new Date(order.created_at).toLocaleDateString() : "—"}
            {order.updated_at && order.updated_at !== order.created_at && (
              <span> · Updated {new Date(order.updated_at).toLocaleDateString()}</span>
            )}
          </p>
        </div>
        <div className="flex gap-2">
          {customer && (
            <button
              onClick={() => navigate(`/crm/customers/${customer.id}`)}
              className="px-3 py-1.5 text-sm rounded-md border cursor-pointer hover:opacity-80"
              style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
            >
              Back to Customer
            </button>
          )}
          {canEdit && (
            <button
              onClick={() => navigate(`/crm/orders/${id}/edit`)}
              className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              Edit
            </button>
          )}
        </div>
      </div>

      {/* Items */}
      <SectionCard title="Items">
        {(order.items || []).length === 0 ? (
          <p className="text-sm" style={{ color: "var(--text-muted)" }}>No items.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr style={{ borderBottom: "1px solid var(--border-primary)" }}>
                  <th className="pb-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Item</th>
                  <th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Qty</th>
                  <th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Unit Price</th>
                  <th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Line Total</th>
                </tr>
              </thead>
              <tbody>
                {order.items.map((item, idx) => {
                  const lineTotal = (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
                  const label =
                    item.type === "product"
                      ? item.product_name || item.product_id || "Product"
                      : item.type === "console_device"
                      ? `${item.device_id || ""}${item.label ? ` (${item.label})` : ""}`
                      : item.description || "—";

                  return (
                    <tr
                      key={idx}
                      style={{ borderBottom: idx < order.items.length - 1 ? "1px solid var(--border-secondary)" : "none" }}
                    >
                      <td className="py-2 pr-4">
                        <span style={{ color: "var(--text-primary)" }}>{label}</span>
                        <span className="ml-2 text-xs px-1.5 py-0.5 rounded-full" style={{ backgroundColor: "var(--bg-primary)", color: "var(--text-muted)" }}>
                          {item.type.replace("_", " ")}
                        </span>
                        {Array.isArray(item.serial_numbers) && item.serial_numbers.length > 0 && (
                          <div className="text-xs mt-0.5 font-mono" style={{ color: "var(--text-muted)" }}>
                            SN: {item.serial_numbers.join(", ")}
                          </div>
                        )}
                      </td>
                      <td className="py-2 text-right" style={{ color: "var(--text-primary)" }}>{item.quantity}</td>
                      <td className="py-2 text-right" style={{ color: "var(--text-primary)" }}>
                        {order.currency} {Number(item.unit_price || 0).toFixed(2)}
                      </td>
                      <td className="py-2 text-right font-medium" style={{ color: "var(--text-heading)" }}>
                        {order.currency} {lineTotal.toFixed(2)}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>

      {/* Pricing Summary */}
      <SectionCard title="Pricing">
        <div style={{ display: "flex", flexDirection: "column", gap: 8, maxWidth: 300, marginLeft: "auto" }}>
          <div className="flex justify-between text-sm">
            <span style={{ color: "var(--text-secondary)" }}>Subtotal</span>
            <span style={{ color: "var(--text-primary)" }}>{order.currency} {subtotal.toFixed(2)}</span>
          </div>
          {discountAmount > 0 && (
            <div className="flex justify-between text-sm">
              <span style={{ color: "var(--text-secondary)" }}>
                Discount
                {discount.type === "percentage" && ` (${discount.value}%)`}
                {discount.reason && ` — ${discount.reason}`}
              </span>
              <span style={{ color: "var(--danger-text)" }}>−{order.currency} {discountAmount.toFixed(2)}</span>
            </div>
          )}
          <div
            className="flex justify-between text-sm font-semibold pt-2"
            style={{ borderTop: "1px solid var(--border-primary)" }}
          >
            <span style={{ color: "var(--text-heading)" }}>Total</span>
            <span style={{ color: "var(--text-heading)" }}>{order.currency} {total.toFixed(2)}</span>
          </div>
        </div>
      </SectionCard>

      {/* Payment */}
      <SectionCard title="Payment">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div>
            <div style={labelStyle}>Payment Status</div>
            <span
              className="px-2 py-0.5 text-xs rounded-full capitalize"
              style={{ backgroundColor: payStyle.bg, color: payStyle.color }}
            >
              {order.payment_status || "pending"}
            </span>
          </div>
          <div>
            <div style={labelStyle}>Invoice</div>
            {order.invoice_path ? (
              <span className="text-sm font-mono" style={{ color: "var(--text-primary)" }}>
                {order.invoice_path}
              </span>
            ) : (
              <span style={{ color: "var(--text-muted)", fontSize: 14 }}>—</span>
            )}
          </div>
        </div>
      </SectionCard>

      {/* Shipping */}
      <SectionCard title="Shipping">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
          <ReadField label="Method" value={shipping.method} />
          <ReadField label="Carrier" value={shipping.carrier} />
          <ReadField label="Tracking Number" value={shipping.tracking_number} />
          <ReadField label="Destination" value={shipping.destination} />
          <ReadField
            label="Shipped At"
            value={shipping.shipped_at ? new Date(shipping.shipped_at).toLocaleDateString() : null}
          />
          <ReadField
            label="Delivered At"
            value={shipping.delivered_at ? new Date(shipping.delivered_at).toLocaleDateString() : null}
          />
        </div>
      </SectionCard>

      {/* Notes */}
      {order.notes && (
        <SectionCard title="Notes">
          <p className="text-sm whitespace-pre-wrap" style={{ color: "var(--text-primary)" }}>{order.notes}</p>
        </SectionCard>
      )}
    </div>
  );
}
