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

const ORDER_STATUSES = ["draft", "confirmed", "in_production", "shipped", "delivered", "cancelled"];
const PAYMENT_STATUSES = ["pending", "partial", "paid"];
const CURRENCIES = ["EUR", "USD", "GBP"];
const ITEM_TYPES = ["product", "console_device", "freetext"];

const inputClass = "w-full px-3 py-2 text-sm rounded-md border";
const inputStyle = {
  backgroundColor: "var(--bg-input)",
  borderColor: "var(--border-primary)",
  color: "var(--text-primary)",
};
const labelStyle = {
  display: "block",
  marginBottom: 4,
  fontSize: 12,
  color: "var(--text-secondary)",
  fontWeight: 500,
};

function Field({ label, children, style }) {
  return (
    <div style={style}>
      <label style={labelStyle}>{label}</label>
      {children}
    </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>
  );
}

const emptyItem = () => ({
  type: "product",
  product_id: "",
  product_name: "",
  description: "",
  device_id: "",
  label: "",
  quantity: 1,
  unit_price: 0,
  serial_numbers: "",
});

export default function OrderForm() {
  const { id } = useParams();
  const isEdit = Boolean(id);
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("crm", "edit");

  const [form, setForm] = useState({
    customer_id: searchParams.get("customer_id") || "",
    order_number: "",
    status: "draft",
    currency: "EUR",
    items: [],
    discount: { type: "percentage", value: 0, reason: "" },
    payment_status: "pending",
    invoice_path: "",
    shipping: {
      method: "",
      carrier: "",
      tracking_number: "",
      destination: "",
      shipped_at: "",
      delivered_at: "",
    },
    notes: "",
  });

  const [customers, setCustomers] = useState([]);
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(isEdit);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const [customerSearch, setCustomerSearch] = useState("");
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);

  // Load customers and products
  useEffect(() => {
    api.get("/crm/customers").then((d) => setCustomers(d.customers || [])).catch(() => {});
    api.get("/crm/products").then((d) => setProducts(d.products || [])).catch(() => {});
  }, []);

  // Load order for edit
  useEffect(() => {
    if (!isEdit) return;
    api.get(`/crm/orders/${id}`)
      .then((data) => {
        const shipping = data.shipping || {};
        setForm({
          customer_id: data.customer_id || "",
          order_number: data.order_number || "",
          status: data.status || "draft",
          currency: data.currency || "EUR",
          items: (data.items || []).map((item) => ({
            ...emptyItem(),
            ...item,
            serial_numbers: Array.isArray(item.serial_numbers)
              ? item.serial_numbers.join(", ")
              : item.serial_numbers || "",
          })),
          discount: data.discount || { type: "percentage", value: 0, reason: "" },
          payment_status: data.payment_status || "pending",
          invoice_path: data.invoice_path || "",
          shipping: {
            method: shipping.method || "",
            carrier: shipping.carrier || "",
            tracking_number: shipping.tracking_number || "",
            destination: shipping.destination || "",
            shipped_at: shipping.shipped_at ? shipping.shipped_at.slice(0, 10) : "",
            delivered_at: shipping.delivered_at ? shipping.delivered_at.slice(0, 10) : "",
          },
          notes: data.notes || "",
        });
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, [id, isEdit]);

  // Set customer search label when customer_id loads
  useEffect(() => {
    if (form.customer_id && customers.length > 0) {
      const c = customers.find((x) => x.id === form.customer_id);
      if (c) setCustomerSearch(c.organization ? `${c.name} / ${c.organization}` : c.name);
    }
  }, [form.customer_id, customers]);

  const setField = (key, value) => setForm((f) => ({ ...f, [key]: value }));
  const setShipping = (key, value) => setForm((f) => ({ ...f, shipping: { ...f.shipping, [key]: value } }));
  const setDiscount = (key, value) => setForm((f) => ({ ...f, discount: { ...f.discount, [key]: value } }));

  const addItem = () => setForm((f) => ({ ...f, items: [...f.items, emptyItem()] }));
  const removeItem = (idx) => setForm((f) => ({ ...f, items: f.items.filter((_, i) => i !== idx) }));
  const setItem = (idx, key, value) =>
    setForm((f) => ({
      ...f,
      items: f.items.map((item, i) => (i === idx ? { ...item, [key]: value } : item)),
    }));

  const onProductSelect = (idx, productId) => {
    const product = products.find((p) => p.id === productId);
    setForm((f) => ({
      ...f,
      items: f.items.map((item, i) =>
        i === idx
          ? { ...item, product_id: productId, product_name: product?.name || "", unit_price: product?.price || 0 }
          : item
      ),
    }));
  };

  // Computed pricing
  const subtotal = form.items.reduce((sum, item) => {
    return sum + (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
  }, 0);

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

  const total = Math.max(0, subtotal - discountAmount);

  const filteredCustomers = customerSearch
    ? customers.filter((c) => {
        const q = customerSearch.toLowerCase();
        return c.name.toLowerCase().includes(q) || (c.organization || "").toLowerCase().includes(q);
      })
    : customers.slice(0, 20);

  const handleSave = async () => {
    if (!form.customer_id) { setError("Please select a customer."); return; }
    setSaving(true);
    setError("");
    try {
      const payload = {
        customer_id: form.customer_id,
        order_number: form.order_number || undefined,
        status: form.status,
        currency: form.currency,
        items: form.items.map((item) => ({
          type: item.type,
          product_id: item.product_id || null,
          product_name: item.product_name || null,
          description: item.description || null,
          device_id: item.device_id || null,
          label: item.label || null,
          quantity: Number(item.quantity) || 1,
          unit_price: Number(item.unit_price) || 0,
          serial_numbers: item.serial_numbers
            ? item.serial_numbers.split(",").map((s) => s.trim()).filter(Boolean)
            : [],
        })),
        subtotal,
        discount: {
          type: form.discount.type,
          value: Number(form.discount.value) || 0,
          reason: form.discount.reason || "",
        },
        total_price: total,
        payment_status: form.payment_status,
        invoice_path: form.invoice_path || "",
        shipping: {
          method: form.shipping.method || "",
          carrier: form.shipping.carrier || "",
          tracking_number: form.shipping.tracking_number || "",
          destination: form.shipping.destination || "",
          shipped_at: form.shipping.shipped_at || null,
          delivered_at: form.shipping.delivered_at || null,
        },
        notes: form.notes || "",
      };

      if (isEdit) {
        await api.put(`/crm/orders/${id}`, payload);
        navigate(`/crm/orders/${id}`);
      } else {
        const result = await api.post("/crm/orders", payload);
        navigate(`/crm/orders/${result.id}`);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!window.confirm("Delete this order? This cannot be undone.")) return;
    try {
      await api.delete(`/crm/orders/${id}`);
      navigate("/crm/orders");
    } catch (err) {
      setError(err.message);
    }
  };

  if (loading) {
    return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
  }

  if (!canEdit) {
    return <div className="text-sm p-3" style={{ color: "var(--danger-text)" }}>No permission to edit orders.</div>;
  }

  return (
    <div style={{ maxWidth: 900 }}>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
          {isEdit ? "Edit Order" : "New Order"}
        </h1>
        <button
          onClick={() => navigate(isEdit ? `/crm/orders/${id}` : "/crm/orders")}
          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)" }}
        >
          Cancel
        </button>
      </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>
      )}

      {/* 1. Customer */}
      <SectionCard title="Customer">
        <div style={{ position: "relative" }}>
          <label style={labelStyle}>Customer *</label>
          <input
            className={inputClass}
            style={inputStyle}
            placeholder="Search by name or organization..."
            value={customerSearch}
            onChange={(e) => {
              setCustomerSearch(e.target.value);
              setShowCustomerDropdown(true);
              if (!e.target.value) setField("customer_id", "");
            }}
            onFocus={() => setShowCustomerDropdown(true)}
            onBlur={() => setTimeout(() => setShowCustomerDropdown(false), 150)}
          />
          {showCustomerDropdown && filteredCustomers.length > 0 && (
            <div
              className="absolute z-10 w-full mt-1 rounded-md border shadow-lg"
              style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", maxHeight: 200, overflowY: "auto" }}
            >
              {filteredCustomers.map((c) => (
                <div
                  key={c.id}
                  className="px-3 py-2 text-sm cursor-pointer hover:opacity-80"
                  style={{ color: "var(--text-primary)", borderBottom: "1px solid var(--border-secondary)" }}
                  onMouseDown={() => {
                    setField("customer_id", c.id);
                    setCustomerSearch(c.organization ? `${c.name} / ${c.organization}` : c.name);
                    setShowCustomerDropdown(false);
                  }}
                >
                  <span style={{ color: "var(--text-heading)" }}>{c.name}</span>
                  {c.organization && (
                    <span className="ml-2 text-xs" style={{ color: "var(--text-muted)" }}>{c.organization}</span>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </SectionCard>

      {/* 2. Order Info */}
      <SectionCard title="Order Info">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
          <Field label="Order Number">
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="Auto-generated if empty"
              value={form.order_number}
              onChange={(e) => setField("order_number", e.target.value)}
            />
          </Field>
          <Field label="Status">
            <select className={inputClass} style={inputStyle} value={form.status}
              onChange={(e) => setField("status", e.target.value)}>
              {ORDER_STATUSES.map((s) => (
                <option key={s} value={s}>{s.replace("_", " ")}</option>
              ))}
            </select>
          </Field>
          <Field label="Currency">
            <select className={inputClass} style={inputStyle} value={form.currency}
              onChange={(e) => setField("currency", e.target.value)}>
              {CURRENCIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>
        </div>
      </SectionCard>

      {/* 3. Items */}
      <SectionCard title="Items">
        {form.items.length === 0 ? (
          <p className="text-sm mb-4" style={{ color: "var(--text-muted)" }}>No items yet.</p>
        ) : (
          <div className="space-y-3 mb-4">
            {form.items.map((item, idx) => (
              <div
                key={idx}
                className="rounded-md border p-4"
                style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-secondary)" }}
              >
                <div style={{ display: "grid", gridTemplateColumns: "140px 1fr 100px 120px auto", gap: 12, alignItems: "end" }}>
                  <Field label="Type">
                    <select
                      className={inputClass}
                      style={inputStyle}
                      value={item.type}
                      onChange={(e) => setItem(idx, "type", e.target.value)}
                    >
                      {ITEM_TYPES.map((t) => <option key={t} value={t}>{t.replace("_", " ")}</option>)}
                    </select>
                  </Field>

                  {item.type === "product" && (
                    <Field label="Product">
                      <select
                        className={inputClass}
                        style={inputStyle}
                        value={item.product_id}
                        onChange={(e) => onProductSelect(idx, e.target.value)}
                      >
                        <option value="">Select product...</option>
                        {products.map((p) => (
                          <option key={p.id} value={p.id}>{p.name}</option>
                        ))}
                      </select>
                    </Field>
                  )}

                  {item.type === "console_device" && (
                    <Field label="Device ID + Label">
                      <div style={{ display: "flex", gap: 8 }}>
                        <input
                          className={inputClass}
                          style={inputStyle}
                          placeholder="Device UID"
                          value={item.device_id}
                          onChange={(e) => setItem(idx, "device_id", e.target.value)}
                        />
                        <input
                          className={inputClass}
                          style={inputStyle}
                          placeholder="Label"
                          value={item.label}
                          onChange={(e) => setItem(idx, "label", e.target.value)}
                        />
                      </div>
                    </Field>
                  )}

                  {item.type === "freetext" && (
                    <Field label="Description">
                      <input
                        className={inputClass}
                        style={inputStyle}
                        placeholder="Description..."
                        value={item.description}
                        onChange={(e) => setItem(idx, "description", e.target.value)}
                      />
                    </Field>
                  )}

                  <Field label="Qty">
                    <input
                      type="number"
                      min="1"
                      className={inputClass}
                      style={inputStyle}
                      value={item.quantity}
                      onChange={(e) => setItem(idx, "quantity", e.target.value)}
                    />
                  </Field>

                  <Field label="Unit Price">
                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      className={inputClass}
                      style={inputStyle}
                      value={item.unit_price}
                      onChange={(e) => setItem(idx, "unit_price", e.target.value)}
                    />
                  </Field>

                  <div style={{ paddingBottom: 2 }}>
                    <button
                      type="button"
                      onClick={() => removeItem(idx)}
                      className="px-3 py-2 text-sm rounded-md border cursor-pointer hover:opacity-80"
                      style={{ borderColor: "var(--danger)", color: "var(--danger-text)", whiteSpace: "nowrap" }}
                    >
                      Remove
                    </button>
                  </div>
                </div>

                <div className="mt-3">
                  <Field label="Serial Numbers (comma-separated)">
                    <input
                      className={inputClass}
                      style={inputStyle}
                      placeholder="SN001, SN002..."
                      value={item.serial_numbers}
                      onChange={(e) => setItem(idx, "serial_numbers", e.target.value)}
                    />
                  </Field>
                </div>
              </div>
            ))}
          </div>
        )}
        <button
          type="button"
          onClick={addItem}
          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)" }}
        >
          + Add Item
        </button>
      </SectionCard>

      {/* 4. Pricing */}
      <SectionCard title="Pricing">
        <div className="flex gap-8 mb-4">
          <div>
            <div style={labelStyle}>Subtotal</div>
            <div className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
              {form.currency} {subtotal.toFixed(2)}
            </div>
          </div>
          <div>
            <div style={labelStyle}>Total</div>
            <div className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
              {form.currency} {total.toFixed(2)}
            </div>
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "140px 160px 1fr", gap: 16 }}>
          <Field label="Discount Type">
            <select
              className={inputClass}
              style={inputStyle}
              value={form.discount.type}
              onChange={(e) => setDiscount("type", e.target.value)}
            >
              <option value="percentage">Percentage (%)</option>
              <option value="fixed">Fixed Amount</option>
            </select>
          </Field>
          <Field label={form.discount.type === "percentage" ? "Discount %" : "Discount Amount"}>
            <input
              type="number"
              min="0"
              step="0.01"
              className={inputClass}
              style={inputStyle}
              value={form.discount.value}
              onChange={(e) => setDiscount("value", e.target.value)}
            />
          </Field>
          <Field label="Discount Reason">
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="Optional reason..."
              value={form.discount.reason}
              onChange={(e) => setDiscount("reason", e.target.value)}
            />
          </Field>
        </div>
        {Number(form.discount.value) > 0 && (
          <p className="text-xs mt-2" style={{ color: "var(--text-muted)" }}>
            Discount: {form.currency} {discountAmount.toFixed(2)}
          </p>
        )}
      </SectionCard>

      {/* 5. Payment */}
      <SectionCard title="Payment">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <Field label="Payment Status">
            <select
              className={inputClass}
              style={inputStyle}
              value={form.payment_status}
              onChange={(e) => setField("payment_status", e.target.value)}
            >
              {PAYMENT_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
          </Field>
          <Field label="Invoice Path (Nextcloud)">
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="05_Customers/FOLDER/invoice.pdf"
              value={form.invoice_path}
              onChange={(e) => setField("invoice_path", e.target.value)}
            />
          </Field>
        </div>
      </SectionCard>

      {/* 6. Shipping */}
      <SectionCard title="Shipping">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 16 }}>
          <Field label="Method">
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="e.g. courier, pickup"
              value={form.shipping.method}
              onChange={(e) => setShipping("method", e.target.value)}
            />
          </Field>
          <Field label="Carrier">
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="e.g. ACS, DHL"
              value={form.shipping.carrier}
              onChange={(e) => setShipping("carrier", e.target.value)}
            />
          </Field>
          <Field label="Tracking Number">
            <input
              className={inputClass}
              style={inputStyle}
              value={form.shipping.tracking_number}
              onChange={(e) => setShipping("tracking_number", e.target.value)}
            />
          </Field>
          <Field label="Destination" style={{ gridColumn: "1 / -1" }}>
            <input
              className={inputClass}
              style={inputStyle}
              placeholder="City, Country"
              value={form.shipping.destination}
              onChange={(e) => setShipping("destination", e.target.value)}
            />
          </Field>
          <Field label="Shipped At">
            <input
              type="date"
              className={inputClass}
              style={inputStyle}
              value={form.shipping.shipped_at}
              onChange={(e) => setShipping("shipped_at", e.target.value)}
            />
          </Field>
          <Field label="Delivered At">
            <input
              type="date"
              className={inputClass}
              style={inputStyle}
              value={form.shipping.delivered_at}
              onChange={(e) => setShipping("delivered_at", e.target.value)}
            />
          </Field>
        </div>
      </SectionCard>

      {/* 7. Notes */}
      <SectionCard title="Notes">
        <textarea
          className={inputClass}
          style={{ ...inputStyle, resize: "vertical", minHeight: 100 }}
          placeholder="Internal notes..."
          value={form.notes}
          onChange={(e) => setField("notes", e.target.value)}
        />
      </SectionCard>

      {/* Actions */}
      <div className="flex items-center gap-3">
        <button
          onClick={handleSave}
          disabled={saving}
          className="px-5 py-2 text-sm rounded-md cursor-pointer hover:opacity-90"
          style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: saving ? 0.7 : 1 }}
        >
          {saving ? "Saving..." : isEdit ? "Save Changes" : "Create Order"}
        </button>
        {isEdit && (
          <button
            onClick={handleDelete}
            className="px-4 py-2 text-sm rounded-md border cursor-pointer hover:opacity-80"
            style={{ borderColor: "var(--danger)", color: "var(--danger-text)" }}
          >
            Delete Order
          </button>
        )}
      </div>
    </div>
  );
}
