// ============================================
// forms2.jsx — Invoice Form (create/edit/convert)
// ============================================
function InvoiceForm({ invoice, onSave, onCancel, isNew, fromQuotation }) {
    const getDepositFromQuotation = (q) => {
        if (!q) return null
        let amount = 0
        let note = ""
        if (q.depositType === "percentage" && q.depositPercentage) {
            amount = Math.round(q.total * (q.depositPercentage / 100))
            note = `Deposit ${q.depositPercentage}%`
        } else if (q.depositType === "custom" && q.depositCustom) {
            amount = q.depositCustom
            note = "Deposit"
        }
        if (amount > 0) {
            return {
                amount,
                note,
                date: new Date().toISOString().split("T")[0],
                status: "pending",
                paidDate: null,
            }
        }
        return null
    }

    const defaultInvoice = fromQuotation
        ? {
              id: `#INV${String(Math.floor(Math.random() * 9999)).padStart(4, "0")}`,
              quotationRef: fromQuotation.id,
              client: fromQuotation.client,
              company: fromQuotation.company,
              email: fromQuotation.email,
              phone: fromQuotation.phone,
              project: fromQuotation.project,
              status: "unpaid",
              date: new Date().toLocaleDateString("en-GB", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
              }),
              due: new Date(
                  Date.now() + 15 * 24 * 60 * 60 * 1000
              ).toLocaleDateString("en-GB", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
              }),
              items: fromQuotation.items.map((item) => ({
                  desc: item.desc,
                  itemDesc: item.itemDesc || "",
                  priceType: item.priceType || "amount",
                  qty: 1,
                  price: item.price,
              })),
              total: fromQuotation.total,
              deposit: getDepositFromQuotation(fromQuotation),
              payments: [],
          }
        : {
              id: `#INV${String(Math.floor(Math.random() * 9999)).padStart(4, "0")}`,
              quotationRef: "",
              client: "",
              company: "",
              email: "",
              phone: "",
              project: "",
              status: "unpaid",
              date: new Date().toLocaleDateString("en-GB", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
              }),
              due: new Date(
                  Date.now() + 15 * 24 * 60 * 60 * 1000
              ).toLocaleDateString("en-GB", {
                  day: "2-digit",
                  month: "short",
                  year: "numeric",
              }),
              items: [
                  {
                      desc: "",
                      itemDesc: "",
                      priceType: "amount",
                      qty: 1,
                      price: 0,
                  },
              ],
              total: 0,
              deposit: null,
              payments: [],
          }

    const [form, setForm] = useState(invoice || defaultInvoice)

    const updateField = (field, value) => {
        setForm({ ...form, [field]: value })
    }

    const updateItem = (index, field, value) => {
        const newItems = [...form.items]
        if (field === "price" || field === "qty") {
            newItems[index][field] = parseFloat(value) || 0
        } else if (field === "priceType") {
            newItems[index][field] = value
            if (value === "included" || value === "lumpsum") {
                newItems[index].price = 0
                newItems[index].qty = 0
            } else {
                newItems[index].qty = newItems[index].qty || 1
            }
        } else {
            newItems[index][field] = value
        }
        const total = newItems.reduce((sum, item) => {
            if (!item.priceType || item.priceType === "amount") {
                return sum + (item.price || 0) * (item.qty || 1)
            }
            return sum
        }, 0)
        setForm({ ...form, items: newItems, total })
    }

    const addItem = () => {
        setForm({
            ...form,
            items: [
                ...form.items,
                {
                    desc: "",
                    itemDesc: "",
                    priceType: "amount",
                    qty: 1,
                    price: 0,
                },
            ],
        })
    }

    const removeItem = (index) => {
        if (form.items.length > 1) {
            const newItems = form.items.filter((_, i) => i !== index)
            const total = newItems.reduce((sum, item) => {
                if (!item.priceType || item.priceType === "amount") {
                    return sum + (item.price || 0) * (item.qty || 1)
                }
                return sum
            }, 0)
            setForm({ ...form, items: newItems, total })
        }
    }

    const [dragIndex, setDragIndex] = useState(null)

    const handleDragStart = (index) => {
        setDragIndex(index)
    }

    const handleDragOver = (e, index) => {
        e.preventDefault()
    }

    const handleDrop = (e, dropIndex) => {
        e.preventDefault()
        if (dragIndex === null || dragIndex === dropIndex) return

        const newItems = [...form.items]
        const draggedItem = newItems[dragIndex]
        newItems.splice(dragIndex, 1)
        newItems.splice(dropIndex, 0, draggedItem)
        setForm({ ...form, items: newItems })
        setDragIndex(null)
    }

    const moveItem = (index, direction) => {
        const newIndex = index + direction
        if (newIndex < 0 || newIndex >= form.items.length) return

        const newItems = [...form.items]
        const temp = newItems[index]
        newItems[index] = newItems[newIndex]
        newItems[newIndex] = temp
        setForm({ ...form, items: newItems })
    }

    return (
        <div
            style={{
                minHeight: "100vh",
                width: "100%",
                backgroundColor: "#F3F4F6",
                fontFamily: "system-ui, sans-serif",
            }}
        >
            {/* Header */}
            <div
                style={{
                    background:
                        "linear-gradient(135deg, #1F2937 0%, #374151 100%)",
                }}
            >
                <div
                    style={{ maxWidth: 800, margin: "0 auto", padding: "16px" }}
                >
                    <button
                        onClick={onCancel}
                        style={{
                            marginBottom: 12,
                            padding: "6px 12px",
                            borderRadius: 8,
                            border: "none",
                            backgroundColor: "rgba(255,255,255,0.15)",
                            color: "#FFF",
                            fontSize: 13,
                            cursor: "pointer",
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 6,
                        }}
                    >
                        <Icon name="arrow-left" size={14} />
                        Cancel
                    </button>
                    <div
                        style={{ fontSize: 20, fontWeight: 700, color: "#FFF" }}
                    >
                        {fromQuotation
                            ? "Convert to Invoice"
                            : isNew
                              ? "New Invoice"
                              : "Edit Invoice"}
                    </div>
                    <div
                        style={{ color: "#9CA3AF", fontSize: 13, marginTop: 4 }}
                    >
                        {form.id}
                    </div>
                    {fromQuotation && (
                        <div
                            style={{
                                color: "#60A5FA",
                                fontSize: 12,
                                marginTop: 4,
                            }}
                        >
                            From: {fromQuotation.id}
                        </div>
                    )}
                </div>
            </div>

            {/* Form */}
            <div
                style={{
                    maxWidth: 800,
                    margin: "0 auto",
                    minHeight: "calc(100vh - 120px)",
                }}
            >
                <div style={{ padding: 16 }}>
                    {/* Client Info */}
                    <div style={{ ...cardStyle, padding: 16 }}>
                        <div
                            style={{
                                fontSize: 15,
                                fontWeight: 600,
                                color: "#2563EB",
                                marginBottom: 16,
                            }}
                        >
                            Client Information
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label style={labelStyle}>Client Name *</label>
                            <input
                                style={inputStyle}
                                value={form.client}
                                onChange={(e) =>
                                    updateField("client", e.target.value)
                                }
                                placeholder="e.g. John Doe"
                            />
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label style={labelStyle}>Company</label>
                            <input
                                style={inputStyle}
                                value={form.company}
                                onChange={(e) =>
                                    updateField("company", e.target.value)
                                }
                                placeholder="e.g. ABC Sdn Bhd"
                            />
                        </div>

                        <div
                            style={{
                                display: "grid",
                                gridTemplateColumns: "1fr 1fr",
                                gap: 12,
                            }}
                        >
                            <div>
                                <label style={labelStyle}>Email</label>
                                <input
                                    style={inputStyle}
                                    type="email"
                                    value={form.email}
                                    onChange={(e) =>
                                        updateField("email", e.target.value)
                                    }
                                    placeholder="email@example.com"
                                />
                            </div>
                            <div>
                                <label style={labelStyle}>Phone</label>
                                <input
                                    style={inputStyle}
                                    value={form.phone}
                                    onChange={(e) =>
                                        updateField("phone", e.target.value)
                                    }
                                    placeholder="012-3456789"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Invoice Info */}
                    <div style={{ ...cardStyle, padding: 16 }}>
                        <div
                            style={{
                                fontSize: 15,
                                fontWeight: 600,
                                color: "#2563EB",
                                marginBottom: 16,
                            }}
                        >
                            Invoice Details
                        </div>

                        <div style={{ marginBottom: 16 }}>
                            <label style={labelStyle}>Project *</label>
                            <input
                                style={inputStyle}
                                value={form.project}
                                onChange={(e) =>
                                    updateField("project", e.target.value)
                                }
                                placeholder="e.g. Website Development"
                            />
                        </div>

                        <div
                            style={{
                                display: "grid",
                                gridTemplateColumns: "1fr 1fr",
                                gap: 12,
                                marginBottom: 16,
                            }}
                        >
                            <div>
                                <label style={labelStyle}>Quotation Ref</label>
                                <input
                                    style={inputStyle}
                                    value={form.quotationRef}
                                    onChange={(e) =>
                                        updateField(
                                            "quotationRef",
                                            e.target.value
                                        )
                                    }
                                    placeholder="#Q0000"
                                />
                            </div>
                            <div>
                                <label style={labelStyle}>Status</label>
                                <select
                                    style={inputStyle}
                                    value={form.status}
                                    onChange={(e) =>
                                        updateField("status", e.target.value)
                                    }
                                >
                                    <option value="unpaid">Unpaid</option>
                                    <option value="paid">Paid</option>
                                    <option value="overdue">Overdue</option>
                                </select>
                            </div>
                        </div>

                        <div
                            style={{
                                display: "grid",
                                gridTemplateColumns: "1fr 1fr",
                                gap: 12,
                            }}
                        >
                            <div>
                                <label style={labelStyle}>Invoice Date</label>
                                <input
                                    style={inputStyle}
                                    type="date"
                                    value={toDateInputValue(form.date)}
                                    onChange={(e) =>
                                        updateField("date", e.target.value)
                                    }
                                />
                            </div>
                            <div>
                                <label style={labelStyle}>Due Date</label>
                                <input
                                    style={inputStyle}
                                    type="date"
                                    value={toDateInputValue(form.due)}
                                    onChange={(e) =>
                                        updateField("due", e.target.value)
                                    }
                                />
                            </div>
                        </div>
                    </div>

                    {/* Items */}
                    <div style={{ ...cardStyle, padding: 16 }}>
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                marginBottom: 16,
                            }}
                        >
                            <div
                                style={{
                                    fontSize: 15,
                                    fontWeight: 600,
                                    color: "#2563EB",
                                }}
                            >
                                Line Items
                            </div>
                            <button
                                onClick={addItem}
                                style={{
                                    padding: "6px 12px",
                                    borderRadius: 6,
                                    border: "none",
                                    backgroundColor: "#EFF6FF",
                                    color: "#2563EB",
                                    fontWeight: 600,
                                    fontSize: 13,
                                    cursor: "pointer",
                                }}
                            >
                                + Add Item
                            </button>
                        </div>

                        {form.items.map((item, index) => (
                            <div
                                key={index}
                                draggable
                                onDragStart={() => handleDragStart(index)}
                                onDragOver={(e) => handleDragOver(e, index)}
                                onDrop={(e) => handleDrop(e, index)}
                                onDragEnd={() => setDragIndex(null)}
                                style={{
                                    backgroundColor:
                                        dragIndex === index
                                            ? "#EFF6FF"
                                            : "#F9FAFB",
                                    borderRadius: 10,
                                    padding: 14,
                                    marginBottom: 10,
                                    border:
                                        dragIndex === index
                                            ? "2px dashed #2563EB"
                                            : "1px solid #E5E7EB",
                                    cursor: "grab",
                                    opacity: dragIndex === index ? 0.8 : 1,
                                }}
                            >
                                <div
                                    style={{
                                        display: "flex",
                                        justifyContent: "space-between",
                                        alignItems: "center",
                                        marginBottom: 10,
                                    }}
                                >
                                    <div
                                        style={{
                                            display: "flex",
                                            alignItems: "center",
                                            gap: 4,
                                        }}
                                    >
                                        <span
                                            style={{
                                                color: "#9CA3AF",
                                                cursor: "grab",
                                                display: "flex",
                                            }}
                                        >
                                            <Icon name="grip" size={15} />
                                        </span>
                                        <span
                                            style={{
                                                color: "#9CA3AF",
                                                fontSize: 11,
                                            }}
                                        >
                                            Item {index + 1}
                                        </span>
                                    </div>
                                    <div style={{ display: "flex", gap: 4 }}>
                                        <button
                                            onClick={() => moveItem(index, -1)}
                                            disabled={index === 0}
                                            style={{
                                                padding: "4px 8px",
                                                borderRadius: 4,
                                                border: "1px solid #E5E7EB",
                                                backgroundColor: "#FFF",
                                                color:
                                                    index === 0
                                                        ? "#D1D5DB"
                                                        : "#6B7280",
                                                fontSize: 12,
                                                cursor:
                                                    index === 0
                                                        ? "not-allowed"
                                                        : "pointer",
                                            }}
                                        >
                                            <Icon name="chevron-up" size={14} />
                                        </button>
                                        <button
                                            onClick={() => moveItem(index, 1)}
                                            disabled={
                                                index === form.items.length - 1
                                            }
                                            style={{
                                                padding: "4px 8px",
                                                borderRadius: 4,
                                                border: "1px solid #E5E7EB",
                                                backgroundColor: "#FFF",
                                                color:
                                                    index ===
                                                    form.items.length - 1
                                                        ? "#D1D5DB"
                                                        : "#6B7280",
                                                fontSize: 12,
                                                cursor:
                                                    index ===
                                                    form.items.length - 1
                                                        ? "not-allowed"
                                                        : "pointer",
                                            }}
                                        >
                                            <Icon name="chevron-down" size={14} />
                                        </button>
                                        {form.items.length > 1 && (
                                            <button
                                                onClick={() =>
                                                    removeItem(index)
                                                }
                                                style={{
                                                    padding: "4px 8px",
                                                    borderRadius: 4,
                                                    border: "none",
                                                    backgroundColor: "#FEE2E2",
                                                    color: "#DC2626",
                                                    cursor: "pointer",
                                                    fontSize: 12,
                                                }}
                                            >
                                                <Icon name="x" size={14} />
                                            </button>
                                        )}
                                    </div>
                                </div>

                                <div
                                    style={{
                                        display: "flex",
                                        gap: 8,
                                        marginBottom: 8,
                                    }}
                                >
                                    <div style={{ flex: 1 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Item
                                        </label>
                                        <input
                                            style={inputStyle}
                                            value={item.desc}
                                            onChange={(e) =>
                                                updateItem(
                                                    index,
                                                    "desc",
                                                    e.target.value
                                                )
                                            }
                                            placeholder="Item name"
                                        />
                                    </div>
                                    <div style={{ width: 60 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Qty
                                        </label>
                                        <input
                                            style={{
                                                ...inputStyle,
                                                backgroundColor:
                                                    item.priceType ===
                                                        "included" ||
                                                    item.priceType === "lumpsum"
                                                        ? "#E5E7EB"
                                                        : "#FFF",
                                                color:
                                                    item.priceType ===
                                                        "included" ||
                                                    item.priceType === "lumpsum"
                                                        ? "#9CA3AF"
                                                        : "#111827",
                                            }}
                                            type="number"
                                            value={
                                                item.priceType === "included" ||
                                                item.priceType === "lumpsum"
                                                    ? ""
                                                    : item.qty
                                            }
                                            onChange={(e) =>
                                                updateItem(
                                                    index,
                                                    "qty",
                                                    e.target.value
                                                )
                                            }
                                            placeholder="1"
                                            disabled={
                                                item.priceType === "included" ||
                                                item.priceType === "lumpsum"
                                            }
                                        />
                                    </div>
                                    <div style={{ width: 100 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Price
                                        </label>
                                        <input
                                            style={{
                                                ...inputStyle,
                                                backgroundColor:
                                                    item.priceType ===
                                                        "included" ||
                                                    item.priceType === "lumpsum"
                                                        ? "#E5E7EB"
                                                        : "#FFF",
                                                color:
                                                    item.priceType ===
                                                        "included" ||
                                                    item.priceType === "lumpsum"
                                                        ? "#9CA3AF"
                                                        : "#111827",
                                            }}
                                            type="number"
                                            value={
                                                item.priceType === "included" ||
                                                item.priceType === "lumpsum"
                                                    ? ""
                                                    : item.price
                                            }
                                            onChange={(e) =>
                                                updateItem(
                                                    index,
                                                    "price",
                                                    e.target.value
                                                )
                                            }
                                            placeholder="1000"
                                            disabled={
                                                item.priceType === "included" ||
                                                item.priceType === "lumpsum"
                                            }
                                        />
                                    </div>
                                </div>

                                <div
                                    style={{
                                        display: "flex",
                                        gap: 6,
                                        marginBottom: 8,
                                    }}
                                >
                                    {[
                                        { value: "amount", label: "Amount" },
                                        { value: "included", label: "Included" },
                                        { value: "lumpsum", label: "Lump Sum" },
                                    ].map((opt) => (
                                        <button
                                            key={opt.value}
                                            type="button"
                                            onClick={() =>
                                                updateItem(
                                                    index,
                                                    "priceType",
                                                    opt.value
                                                )
                                            }
                                            style={{
                                                padding: "6px 12px",
                                                borderRadius: 20,
                                                border: "1px solid",
                                                borderColor:
                                                    (item.priceType ||
                                                        "amount") === opt.value
                                                        ? "#2563EB"
                                                        : "#E5E7EB",
                                                backgroundColor:
                                                    (item.priceType ||
                                                        "amount") === opt.value
                                                        ? "#EFF6FF"
                                                        : "#FFF",
                                                color:
                                                    (item.priceType ||
                                                        "amount") === opt.value
                                                        ? "#2563EB"
                                                        : "#6B7280",
                                                fontSize: 11,
                                                fontWeight:
                                                    (item.priceType ||
                                                        "amount") === opt.value
                                                        ? 600
                                                        : 400,
                                                cursor: "pointer",
                                                display: "inline-flex",
                                                alignItems: "center",
                                                gap: 5,
                                            }}
                                        >
                                            <Icon
                                                name={
                                                    (item.priceType ||
                                                        "amount") === opt.value
                                                        ? "dot-circle"
                                                        : "circle"
                                                }
                                                size={13}
                                            />
                                            {opt.label}
                                        </button>
                                    ))}
                                </div>

                                <div>
                                    <label
                                        style={{ ...labelStyle, fontSize: 11 }}
                                    >
                                        Description{" "}
                                        <span
                                            style={{
                                                color: "#9CA3AF",
                                                fontWeight: 400,
                                            }}
                                        >
                                            (optional)
                                        </span>
                                    </label>
                                    <input
                                        style={inputStyle}
                                        value={item.itemDesc || ""}
                                        onChange={(e) =>
                                            updateItem(
                                                index,
                                                "itemDesc",
                                                e.target.value
                                            )
                                        }
                                        placeholder="cth: Includes design and development"
                                    />
                                </div>
                            </div>
                        ))}

                        <div
                            style={{
                                borderTop: "2px solid #111827",
                                marginTop: 16,
                                paddingTop: 16,
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                            }}
                        >
                            <span style={{ fontWeight: 600, color: "#111827" }}>
                                Total
                            </span>
                            <span
                                style={{
                                    fontSize: 24,
                                    fontWeight: 700,
                                    color: "#111827",
                                }}
                            >
                                RM {form.total.toLocaleString()}
                            </span>
                        </div>
                    </div>

                    {/* Deposit Section */}
                    <div style={{ ...cardStyle, padding: 16 }}>
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                marginBottom: 16,
                            }}
                        >
                            <div
                                style={{
                                    fontSize: 15,
                                    fontWeight: 600,
                                    color: "#D97706",
                                }}
                            >
                                <Icon
                                    name="lock"
                                    size={16}
                                    style={{ marginRight: 7 }}
                                />
                                Deposit
                            </div>
                            {!form.deposit && (
                                <button
                                    onClick={() =>
                                        setForm({
                                            ...form,
                                            deposit: {
                                                amount: Math.round(
                                                    form.total * 0.5
                                                ),
                                                note: "Deposit 50%",
                                                date: new Date()
                                                    .toISOString()
                                                    .split("T")[0],
                                                status: "pending",
                                                paidDate: null,
                                            },
                                        })
                                    }
                                    style={{
                                        padding: "6px 12px",
                                        borderRadius: 6,
                                        border: "none",
                                        backgroundColor: "#FEF3C7",
                                        color: "#D97706",
                                        fontWeight: 600,
                                        fontSize: 12,
                                        cursor: "pointer",
                                    }}
                                >
                                    + Add Deposit
                                </button>
                            )}
                        </div>

                        {form.deposit ? (
                            <div
                                style={{
                                    backgroundColor:
                                        form.deposit.status === "paid"
                                            ? "#F0FDF4"
                                            : "#FEF3C7",
                                    borderRadius: 10,
                                    padding: 12,
                                    border:
                                        form.deposit.status === "paid"
                                            ? "1px solid #BBF7D0"
                                            : "1px solid #FDE68A",
                                }}
                            >
                                <div
                                    style={{
                                        display: "flex",
                                        gap: 8,
                                        marginBottom: 8,
                                    }}
                                >
                                    <div style={{ flex: 1 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Amount (RM)
                                        </label>
                                        <input
                                            style={inputStyle}
                                            type="number"
                                            value={form.deposit.amount || ""}
                                            onChange={(e) =>
                                                setForm({
                                                    ...form,
                                                    deposit: {
                                                        ...form.deposit,
                                                        amount:
                                                            parseFloat(
                                                                e.target.value
                                                            ) || 0,
                                                    },
                                                })
                                            }
                                            placeholder="1000"
                                            disabled={
                                                form.deposit.status === "paid"
                                            }
                                        />
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Date
                                        </label>
                                        <input
                                            style={inputStyle}
                                            type="date"
                                            value={toDateInputValue(
                                                form.deposit.date
                                            )}
                                            onChange={(e) =>
                                                setForm({
                                                    ...form,
                                                    deposit: {
                                                        ...form.deposit,
                                                        date: e.target.value,
                                                    },
                                                })
                                            }
                                        />
                                    </div>
                                    <button
                                        onClick={() =>
                                            setForm({ ...form, deposit: null })
                                        }
                                        style={{
                                            padding: "8px",
                                            borderRadius: 6,
                                            border: "none",
                                            backgroundColor: "#FEE2E2",
                                            color: "#DC2626",
                                            cursor: "pointer",
                                            fontSize: 12,
                                            marginTop: 22,
                                        }}
                                    >
                                        <Icon name="x" size={14} />
                                    </button>
                                </div>
                                <div
                                    style={{
                                        display: "flex",
                                        gap: 8,
                                        marginBottom: 8,
                                    }}
                                >
                                    <div style={{ flex: 1 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Note
                                        </label>
                                        <input
                                            style={inputStyle}
                                            value={form.deposit.note || ""}
                                            onChange={(e) =>
                                                setForm({
                                                    ...form,
                                                    deposit: {
                                                        ...form.deposit,
                                                        note: e.target.value,
                                                    },
                                                })
                                            }
                                            placeholder="cth: Deposit 50%"
                                        />
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <label
                                            style={{
                                                ...labelStyle,
                                                fontSize: 11,
                                            }}
                                        >
                                            Status
                                        </label>
                                        <div
                                            style={{
                                                display: "flex",
                                                gap: 4,
                                                marginTop: 8,
                                            }}
                                        >
                                            <button
                                                onClick={() =>
                                                    setForm({
                                                        ...form,
                                                        deposit: {
                                                            ...form.deposit,
                                                            status: "pending",
                                                            paidDate: null,
                                                        },
                                                    })
                                                }
                                                style={{
                                                    flex: 1,
                                                    padding: "8px",
                                                    borderRadius: 6,
                                                    border: "none",
                                                    backgroundColor:
                                                        form.deposit.status ===
                                                        "pending"
                                                            ? "#F59E0B"
                                                            : "#E5E7EB",
                                                    color:
                                                        form.deposit.status ===
                                                        "pending"
                                                            ? "#FFF"
                                                            : "#6B7280",
                                                    fontWeight: 600,
                                                    fontSize: 11,
                                                    cursor: "pointer",
                                                }}
                                            >
                                                Pending
                                            </button>
                                            <button
                                                onClick={() =>
                                                    setForm({
                                                        ...form,
                                                        deposit: {
                                                            ...form.deposit,
                                                            status: "paid",
                                                            paidDate:
                                                                form.deposit
                                                                    .date ||
                                                                new Date()
                                                                    .toISOString()
                                                                    .split(
                                                                        "T"
                                                                    )[0],
                                                        },
                                                    })
                                                }
                                                style={{
                                                    flex: 1,
                                                    padding: "8px",
                                                    borderRadius: 6,
                                                    border: "none",
                                                    backgroundColor:
                                                        form.deposit.status ===
                                                        "paid"
                                                            ? "#10B981"
                                                            : "#E5E7EB",
                                                    color:
                                                        form.deposit.status ===
                                                        "paid"
                                                            ? "#FFF"
                                                            : "#6B7280",
                                                    fontWeight: 600,
                                                    fontSize: 11,
                                                    cursor: "pointer",
                                                }}
                                            >
                                                Paid
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div
                                style={{
                                    color: "#9CA3AF",
                                    fontSize: 13,
                                    textAlign: "center",
                                    padding: 20,
                                }}
                            >
                                Tiada deposit. Klik "+ Add Deposit" untuk
                                tambah.
                            </div>
                        )}
                    </div>

                    {/* Payments Section */}
                    <div style={{ ...cardStyle, padding: 16 }}>
                        <div
                            style={{
                                display: "flex",
                                justifyContent: "space-between",
                                alignItems: "center",
                                marginBottom: 16,
                            }}
                        >
                            <div
                                style={{
                                    fontSize: 15,
                                    fontWeight: 600,
                                    color: "#10B981",
                                }}
                            >
                                <Icon
                                    name="dollar"
                                    size={16}
                                    style={{ marginRight: 7 }}
                                />
                                Payments Received
                            </div>
                            <button
                                onClick={() =>
                                    setForm({
                                        ...form,
                                        payments: [
                                            ...(form.payments || []),
                                            {
                                                amount: 0,
                                                date: new Date().toLocaleDateString(
                                                    "en-GB",
                                                    {
                                                        day: "2-digit",
                                                        month: "short",
                                                        year: "numeric",
                                                    }
                                                ),
                                                note: "",
                                            },
                                        ],
                                    })
                                }
                                style={{
                                    padding: "6px 12px",
                                    borderRadius: 6,
                                    border: "none",
                                    backgroundColor: "#ECFDF5",
                                    color: "#059669",
                                    fontWeight: 600,
                                    fontSize: 12,
                                    cursor: "pointer",
                                }}
                            >
                                + Add Payment
                            </button>
                        </div>

                        {!form.payments || form.payments.length === 0 ? (
                            <div
                                style={{
                                    color: "#9CA3AF",
                                    fontSize: 13,
                                    textAlign: "center",
                                    padding: 20,
                                }}
                            >
                                Tiada payment lagi. Klik "+ Add Payment" untuk
                                tambah.
                            </div>
                        ) : (
                            <>
                                {form.payments.map((payment, index) => (
                                    <div
                                        key={index}
                                        style={{
                                            backgroundColor: "#F0FDF4",
                                            borderRadius: 10,
                                            padding: 12,
                                            marginBottom: 10,
                                            border: "1px solid #BBF7D0",
                                        }}
                                    >
                                        <div
                                            style={{
                                                display: "flex",
                                                gap: 8,
                                                marginBottom: 8,
                                            }}
                                        >
                                            <div style={{ flex: 1 }}>
                                                <label
                                                    style={{
                                                        ...labelStyle,
                                                        fontSize: 11,
                                                    }}
                                                >
                                                    Amount (RM)
                                                </label>
                                                <input
                                                    style={inputStyle}
                                                    type="number"
                                                    value={payment.amount || ""}
                                                    onChange={(e) => {
                                                        const newPayments = [
                                                            ...form.payments,
                                                        ]
                                                        newPayments[
                                                            index
                                                        ].amount =
                                                            parseFloat(
                                                                e.target.value
                                                            ) || 0
                                                        setForm({
                                                            ...form,
                                                            payments:
                                                                newPayments,
                                                        })
                                                    }}
                                                    placeholder="1000"
                                                />
                                            </div>
                                            <div style={{ flex: 1 }}>
                                                <label
                                                    style={{
                                                        ...labelStyle,
                                                        fontSize: 11,
                                                    }}
                                                >
                                                    Date
                                                </label>
                                                <input
                                                    style={inputStyle}
                                                    type="date"
                                                    value={toDateInputValue(
                                                        payment.date
                                                    )}
                                                    onChange={(e) => {
                                                        const newPayments = [
                                                            ...form.payments,
                                                        ]
                                                        newPayments[
                                                            index
                                                        ].date = e.target.value
                                                        setForm({
                                                            ...form,
                                                            payments:
                                                                newPayments,
                                                        })
                                                    }}
                                                />
                                            </div>
                                            <button
                                                onClick={() => {
                                                    const newPayments =
                                                        form.payments.filter(
                                                            (_, i) =>
                                                                i !== index
                                                        )
                                                    setForm({
                                                        ...form,
                                                        payments: newPayments,
                                                    })
                                                }}
                                                style={{
                                                    padding: "8px",
                                                    borderRadius: 6,
                                                    border: "none",
                                                    backgroundColor: "#FEE2E2",
                                                    color: "#DC2626",
                                                    cursor: "pointer",
                                                    fontSize: 12,
                                                    marginTop: 22,
                                                }}
                                            >
                                                <Icon name="x" size={14} />
                                            </button>
                                        </div>
                                        <div>
                                            <label
                                                style={{
                                                    ...labelStyle,
                                                    fontSize: 11,
                                                }}
                                            >
                                                Note{" "}
                                                <span
                                                    style={{
                                                        color: "#9CA3AF",
                                                        fontWeight: 400,
                                                    }}
                                                >
                                                    (optional)
                                                </span>
                                            </label>
                                            <input
                                                style={inputStyle}
                                                value={payment.note || ""}
                                                onChange={(e) => {
                                                    const newPayments = [
                                                        ...form.payments,
                                                    ]
                                                    newPayments[index].note =
                                                        e.target.value
                                                    setForm({
                                                        ...form,
                                                        payments: newPayments,
                                                    })
                                                }}
                                                placeholder="cth: Deposit 50%"
                                            />
                                        </div>
                                    </div>
                                ))}

                                <div
                                    style={{
                                        borderTop: "1px solid #D1FAE5",
                                        marginTop: 12,
                                        paddingTop: 12,
                                    }}
                                >
                                    <div
                                        style={{
                                            display: "flex",
                                            justifyContent: "space-between",
                                            marginBottom: 8,
                                        }}
                                    >
                                        <span
                                            style={{
                                                color: "#6B7280",
                                                fontSize: 13,
                                            }}
                                        >
                                            Total Paid
                                        </span>
                                        <span
                                            style={{
                                                fontWeight: 600,
                                                color: "#059669",
                                                fontSize: 15,
                                            }}
                                        >
                                            RM{" "}
                                            {(form.payments || [])
                                                .reduce(
                                                    (sum, p) =>
                                                        sum + (p.amount || 0),
                                                    0
                                                )
                                                .toLocaleString()}
                                        </span>
                                    </div>
                                    <div
                                        style={{
                                            display: "flex",
                                            justifyContent: "space-between",
                                        }}
                                    >
                                        <span
                                            style={{
                                                color: "#6B7280",
                                                fontSize: 13,
                                            }}
                                        >
                                            Balance Due
                                        </span>
                                        <span
                                            style={{
                                                fontWeight: 700,
                                                color: "#DC2626",
                                                fontSize: 17,
                                            }}
                                        >
                                            RM{" "}
                                            {(
                                                form.total -
                                                (form.payments || []).reduce(
                                                    (sum, p) =>
                                                        sum + (p.amount || 0),
                                                    0
                                                )
                                            ).toLocaleString()}
                                        </span>
                                    </div>
                                </div>
                            </>
                        )}
                    </div>

                    {/* Actions */}
                    <div
                        style={{
                            display: "flex",
                            flexDirection: "column",
                            gap: 10,
                        }}
                    >
                        <button
                            onClick={() => onSave(form)}
                            style={{
                                width: "100%",
                                padding: 14,
                                borderRadius: 10,
                                border: "none",
                                backgroundColor: "#2563EB",
                                color: "#FFF",
                                fontWeight: 600,
                                fontSize: 15,
                                cursor: "pointer",
                            }}
                        >
                            {fromQuotation
                                ? "Create Invoice"
                                : isNew
                                  ? "Create Invoice"
                                  : "Save Changes"}
                        </button>
                        <button
                            onClick={onCancel}
                            style={{
                                width: "100%",
                                padding: 14,
                                borderRadius: 10,
                                border: "1px solid #E5E7EB",
                                backgroundColor: "#FFF",
                                color: "#374151",
                                fontWeight: 600,
                                fontSize: 15,
                                cursor: "pointer",
                            }}
                        >
                            Cancel
                        </button>
                    </div>
                </div>
            </div>
        </div>
    )
}

window.InvoiceForm = InvoiceForm
