"use client";

import { useState, useEffect, useRef } from "react";
// Using plain fetch — API endpoints bypass CSRF in development

interface Customer {
  id: string;
  name: string;
  phone: string;
  email: string | null;
}

const t = {
  en: {
    createTitle: "New Quotation",
    editTitle: "Edit Quotation",
    title: "Title",
    customer: "Customer",
    customerRequired: "Please select a customer",
    customerSearch: "Search customers...",
    noCustomers: "No customers found",
    clearCustomer: "Clear",
    currency: "Currency",
    taxRate: "Tax Rate (%)",
    discountRate: "Discount (%)",
    validUntil: "Valid Until",
    notes: "Notes",
    items: "Line Items",
    description: "Description",
    quantity: "Qty",
    unitPrice: "Unit Price",
    itemTotal: "Total",
    addItem: "Add Item",
    removeItem: "Remove",
    subtotal: "Subtotal",
    discount: "Discount",
    tax: "Tax",
    total: "Total",
    save: "Create & Send",
    saveEdit: "Save",
    saveDraft: "Save as Draft",
    cancel: "Cancel",
    saving: "Saving...",
    makeRecurring: "Make Recurring",
    frequency: "Frequency",
    startDate: "Start Date",
    endDate: "End Date (optional)",
    autoSend: "Auto-send when generated",
    MONTHLY: "Monthly",
    QUARTERLY: "Quarterly",
    SEMI_ANNUAL: "Semi-Annual",
    ANNUAL: "Annual",
    addNewCustomer: "+ New Customer",
    customerName: "Name",
    customerPhone: "Phone",
    customerEmail: "Email (optional)",
    saveCustomer: "Add",
    cancelAdd: "Cancel",
    addingCustomer: "Adding...",
    sendImmediately: "Send to customer immediately",
    saveFailed: "Failed to save. Please try again.",
  },
  ar: {
    createTitle: "عرض سعر جديد",
    editTitle: "تعديل عرض السعر",
    title: "العنوان",
    customer: "العميل",
    customerRequired: "يرجى اختيار عميل",
    customerSearch: "بحث عن عميل...",
    noCustomers: "لم يتم العثور على عملاء",
    clearCustomer: "مسح",
    currency: "العملة",
    taxRate: "معدل الضريبة (%)",
    discountRate: "الخصم (%)",
    validUntil: "صالح حتى",
    notes: "ملاحظات",
    items: "البنود",
    description: "الوصف",
    quantity: "الكمية",
    unitPrice: "سعر الوحدة",
    itemTotal: "الإجمالي",
    addItem: "إضافة بند",
    removeItem: "حذف",
    subtotal: "المجموع الفرعي",
    discount: "الخصم",
    tax: "الضريبة",
    total: "الإجمالي",
    save: "إنشاء وإرسال",
    saveEdit: "حفظ",
    saveDraft: "حفظ كمسودة",
    cancel: "إلغاء",
    saving: "جاري الحفظ...",
    makeRecurring: "جعله متكرراً",
    frequency: "التكرار",
    startDate: "تاريخ البدء",
    endDate: "تاريخ الانتهاء (اختياري)",
    autoSend: "إرسال تلقائي عند الإنشاء",
    MONTHLY: "شهري",
    QUARTERLY: "ربع سنوي",
    SEMI_ANNUAL: "نصف سنوي",
    ANNUAL: "سنوي",
    addNewCustomer: "+ عميل جديد",
    customerName: "الاسم",
    customerPhone: "الهاتف",
    customerEmail: "البريد الإلكتروني (اختياري)",
    saveCustomer: "إضافة",
    cancelAdd: "إلغاء",
    addingCustomer: "جاري الإضافة...",
    sendImmediately: "إرسال للعميل فوراً",
    saveFailed: "فشل الحفظ. يرجى المحاولة مرة أخرى.",
  },
};

interface LineItem {
  id?: string;
  description: string;
  quantity: number;
  unitPrice: number;
}

interface QuotationFormProps {
  lang: string;
  quotation?: {
    id: string;
    title: string;
    currency: string;
    notes?: string | null;
    taxRate?: number;
    discountRate?: number;
    validUntil?: string | null;
    customerId?: string | null;
    customer?: {
      id: string;
      name: string;
      phone?: string;
      email?: string | null;
    } | null;
    items: Array<{
      id: string;
      description: string;
      quantity: number;
      unitPrice: number;
      total: number;
    }>;
  } | null;
  onClose: () => void;
}

export function QuotationForm({
  lang,
  quotation,
  onClose,
}: QuotationFormProps) {
  const isAr = lang === "ar";
  const labels = isAr ? t.ar : t.en;

  // Customer state
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [customerSearch, setCustomerSearch] = useState("");
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(
    quotation?.customer
      ? {
          id: quotation.customer.id,
          name: quotation.customer.name,
          phone: quotation.customer.phone || "",
          email: quotation.customer.email || null,
        }
      : null,
  );
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
  const customerDropdownRef = useRef<HTMLDivElement>(null);
  const formRef = useRef<HTMLFormElement>(null);

  // Fetch customers on mount
  useEffect(() => {
    const fetchCustomers = async () => {
      try {
        const res = await fetch("/api/user/customers?limit=100");
        const data = await res.json();
        if (data.success && data.customers) {
          setCustomers(
            (data.customers as { _id?: string; id?: string; name: string; phone: string; email?: string | null }[]).map((c) => ({
              id: c.id || c._id || "",
              name: c.name,
              phone: c.phone || "",
              email: c.email || null,
            })),
          );
        }
      } catch {
        // silently fail
      }
    };
    fetchCustomers();
  }, []);

  // Close dropdown on outside click
  useEffect(() => {
    const handleClick = (e: MouseEvent) => {
      if (
        customerDropdownRef.current &&
        !customerDropdownRef.current.contains(e.target as Node)
      ) {
        setShowCustomerDropdown(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  const filteredCustomers = customers.filter((c) => {
    const q = customerSearch.toLowerCase();
    return (
      c.name.toLowerCase().includes(q) ||
      c.phone.includes(q) ||
      (c.email && c.email.toLowerCase().includes(q))
    );
  });

  // Inline add-customer state
  const [showAddCustomer, setShowAddCustomer] = useState(false);
  const [newCustomerName, setNewCustomerName] = useState("");
  const [newCustomerPhone, setNewCustomerPhone] = useState("");
  const [newCustomerEmail, setNewCustomerEmail] = useState("");
  const [addingCustomer, setAddingCustomer] = useState(false);
  const [addCustomerError, setAddCustomerError] = useState("");

  const resetAddCustomerForm = () => {
    setShowAddCustomer(false);
    setNewCustomerName("");
    setNewCustomerPhone("");
    setNewCustomerEmail("");
    setAddCustomerError("");
  };

  const handleAddCustomer = async () => {
    if (newCustomerName.trim().length < 2 || newCustomerPhone.trim().length < 5)
      return;
    setAddingCustomer(true);
    setAddCustomerError("");
    try {
      const res = await fetch("/api/user/customers", { credentials: "include",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: newCustomerName.trim(),
          phone: newCustomerPhone.trim(),
          ...(newCustomerEmail.trim()
            ? { email: newCustomerEmail.trim() }
            : {}),
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setAddCustomerError(data.error || "Failed to create customer");
        return;
      }
      const raw = data.customer || {};
      const created: Customer = {
        id: raw.id || raw._id || data.id || "",
        name: raw.name || newCustomerName.trim(),
        phone: raw.phone || newCustomerPhone.trim(),
        email: raw.email || newCustomerEmail.trim() || null,
      };
      setCustomers((prev) => [created, ...prev]);
      setSelectedCustomer(created);
      setShowCustomerDropdown(false);
      setCustomerError(false);
      resetAddCustomerForm();
    } catch {
      setAddCustomerError("Network error");
    } finally {
      setAddingCustomer(false);
    }
  };

  const [title, setTitle] = useState(quotation?.title || "");
  const [currency, setCurrency] = useState(quotation?.currency || "QAR");
  const [taxRate, setTaxRate] = useState(quotation?.taxRate || 0);
  const [discountRate, setDiscountRate] = useState(
    quotation?.discountRate || 0,
  );
  const [validUntil, setValidUntil] = useState(
    quotation?.validUntil
      ? new Date(quotation.validUntil).toISOString().split("T")[0]
      : "",
  );
  const [notes, setNotes] = useState(quotation?.notes || "");
  const [items, setItems] = useState<LineItem[]>(
    quotation?.items?.map((i) => ({
      id: i.id,
      description: i.description,
      quantity: i.quantity,
      unitPrice: i.unitPrice,
    })) || [{ description: "", quantity: 1, unitPrice: 0 }],
  );
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState("");
  const sendImmediatelyRef = useRef(true);
  const [sendImmediately, setSendImmediately] = useState(true);

  // Recurring state
  const [isRecurring, setIsRecurring] = useState(false);
  const [recurringFrequency, setRecurringFrequency] = useState("MONTHLY");
  const [recurringStartDate, setRecurringStartDate] = useState(
    new Date().toISOString().split("T")[0],
  );
  const [recurringEndDate, setRecurringEndDate] = useState("");
  const [recurringAutoSend, setRecurringAutoSend] = useState(true);

  const subtotal = items.reduce((s, i) => s + i.quantity * i.unitPrice, 0);
  const discountAmount = subtotal * (discountRate / 100);
  const afterDiscount = subtotal - discountAmount;
  const taxAmount = afterDiscount * (taxRate / 100);
  const total = afterDiscount + taxAmount;

  const addLineItem = () => {
    setItems([...items, { description: "", quantity: 1, unitPrice: 0 }]);
  };

  const removeLineItem = (index: number) => {
    setItems(items.filter((_, i) => i !== index));
  };

  const updateLineItem = (
    index: number,
    field: keyof LineItem,
    value: string | number,
  ) => {
    const updated = [...items];
    updated[index] = { ...updated[index], [field]: value };
    setItems(updated);
  };

  const [customerError, setCustomerError] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim()) return;
    if (!selectedCustomer && !quotation) {
      setCustomerError(true);
      return;
    }
    setCustomerError(false);

    setSaving(true);
    setSaveError("");
    try {
      const itemsPayload = items
        .filter((i) => i.description.trim())
        .map((i) => ({
          description: i.description,
          quantity: i.quantity,
          unitPrice: i.unitPrice,
        }));

      // If recurring is enabled and this is a new quotation, use recurring endpoint
      if (isRecurring && !quotation) {
        const recurringBody = {
          title,
          currency,
          taxRate,
          discountRate,
          notes: notes || undefined,
          customerId: selectedCustomer?.id || undefined,
          items: itemsPayload,
          frequency: recurringFrequency,
          startDate: new Date(recurringStartDate).toISOString(),
          endDate: recurringEndDate
            ? new Date(recurringEndDate).toISOString()
            : undefined,
          autoSend: recurringAutoSend,
        };

        const res = await fetch("/api/dashboard/quotations/recurring", { credentials: "include",
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(recurringBody),
        });

        if (res.ok) {
          onClose();
          return;
        }
        const errData = await res.json().catch(() => ({}));
        setSaveError(
          (errData as { error?: string }).error || labels.saveFailed,
        );
        return;
      }

      const body = {
        title,
        currency,
        taxRate,
        discountRate,
        validUntil: validUntil ? new Date(validUntil).toISOString() : undefined,
        notes: notes || undefined,
        customerId: selectedCustomer?.id || undefined,
        items: itemsPayload,
        sendImmediately: sendImmediatelyRef.current,
      };

      const url = quotation
        ? `/api/dashboard/quotations/${quotation.id}`
        : "/api/dashboard/quotations";
      const method = quotation ? "PATCH" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify(body),
      });

      if (res.ok) {
        onClose();
        return;
      }
      const errData = await res.json().catch(() => ({}));
      setSaveError((errData as { error?: string }).error || labels.saveFailed);
    } catch (err) {
      console.error("Failed to save quotation:", err);
      setSaveError(labels.saveFailed);
    } finally {
      setSaving(false);
    }
  };

  return (
    <form ref={formRef} onSubmit={handleSubmit} className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold text-gray-900">
          {quotation ? labels.editTitle : labels.createTitle}
        </h2>
        <button
          type="button"
          onClick={onClose}
          className="text-gray-400 hover:text-gray-600"
        >
          &times;
        </button>
      </div>

      {/* Basic Fields */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.title}
          </label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>

        {/* Customer Selector */}
        <div ref={customerDropdownRef} className="relative">
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.customer} <span className="text-red-500">*</span>
          </label>
          {selectedCustomer ? (
            <div className="flex items-center justify-between px-3 py-2 border border-green-300 rounded-lg bg-green-50">
              <div className="text-sm">
                <span className="font-medium text-gray-900">
                  {selectedCustomer.name}
                </span>
                <span className="text-gray-500 ml-2">
                  {selectedCustomer.phone}
                </span>
              </div>
              <button
                type="button"
                onClick={() => setSelectedCustomer(null)}
                className="text-xs text-red-500 hover:text-red-700 font-medium"
              >
                {labels.clearCustomer}
              </button>
            </div>
          ) : (
            <div className="relative">
              <input
                type="text"
                placeholder={labels.customerSearch}
                value={customerSearch}
                onChange={(e) => {
                  setCustomerSearch(e.target.value);
                  setShowCustomerDropdown(true);
                }}
                onFocus={() => {
                  setShowCustomerDropdown(true);
                  setCustomerError(false);
                }}
                className={`w-full px-3 py-2 border rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${customerError ? "border-red-400 bg-red-50" : "border-gray-300"}`}
              />
              {customerError && (
                <p className="text-xs text-red-500 mt-1">
                  {labels.customerRequired}
                </p>
              )}
              {showCustomerDropdown && (
                <div className="absolute z-20 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-64 overflow-y-auto">
                  {showAddCustomer ? (
                    <div className="p-3 space-y-2">
                      <input
                        type="text"
                        placeholder={labels.customerName}
                        value={newCustomerName}
                        onChange={(e) => setNewCustomerName(e.target.value)}
                        className="w-full px-2 py-1.5 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                        autoFocus
                      />
                      <input
                        type="text"
                        placeholder={labels.customerPhone}
                        value={newCustomerPhone}
                        onChange={(e) => setNewCustomerPhone(e.target.value)}
                        className="w-full px-2 py-1.5 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                      />
                      <input
                        type="text"
                        placeholder={labels.customerEmail}
                        value={newCustomerEmail}
                        onChange={(e) => setNewCustomerEmail(e.target.value)}
                        className="w-full px-2 py-1.5 border border-gray-300 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                      />
                      {addCustomerError && (
                        <p className="text-xs text-red-500">
                          {addCustomerError}
                        </p>
                      )}
                      <div className="flex gap-2">
                        <button
                          type="button"
                          disabled={
                            addingCustomer ||
                            newCustomerName.trim().length < 2 ||
                            newCustomerPhone.trim().length < 5
                          }
                          onClick={handleAddCustomer}
                          className="flex-1 px-2 py-1.5 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
                        >
                          {addingCustomer
                            ? labels.addingCustomer
                            : labels.saveCustomer}
                        </button>
                        <button
                          type="button"
                          onClick={resetAddCustomerForm}
                          className="px-2 py-1.5 border border-gray-300 rounded text-sm text-gray-600 hover:bg-gray-50"
                        >
                          {labels.cancelAdd}
                        </button>
                      </div>
                    </div>
                  ) : (
                    <>
                      <button
                        type="button"
                        onClick={() => setShowAddCustomer(true)}
                        className="w-full text-start px-3 py-2 text-sm font-medium text-blue-600 hover:bg-blue-50 border-b border-gray-200"
                      >
                        {labels.addNewCustomer}
                      </button>
                      {filteredCustomers.length === 0 ? (
                        <div className="px-3 py-2 text-sm text-gray-400">
                          {labels.noCustomers}
                        </div>
                      ) : (
                        filteredCustomers.map((c) => (
                          <button
                            key={c.id}
                            type="button"
                            onClick={() => {
                              setSelectedCustomer(c);
                              setCustomerSearch("");
                              setShowCustomerDropdown(false);
                              setCustomerError(false);
                            }}
                            className="w-full text-start px-3 py-2 hover:bg-blue-50 text-sm border-b border-gray-50 last:border-0"
                          >
                            <div className="font-medium text-gray-900">
                              {c.name}
                            </div>
                            <div className="text-xs text-gray-500">
                              {c.phone}
                              {c.email ? ` · ${c.email}` : ""}
                            </div>
                          </button>
                        ))
                      )}
                    </>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.currency}
          </label>
          <select
            value={currency}
            onChange={(e) => setCurrency(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          >
            <option value="QAR">QAR</option>
            <option value="SAR">SAR</option>
            <option value="AED">AED</option>
            <option value="KWD">KWD</option>
            <option value="BHD">BHD</option>
            <option value="OMR">OMR</option>
            <option value="USD">USD</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.taxRate}
          </label>
          <input
            type="number"
            min="0"
            max="100"
            step="0.01"
            value={taxRate}
            onChange={(e) => setTaxRate(parseFloat(e.target.value) || 0)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.discountRate}
          </label>
          <input
            type="number"
            min="0"
            max="100"
            step="0.01"
            value={discountRate}
            onChange={(e) => setDiscountRate(parseFloat(e.target.value) || 0)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            {labels.validUntil}
          </label>
          <input
            type="date"
            value={validUntil}
            onChange={(e) => setValidUntil(e.target.value)}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
      </div>

      {/* Notes */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">
          {labels.notes}
        </label>
        <textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={2}
          className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
        />
      </div>

      {/* Line Items */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-medium text-gray-700">{labels.items}</h3>
          <button
            type="button"
            onClick={addLineItem}
            className="text-sm text-blue-600 hover:text-blue-700 font-medium"
          >
            + {labels.addItem}
          </button>
        </div>
        <div className="space-y-2">
          {items.map((item, index) => (
            <div key={index} className="flex gap-2 items-start">
              <input
                type="text"
                placeholder={labels.description}
                value={item.description}
                onChange={(e) =>
                  updateLineItem(index, "description", e.target.value)
                }
                className="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <input
                type="number"
                placeholder={labels.quantity}
                min="0.01"
                step="0.01"
                value={item.quantity}
                onChange={(e) =>
                  updateLineItem(
                    index,
                    "quantity",
                    parseFloat(e.target.value) || 0,
                  )
                }
                className="w-20 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <input
                type="number"
                placeholder={labels.unitPrice}
                min="0"
                step="0.01"
                value={item.unitPrice}
                onChange={(e) =>
                  updateLineItem(
                    index,
                    "unitPrice",
                    parseFloat(e.target.value) || 0,
                  )
                }
                className="w-28 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
              <span className="w-24 py-2 text-sm text-gray-700 text-end">
                {(item.quantity * item.unitPrice).toLocaleString()}
              </span>
              {items.length > 1 && (
                <button
                  type="button"
                  onClick={() => removeLineItem(index)}
                  className="text-red-400 hover:text-red-600 py-2 px-1"
                >
                  &times;
                </button>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Totals */}
      <div className="border-t pt-4 space-y-1">
        <div className="flex justify-between text-sm">
          <span className="text-gray-500">{labels.subtotal}</span>
          <span>
            {currency} {subtotal.toLocaleString()}
          </span>
        </div>
        {discountRate > 0 && (
          <div className="flex justify-between text-sm text-red-600">
            <span>
              {labels.discount} ({discountRate}%)
            </span>
            <span>-{discountAmount.toLocaleString()}</span>
          </div>
        )}
        {taxRate > 0 && (
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">
              {labels.tax} ({taxRate}%)
            </span>
            <span>{taxAmount.toLocaleString()}</span>
          </div>
        )}
        <div className="flex justify-between text-base font-semibold pt-2 border-t">
          <span>{labels.total}</span>
          <span>
            {currency} {total.toLocaleString()}
          </span>
        </div>
      </div>

      {/* Make Recurring Toggle (only for new quotations) */}
      {!quotation && (
        <div className="border-t pt-4">
          <div className="flex items-center justify-between mb-3">
            <label className="text-sm font-medium text-gray-700">
              {labels.makeRecurring}
            </label>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={isRecurring}
                onChange={(e) => setIsRecurring(e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
            </label>
          </div>

          {isRecurring && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-blue-50 p-4 rounded-lg">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {labels.frequency}
                </label>
                <select
                  value={recurringFrequency}
                  onChange={(e) => setRecurringFrequency(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value="MONTHLY">{labels.MONTHLY}</option>
                  <option value="QUARTERLY">{labels.QUARTERLY}</option>
                  <option value="SEMI_ANNUAL">{labels.SEMI_ANNUAL}</option>
                  <option value="ANNUAL">{labels.ANNUAL}</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {labels.startDate}
                </label>
                <input
                  type="date"
                  value={recurringStartDate}
                  onChange={(e) => setRecurringStartDate(e.target.value)}
                  required={isRecurring}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {labels.endDate}
                </label>
                <input
                  type="date"
                  value={recurringEndDate}
                  onChange={(e) => setRecurringEndDate(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                />
              </div>
              <div className="flex items-center gap-2 pt-6">
                <input
                  type="checkbox"
                  id="autoSend"
                  checked={recurringAutoSend}
                  onChange={(e) => setRecurringAutoSend(e.target.checked)}
                  className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <label htmlFor="autoSend" className="text-sm text-gray-700">
                  {labels.autoSend}
                </label>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Actions */}
      {saveError && (
        <p className="text-sm text-red-600 text-end">{saveError}</p>
      )}
      <div className="flex gap-3 justify-end">
        <button
          type="button"
          onClick={onClose}
          className="px-4 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50"
        >
          {labels.cancel}
        </button>
        {!quotation && (
          <button
            type="button"
            disabled={saving}
            onClick={() => {
              sendImmediatelyRef.current = false;
              setSendImmediately(false);
              formRef.current?.requestSubmit();
            }}
            className="px-4 py-2 border border-gray-300 rounded-lg text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
          >
            {saving && !sendImmediately ? labels.saving : labels.saveDraft}
          </button>
        )}
        <button
          type="submit"
          disabled={saving}
          onClick={() => {
            if (!quotation) {
              sendImmediatelyRef.current = true;
              setSendImmediately(true);
            }
          }}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700 disabled:opacity-50"
        >
          {saving && sendImmediately
            ? labels.saving
            : quotation
              ? labels.saveEdit
              : labels.save}
        </button>
      </div>
    </form>
  );
}
