"use client";

import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { handleUpdateGeneralSettings } from "@/lib/actions";
import { useToast } from "@/hooks/use-toast";
import { useTransition } from "react";
import { PlusCircle, Trash2 } from "lucide-react";

const printerConfigSchema = z.object({
  id: z.string(),
  name: z.string(),
  ipAddress: z.string(),
  port: z.coerce.number(),
});

const printSectionSchema = z.object({
  id: z.string(),
  name: z.string(),
  printerId: z.string(),
  autoPrint: z.boolean(),
});

const restaurantAreaSchema = z.object({
  id: z.string(),
  name: z.string(),
  sortOrder: z.coerce.number().int().min(0).default(0),
});

const restaurantTableSchema = z.object({
  id: z.string(),
  name: z.string(),
  areaId: z.string().optional().default(""),
  seats: z.coerce.number().int().min(1).max(20).default(4),
});

const createClientId = () => {
  const randomUuid = globalThis.crypto?.randomUUID;
  if (typeof randomUuid === "function") {
    return randomUuid.call(globalThis.crypto);
  }
  return `tmp-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
};

const NO_RESTAURANT_AREA_VALUE = "__no_area__";

const formSchema = z.object({
  appName: z.string().optional(),
  appCurrency: z.string().optional(),
  appLogoUrl: z.string().optional(),
  deploymentMode: z.string().optional(),
  businessMode: z.string().optional(),
  documentStoragePath: z.string().optional(),
  approvedIpAddress: z.string().optional(),
  defaultPosVisaBankAccountId: z.string().optional(),
  restaurantPosEnabled: z.boolean().optional(),
  restaurantPosAreasEnabled: z.boolean().optional(),
  restaurantPosSplitBillEnabled: z.boolean().optional(),
  restaurantPosMergeTablesEnabled: z.boolean().optional(),
  restaurantPosTransferItemEnabled: z.boolean().optional(),
  restaurantPosPartialCheckoutEnabled: z.boolean().optional(),
  restaurantPosKotEnabled: z.boolean().optional(),
  restaurantPosAutoReserveMinutes: z.coerce.number().int().min(0).max(720).optional(),
  restaurantPosDefaultGuestCount: z.coerce.number().int().min(1).max(100).optional(),
  restaurantPosAreas: z.array(restaurantAreaSchema).optional(),
  restaurantPosTables: z.array(restaurantTableSchema).optional(),
  posShowSuppliers: z.boolean().optional(),
  salesRepsEnabled: z.boolean().optional(),
  posShowItemNumberColumn: z.boolean().optional(),
  posShowUnitColumn: z.boolean().optional(),
  posShowDescriptionColumn: z.boolean().optional(),
  posShowBarcodeColumn: z.boolean().optional(),
  posShowQuantityColumn: z.boolean().optional(),
  posShowPriceColumn: z.boolean().optional(),
  posShowItemDiscountColumn: z.boolean().optional(),
  posShowBonusColumn: z.boolean().optional(),
  posShowTotalColumn: z.boolean().optional(),
  posShowActionsColumn: z.boolean().optional(),
  posShowWeighedItemsButton: z.boolean().optional(),
  warehousesEnabled: z.boolean().optional(),
  allowOutOfStockSales: z.boolean().optional(),
  blockSalesBelowCost: z.boolean().optional(),
  salesShipmentWorkflowEnabled: z.boolean().optional(),
  purchaseShipmentWorkflowEnabled: z.boolean().optional(),
  purchaseShelfTaskEnabled: z.boolean().optional(),
  purchasePostingFollowupEnabled: z.boolean().optional(),
  defaultWarehouseId: z.string().optional(),
  defaultPurchaseWarehouseId: z.string().optional(),
  defaultTaxMethod: z.string().optional(),
  defaultInvoiceTaxRate: z.coerce.number().optional(),
  defaultLineTaxRate: z.coerce.number().optional(),
  fxAutoUpdateRates: z.boolean().optional(),
  fxLockBaseCurrency: z.boolean().optional(),
  scaleMode: z.string().optional(),
  scaleDecimalSeparator: z.string().optional(),
  scaleReadRegex: z.string().optional(),
  scaleHidVendorId: z.string().optional(),
  scaleHidProductId: z.string().optional(),
  scaleSerialPort: z.string().optional(),
  scaleSerialBaudRate: z.coerce.number().optional(),
  printHeaderRightText: z.string().optional(),
  printHeaderCenterText: z.string().optional(),
  printHeaderLeftText: z.string().optional(),
  printHeaderText: z.string().optional(),
  printFooterText: z.string().optional(),
  customPrintersEnabled: z.boolean().optional(),
  printerAutoPrintEnabled: z.boolean().optional(),
  printTransportMode: z.string().optional(),
  defaultCustomerReceiptPrinterId: z.string().optional(),
  printerConfigs: z.array(printerConfigSchema).optional(),
  printSections: z.array(printSectionSchema).optional(),
  aiInvoiceEntryEnabled: z.boolean().optional(),
  aiInvoiceApiKey: z.string().optional(),
  showEditingMessageToUser: z.boolean().optional(),
});

const posFormSchema = formSchema.pick({
  defaultPosVisaBankAccountId: true,
  restaurantPosEnabled: true,
  restaurantPosAreasEnabled: true,
  restaurantPosSplitBillEnabled: true,
  restaurantPosMergeTablesEnabled: true,
  restaurantPosTransferItemEnabled: true,
  restaurantPosPartialCheckoutEnabled: true,
  restaurantPosKotEnabled: true,
  restaurantPosAutoReserveMinutes: true,
  restaurantPosDefaultGuestCount: true,
  restaurantPosAreas: true,
  restaurantPosTables: true,
  posShowSuppliers: true,
  salesRepsEnabled: true,
  posShowItemNumberColumn: true,
  posShowUnitColumn: true,
  posShowDescriptionColumn: true,
  posShowBarcodeColumn: true,
  posShowQuantityColumn: true,
  posShowPriceColumn: true,
  posShowItemDiscountColumn: true,
  posShowBonusColumn: true,
  posShowTotalColumn: true,
  posShowActionsColumn: true,
  posShowWeighedItemsButton: true,
});

type FormValues = z.infer<typeof formSchema>;

interface Currency {
  id: string;
  code: string;
  symbol: string;
}

interface Warehouse {
  id: string;
  name: string;
}

interface Bank {
  id: string;
  name: string;
}

interface GeneralSettings {
  appName?: string;
  appCurrency?: string;
  appLogoUrl?: string;
  deploymentMode?: string;
  businessMode?: string;
  documentStoragePath?: string;
  approvedIpAddress?: string;
  defaultPosVisaBankAccountId?: string;
  restaurantPosEnabled?: boolean;
  restaurantPosAreasEnabled?: boolean;
  restaurantPosSplitBillEnabled?: boolean;
  restaurantPosMergeTablesEnabled?: boolean;
  restaurantPosTransferItemEnabled?: boolean;
  restaurantPosPartialCheckoutEnabled?: boolean;
  restaurantPosKotEnabled?: boolean;
  restaurantPosAutoReserveMinutes?: number;
  restaurantPosDefaultGuestCount?: number;
  restaurantPosAreas?: Array<{ id: string; name: string; sortOrder: number }>;
  restaurantPosTables?: Array<{ id: string; name: string; areaId?: string; seats: number }>;
  posShowSuppliers?: boolean;
  salesRepsEnabled?: boolean;
  posShowItemNumberColumn?: boolean;
  posShowUnitColumn?: boolean;
  posShowDescriptionColumn?: boolean;
  posShowBarcodeColumn?: boolean;
  posShowQuantityColumn?: boolean;
  posShowPriceColumn?: boolean;
  posShowItemDiscountColumn?: boolean;
  posShowBonusColumn?: boolean;
  posShowTotalColumn?: boolean;
  posShowActionsColumn?: boolean;
  posShowWeighedItemsButton?: boolean;
  warehousesEnabled?: boolean;
  allowOutOfStockSales?: boolean;
  blockSalesBelowCost?: boolean;
  salesShipmentWorkflowEnabled?: boolean;
  purchaseShipmentWorkflowEnabled?: boolean;
  purchaseShelfTaskEnabled?: boolean;
  purchasePostingFollowupEnabled?: boolean;
  defaultWarehouseId?: string;
  defaultPurchaseWarehouseId?: string;
  defaultTaxMethod?: string;
  defaultInvoiceTaxRate?: number;
  defaultLineTaxRate?: number;
  fxAutoUpdateRates?: boolean;
  fxLockBaseCurrency?: boolean;
  scaleMode?: string;
  scaleDecimalSeparator?: string;
  scaleReadRegex?: string;
  scaleHidVendorId?: string;
  scaleHidProductId?: string;
  scaleSerialPort?: string;
  scaleSerialBaudRate?: number;
  printHeaderRightText?: string;
  printHeaderCenterText?: string;
  printHeaderLeftText?: string;
  printHeaderText?: string;
  printFooterText?: string;
  customPrintersEnabled?: boolean;
  printerAutoPrintEnabled?: boolean;
  printTransportMode?: string;
  defaultCustomerReceiptPrinterId?: string;
  printerConfigs?: Array<{ id: string; name: string; ipAddress: string; port: number }>;
  printSections?: Array<{ id: string; name: string; printerId: string; autoPrint: boolean }>;
  aiInvoiceEntryEnabled?: boolean;
  aiInvoiceApiKey?: string;
  showEditingMessageToUser?: boolean;
}

interface GeneralSettingsFormProps {
  currentSettings: GeneralSettings;
  sectionMode?: "system" | "pos";
  currencies: Currency[];
  warehouses: Warehouse[];
  banks: Bank[];
  currentApprovedIp?: string;
  detectedIp?: string;
  dbFiles?: string[];
  backupIds?: string[];
  t?: Record<string, string>;
  tGlobal?: Record<string, string>;
  defaultCurrency?: Currency;
  currentCurrencyCode?: string;
  formId?: string;
}

const toBoolean = (value: unknown, defaultValue = false): boolean => {
  if (value === undefined || value === null || value === "") return defaultValue;
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value === 1;
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (["true", "1", "yes", "on"].includes(normalized)) return true;
    if (["false", "0", "no", "off"].includes(normalized)) return false;
  }
  return defaultValue;
};

export default function GeneralSettingsForm({
  currentSettings: settings,
  sectionMode = "system",
  currencies,
  warehouses,
  banks,
  detectedIp,
  formId,
}: GeneralSettingsFormProps) {
  const { toast } = useToast();
  const [isPending, startTransition] = useTransition();

  const form = useForm<FormValues>({
    resolver: zodResolver(sectionMode === "pos" ? posFormSchema : formSchema),
    defaultValues: {
      appName: settings.appName ?? "",
      appCurrency: settings.appCurrency ?? "",
      appLogoUrl: settings.appLogoUrl ?? "",
      deploymentMode: settings.deploymentMode ?? "local",
      businessMode: settings.businessMode ?? "inventory",
      documentStoragePath: settings.documentStoragePath ?? "uploads/",
      approvedIpAddress: settings.approvedIpAddress ?? "",
      defaultPosVisaBankAccountId: settings.defaultPosVisaBankAccountId ?? "",
      restaurantPosEnabled: toBoolean(settings.restaurantPosEnabled, false),
      restaurantPosAreasEnabled: toBoolean(settings.restaurantPosAreasEnabled, true),
      restaurantPosSplitBillEnabled: toBoolean(settings.restaurantPosSplitBillEnabled, true),
      restaurantPosMergeTablesEnabled: toBoolean(settings.restaurantPosMergeTablesEnabled, true),
      restaurantPosTransferItemEnabled: toBoolean(settings.restaurantPosTransferItemEnabled, true),
      restaurantPosPartialCheckoutEnabled: toBoolean(settings.restaurantPosPartialCheckoutEnabled, true),
      restaurantPosKotEnabled: toBoolean(settings.restaurantPosKotEnabled, true),
      restaurantPosAutoReserveMinutes: Number(settings.restaurantPosAutoReserveMinutes ?? 90),
      restaurantPosDefaultGuestCount: Number(settings.restaurantPosDefaultGuestCount ?? 2),
      restaurantPosAreas: settings.restaurantPosAreas ?? [],
      restaurantPosTables: settings.restaurantPosTables ?? [],
      posShowSuppliers: toBoolean(settings.posShowSuppliers, true),
      salesRepsEnabled: toBoolean(settings.salesRepsEnabled, true),
      posShowItemNumberColumn: toBoolean(settings.posShowItemNumberColumn, true),
      posShowUnitColumn: toBoolean(settings.posShowUnitColumn, true),
      posShowDescriptionColumn: toBoolean(settings.posShowDescriptionColumn, true),
      posShowBarcodeColumn: toBoolean(settings.posShowBarcodeColumn, true),
      posShowQuantityColumn: toBoolean(settings.posShowQuantityColumn, true),
      posShowPriceColumn: toBoolean(settings.posShowPriceColumn, true),
      posShowItemDiscountColumn: toBoolean(settings.posShowItemDiscountColumn, true),
      posShowBonusColumn: toBoolean(settings.posShowBonusColumn, true),
      posShowTotalColumn: toBoolean(settings.posShowTotalColumn, true),
      posShowActionsColumn: toBoolean(settings.posShowActionsColumn, true),
      posShowWeighedItemsButton: toBoolean(settings.posShowWeighedItemsButton, false),
      warehousesEnabled: toBoolean(settings.warehousesEnabled, false),
      allowOutOfStockSales: toBoolean(settings.allowOutOfStockSales, true),
      blockSalesBelowCost: toBoolean(settings.blockSalesBelowCost, false),
      salesShipmentWorkflowEnabled: toBoolean(settings.salesShipmentWorkflowEnabled, false),
      purchaseShipmentWorkflowEnabled: toBoolean(settings.purchaseShipmentWorkflowEnabled, false),
      purchaseShelfTaskEnabled: toBoolean(settings.purchaseShelfTaskEnabled, false),
      purchasePostingFollowupEnabled: toBoolean(settings.purchasePostingFollowupEnabled, false),
      defaultWarehouseId: settings.defaultWarehouseId ?? "",
      defaultPurchaseWarehouseId: settings.defaultPurchaseWarehouseId ?? "",
      defaultTaxMethod: settings.defaultTaxMethod ?? "none",
      defaultInvoiceTaxRate: settings.defaultInvoiceTaxRate ?? 0,
      defaultLineTaxRate: settings.defaultLineTaxRate ?? 0,
      fxAutoUpdateRates: settings.fxAutoUpdateRates ?? false,
      fxLockBaseCurrency: settings.fxLockBaseCurrency ?? false,
      scaleMode: settings.scaleMode ?? "disabled",
      scaleDecimalSeparator: settings.scaleDecimalSeparator ?? ".",
      scaleReadRegex: settings.scaleReadRegex ?? "",
      scaleHidVendorId: settings.scaleHidVendorId ?? "",
      scaleHidProductId: settings.scaleHidProductId ?? "",
      scaleSerialPort: settings.scaleSerialPort ?? "",
      scaleSerialBaudRate: settings.scaleSerialBaudRate ?? 9600,
      printHeaderRightText: settings.printHeaderRightText ?? "",
      printHeaderCenterText: settings.printHeaderCenterText ?? "",
      printHeaderLeftText: settings.printHeaderLeftText ?? "",
      printHeaderText: settings.printHeaderText ?? "",
      printFooterText: settings.printFooterText ?? "",
      customPrintersEnabled: toBoolean(settings.customPrintersEnabled, false),
      printerAutoPrintEnabled: toBoolean(settings.printerAutoPrintEnabled, false),
      printTransportMode: settings.printTransportMode ?? "usb",
      defaultCustomerReceiptPrinterId: settings.defaultCustomerReceiptPrinterId ?? "",
      printerConfigs: settings.printerConfigs ?? [],
      printSections: settings.printSections ?? [],
      aiInvoiceEntryEnabled: toBoolean(settings.aiInvoiceEntryEnabled, false),
      aiInvoiceApiKey: settings.aiInvoiceApiKey ?? "",
      showEditingMessageToUser: toBoolean(settings.showEditingMessageToUser, true),
    },
  });

  const { fields: printerFields, append: appendPrinter, remove: removePrinter } = useFieldArray({
    control: form.control,
    name: "printerConfigs",
  });

  const { fields: sectionFields, append: appendSection, remove: removeSection } = useFieldArray({
    control: form.control,
    name: "printSections",
  });

  const { fields: areaFields, append: appendArea, remove: removeArea } = useFieldArray({
    control: form.control,
    name: "restaurantPosAreas",
  });

  const { fields: tableFields, append: appendTable, remove: removeTable } = useFieldArray({
    control: form.control,
    name: "restaurantPosTables",
  });

  const warehousesEnabled = form.watch("warehousesEnabled");
  const scaleMode = form.watch("scaleMode");
  const customPrintersEnabled = form.watch("customPrintersEnabled");
  const restaurantPosEnabled = form.watch("restaurantPosEnabled");
  const aiInvoiceEntryEnabled = form.watch("aiInvoiceEntryEnabled");
  const defaultTaxMethod = form.watch("defaultTaxMethod");

  function onSubmit(values: FormValues) {
    startTransition(async () => {
      const result = await handleUpdateGeneralSettings(values as Record<string, unknown>);
      if (result.success) {
        toast({ title: "✅ تم الحفظ بنجاح", description: "تم تحديث إعدادات نقطة البيع والنظام." });
      } else {
        toast({ title: "❌ فشل الحفظ", description: result.error ?? "حدث خطأ غير متوقع.", variant: "destructive" });
        console.error('[GeneralSettingsForm] save failed:', result.error);
      }
    });
  }

  const renderPosSettingsSection = () => (
    <div className="space-y-4">
      <h3 className="font-semibold">إعدادات نقطة البيع (POS)</h3>
      <FormField control={form.control} name="defaultPosVisaBankAccountId" render={({ field }) => (
        <FormItem>
          <FormLabel>البنك الافتراضي لمدفوعات البطاقة</FormLabel>
          <Select onValueChange={(v) => field.onChange(v === "__none__" ? "" : v)} value={field.value || "__none__"}>
            <FormControl>
              <SelectTrigger><SelectValue placeholder="بدون تحديد" /></SelectTrigger>
            </FormControl>
            <SelectContent>
              <SelectItem value="__none__">بدون تحديد</SelectItem>
              {banks.map((b) => (
                <SelectItem key={b.id} value={b.id}>{b.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <FormMessage />
        </FormItem>
      )} />
      <div className="space-y-2">
        <FormField control={form.control} name="restaurantPosEnabled" render={({ field }) => (
          <FormItem className="flex flex-row items-center gap-2">
            <FormControl>
              <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
            </FormControl>
            <FormLabel className="font-normal cursor-pointer">تفعيل وضع المطعم (Restaurant POS)</FormLabel>
          </FormItem>
        )} />
      </div>
      {restaurantPosEnabled && (
        <div className="space-y-3 rounded-md border p-3">
          <div className="text-sm font-medium">إعدادات تشغيل المطعم</div>
          <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
            <FormField control={form.control} name="restaurantPosAreasEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل المناطق/القاعات</FormLabel>
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosKotEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل طباعة تذاكر المطبخ KOT</FormLabel>
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosSplitBillEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل تقسيم الفاتورة (Split Bill)</FormLabel>
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosMergeTablesEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل دمج الطاولات (Merge Tables)</FormLabel>
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosTransferItemEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل نقل الأصناف بين الطاولات</FormLabel>
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosPartialCheckoutEnabled" render={({ field }) => (
              <FormItem className="flex flex-row items-center gap-2">
                <FormControl>
                  <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                </FormControl>
                <FormLabel className="font-normal cursor-pointer">تفعيل الإقفال الجزئي (Partial Checkout)</FormLabel>
              </FormItem>
            )} />
          </div>
          <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
            <FormField control={form.control} name="restaurantPosAutoReserveMinutes" render={({ field }) => (
              <FormItem>
                <FormLabel>مدة الحجز التلقائي للطاولة (بالدقائق)</FormLabel>
                <FormControl><Input type="number" min={0} max={720} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />
            <FormField control={form.control} name="restaurantPosDefaultGuestCount" render={({ field }) => (
              <FormItem>
                <FormLabel>عدد الضيوف الافتراضي</FormLabel>
                <FormControl><Input type="number" min={1} max={100} {...field} /></FormControl>
                <FormMessage />
              </FormItem>
            )} />
          </div>
          <div className="space-y-2 rounded-md border p-3">
            <div className="flex items-center justify-between">
              <div className="text-sm font-medium">المناطق/القاعات</div>
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => appendArea({ id: createClientId(), name: "", sortOrder: areaFields.length })}
              >
                <PlusCircle className="me-1 h-4 w-4" />
                إضافة منطقة
              </Button>
            </div>
            {areaFields.length === 0 && (
              <div className="text-xs text-muted-foreground">لا توجد مناطق معرفة.</div>
            )}
            <div className="space-y-2">
              {areaFields.map((field, index) => (
                <div key={field.id} className="grid grid-cols-12 gap-2">
                  <div className="col-span-7">
                    <FormField control={form.control} name={`restaurantPosAreas.${index}.name`} render={({ field }) => (
                      <FormItem>
                        <FormControl><Input placeholder="اسم المنطقة" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                  <div className="col-span-3">
                    <FormField control={form.control} name={`restaurantPosAreas.${index}.sortOrder`} render={({ field }) => (
                      <FormItem>
                        <FormControl><Input type="number" min={0} placeholder="ترتيب" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                  <div className="col-span-2">
                    <Button type="button" variant="ghost" size="icon" onClick={() => removeArea(index)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="space-y-2 rounded-md border p-3">
            <div className="flex items-center justify-between">
              <div className="text-sm font-medium">الطاولات</div>
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => appendTable({ id: createClientId(), name: "", areaId: "", seats: 4 })}
              >
                <PlusCircle className="me-1 h-4 w-4" />
                إضافة طاولة
              </Button>
            </div>
            {tableFields.length === 0 && (
              <div className="text-xs text-muted-foreground">لا توجد طاولات معرفة.</div>
            )}
            <div className="space-y-2">
              {tableFields.map((field, index) => (
                <div key={field.id} className="grid grid-cols-12 gap-2">
                  <div className="col-span-4">
                    <FormField control={form.control} name={`restaurantPosTables.${index}.name`} render={({ field }) => (
                      <FormItem>
                        <FormControl><Input placeholder="اسم الطاولة" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                  <div className="col-span-4">
                    <FormField control={form.control} name={`restaurantPosTables.${index}.areaId`} render={({ field }) => (
                      <FormItem>
                        <Select
                          onValueChange={(value) => field.onChange(value === NO_RESTAURANT_AREA_VALUE ? "" : value)}
                          value={field.value || NO_RESTAURANT_AREA_VALUE}
                        >
                          <FormControl>
                            <SelectTrigger><SelectValue placeholder="المنطقة" /></SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value={NO_RESTAURANT_AREA_VALUE}>بدون منطقة</SelectItem>
                            {areaFields.map((areaField, areaIndex) => {
                              const areaName = String(form.getValues(`restaurantPosAreas.${areaIndex}.name`) || "").trim() || `منطقة ${areaIndex + 1}`;
                              return (
                                <SelectItem key={areaField.id} value={String(areaField.id)}>{areaName}</SelectItem>
                              );
                            })}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                  <div className="col-span-2">
                    <FormField control={form.control} name={`restaurantPosTables.${index}.seats`} render={({ field }) => (
                      <FormItem>
                        <FormControl><Input type="number" min={1} max={20} placeholder="المقاعد" {...field} /></FormControl>
                        <FormMessage />
                      </FormItem>
                    )} />
                  </div>
                  <div className="col-span-2">
                    <Button type="button" variant="ghost" size="icon" onClick={() => removeTable(index)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
      <div className="space-y-2">
        <FormField control={form.control} name="posShowSuppliers" render={({ field }) => (
          <FormItem className="flex flex-row items-center gap-2">
            <FormControl>
              <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
            </FormControl>
            <FormLabel className="font-normal cursor-pointer">إظهار الموردين في نقطة البيع</FormLabel>
          </FormItem>
        )} />
        <FormField control={form.control} name="salesRepsEnabled" render={({ field }) => (
          <FormItem className="flex flex-row items-center gap-2">
            <FormControl>
              <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
            </FormControl>
            <FormLabel className="font-normal cursor-pointer">تفعيل مناديبي المبيعات</FormLabel>
          </FormItem>
        )} />
      </div>
      <div className="space-y-2 rounded-md border p-3">
        <div className="text-sm font-medium">الأعمدة المعروضة في جدول الأصناف</div>
        <div className="grid grid-cols-1 gap-2 md:grid-cols-2">
          <FormField control={form.control} name="posShowItemNumberColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">رقم الصنف</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowUnitColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">الوحدة</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowDescriptionColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">الوصف</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowBarcodeColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">الباركود</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowQuantityColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">الكمية</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowPriceColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">السعر</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowItemDiscountColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">خصم الصنف</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowBonusColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">بونص</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowTotalColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">الإجمالي</FormLabel>
            </FormItem>
          )} />
          <FormField control={form.control} name="posShowActionsColumn" render={({ field }) => (
            <FormItem className="flex flex-row items-center gap-2">
              <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
              <FormLabel className="font-normal cursor-pointer">العمليات</FormLabel>
            </FormItem>
          )} />
        </div>
      </div>
      <div className="space-y-2 rounded-md border p-3">
        <div className="text-sm font-medium">أزرار إضافية</div>
        <FormField control={form.control} name="posShowWeighedItemsButton" render={({ field }) => (
          <FormItem className="flex flex-row items-center gap-2">
            <FormControl><Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} /></FormControl>
            <FormLabel className="font-normal cursor-pointer">إظهار زر أصناف الميزان ⚖️</FormLabel>
          </FormItem>
        )} />
      </div>
    </div>
  );

  if (sectionMode === "pos") {
    return (
      <Card>
        <CardHeader>
          <CardTitle>إعدادات نقطة البيع</CardTitle>
          <CardDescription>إدارة إعدادات POS الأساسية.</CardDescription>
        </CardHeader>
        <CardContent>
          <Form {...form}>
            <form id={formId} onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              {renderPosSettingsSection()}
            </form>
          </Form>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>الإعدادات العامة</CardTitle>
        <CardDescription>إدارة الإعدادات العامة للتطبيق.</CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form id={formId} onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">

            {/* هوية التطبيق */}
            <div className="space-y-4">
              <h3 className="font-semibold">هوية التطبيق</h3>
              <FormField control={form.control} name="appName" render={({ field }) => (
                <FormItem>
                  <FormLabel>اسم التطبيق</FormLabel>
                  <FormControl><Input placeholder="StaffTrack Pro" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
              <FormField control={form.control} name="appCurrency" render={({ field }) => (
                <FormItem>
                  <FormLabel>عملة التطبيق</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder="اختر العملة" /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {currencies.map((c) => (
                        <SelectItem key={c.id} value={c.code}>{c.code} - {c.symbol}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )} />
              <FormField control={form.control} name="appLogoUrl" render={({ field }) => (
                <FormItem>
                  <FormLabel>رابط شعار التطبيق</FormLabel>
                  <FormControl><Input placeholder="https://example.com/logo.png" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
            </div>

            {/* بيئة النشر ونمط النشاط */}
            <div className="space-y-4">
              <h3 className="font-semibold">بيئة النشر ونمط النشاط</h3>
              <div className="grid grid-cols-2 gap-4">
                <FormField control={form.control} name="deploymentMode" render={({ field }) => (
                  <FormItem>
                    <FormLabel>نمط النشر</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger><SelectValue placeholder="اختر النمط" /></SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="local">محلي (Local)</SelectItem>
                        <SelectItem value="cloud">سحابي (Cloud)</SelectItem>
                        <SelectItem value="hybrid">هجين (Hybrid)</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )} />
                <FormField control={form.control} name="businessMode" render={({ field }) => (
                  <FormItem>
                    <FormLabel>نمط النشاط</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger><SelectValue placeholder="اختر النمط" /></SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="inventory">مخزني / تجاري</SelectItem>
                        <SelectItem value="service">خدمي</SelectItem>
                        <SelectItem value="real-estate">عقاري</SelectItem>
                        <SelectItem value="hybrid">هجين (مخزني + عقاري)</SelectItem>
                        <SelectItem value="mixed">مختلط</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )} />
              </div>
              <FormField control={form.control} name="documentStoragePath" render={({ field }) => (
                <FormItem>
                  <FormLabel>مسار تخزين الملفات</FormLabel>
                  <FormControl><Input placeholder="uploads/" {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
            </div>

            {/* عناوين IP المسموح بها */}
            <div className="space-y-4">
              <h3 className="font-semibold">عناوين IP المسموح بها</h3>
              <FormField control={form.control} name="approvedIpAddress" render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <div className="space-y-2">
                      <Textarea placeholder={"192.168.1.1\n192.168.1.2"} rows={3} {...field} />
                      {detectedIp && (
                        <Button type="button" variant="outline" size="sm" onClick={() => {
                          const current = field.value ?? "";
                          const lines = current.split("\n").filter(Boolean);
                          if (!lines.includes(detectedIp)) {
                            field.onChange([...lines, detectedIp].join("\n"));
                          }
                        }}>
                          استخدم IP الحالي <span className="text-muted-foreground mr-1">({detectedIp})</span>
                        </Button>
                      )}
                    </div>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )} />
            </div>

            {/* المخزون والمستودعات */}
            <div className="space-y-4">
              <h3 className="font-semibold">المخزون والمستودعات</h3>
              <div className="space-y-2">
                <FormField control={form.control} name="warehousesEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل المستودعات المتعددة</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="allowOutOfStockSales" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">السماح بالبيع بدون مخزون</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="blockSalesBelowCost" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">منع البيع بأقل من سعر التكلفة</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="salesShipmentWorkflowEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل سير عمل شحن المبيعات</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="purchaseShipmentWorkflowEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل سير عمل شحن المشتريات</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="purchaseShelfTaskEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل مهمة رف المشتريات</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="purchasePostingFollowupEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل متابعة ترحيل المشتريات</FormLabel>
                  </FormItem>
                )} />
              </div>
              {warehousesEnabled && (
                <div className="grid grid-cols-2 gap-4 pt-2">
                  <FormField control={form.control} name="defaultWarehouseId" render={({ field }) => (
                    <FormItem>
                      <FormLabel>المستودع الافتراضي للمبيعات</FormLabel>
                      <Select onValueChange={(v) => field.onChange(v === "__none__" ? "" : v)} value={field.value || "__none__"}>
                        <FormControl>
                          <SelectTrigger><SelectValue placeholder="اختر المستودع" /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="__none__">بدون تحديد</SelectItem>
                          {warehouses.map((w) => (
                            <SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )} />
                  <FormField control={form.control} name="defaultPurchaseWarehouseId" render={({ field }) => (
                    <FormItem>
                      <FormLabel>المستودع الافتراضي للمشتريات</FormLabel>
                      <Select onValueChange={(v) => field.onChange(v === "__none__" ? "" : v)} value={field.value || "__none__"}>
                        <FormControl>
                          <SelectTrigger><SelectValue placeholder="اختر المستودع" /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="__none__">بدون تحديد</SelectItem>
                          {warehouses.map((w) => (
                            <SelectItem key={w.id} value={w.id}>{w.name}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )} />
                </div>
              )}
            </div>

            {/* إعدادات الضريبة */}
            <div className="space-y-4">
              <h3 className="font-semibold">إعدادات الضريبة</h3>
              <FormField control={form.control} name="defaultTaxMethod" render={({ field }) => (
                <FormItem>
                  <FormLabel>طريقة الضريبة الافتراضية</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder="اختر الطريقة" /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="none">بدون ضريبة</SelectItem>
                      <SelectItem value="inclusive">شاملة للضريبة</SelectItem>
                      <SelectItem value="exclusive">غير شاملة للضريبة</SelectItem>
                      <SelectItem value="per_line">لكل سطر</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )} />
              {defaultTaxMethod && defaultTaxMethod !== "none" && defaultTaxMethod !== "per_line" && (
                <FormField control={form.control} name="defaultInvoiceTaxRate" render={({ field }) => (
                  <FormItem>
                    <FormLabel>نسبة الضريبة على الفاتورة (%)</FormLabel>
                    <FormControl><Input type="number" step="0.01" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
              )}
              {defaultTaxMethod === "per_line" && (
                <FormField control={form.control} name="defaultLineTaxRate" render={({ field }) => (
                  <FormItem>
                    <FormLabel>نسبة الضريبة على السطر (%)</FormLabel>
                    <FormControl><Input type="number" step="0.01" {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
              )}
            </div>

            {/* أسعار الصرف */}
            <div className="space-y-4">
              <h3 className="font-semibold">أسعار الصرف (FX)</h3>
              <div className="space-y-2">
                <FormField control={form.control} name="fxAutoUpdateRates" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تحديث أسعار الصرف تلقائياً</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="fxLockBaseCurrency" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">قفل العملة الأساسية</FormLabel>
                  </FormItem>
                )} />
              </div>
            </div>

            {/* إعدادات الميزان */}
            <div className="space-y-4">
              <h3 className="font-semibold">إعدادات الميزان</h3>
              <FormField control={form.control} name="scaleMode" render={({ field }) => (
                <FormItem>
                  <FormLabel>وضع الميزان</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <FormControl>
                      <SelectTrigger><SelectValue placeholder="اختر الوضع" /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="disabled">معطل</SelectItem>
                      <SelectItem value="hid">HID (USB)</SelectItem>
                      <SelectItem value="serial">Serial (COM)</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )} />
              {scaleMode && scaleMode !== "disabled" && (
                <>
                  <FormField control={form.control} name="scaleDecimalSeparator" render={({ field }) => (
                    <FormItem>
                      <FormLabel>فاصل الكسور العشرية</FormLabel>
                      <Select onValueChange={field.onChange} value={field.value}>
                        <FormControl>
                          <SelectTrigger><SelectValue /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value=".">نقطة (.)</SelectItem>
                          <SelectItem value=",">,فاصلة (</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )} />
                  <FormField control={form.control} name="scaleReadRegex" render={({ field }) => (
                    <FormItem>
                      <FormLabel>تعبير قراءة الميزان (Regex)</FormLabel>
                      <FormControl><Input placeholder="(\d+\.?\d*)" {...field} /></FormControl>
                      <FormMessage />
                    </FormItem>
                  )} />
                  {scaleMode === "hid" && (
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="scaleHidVendorId" render={({ field }) => (
                        <FormItem>
                          <FormLabel>Vendor ID (HID)</FormLabel>
                          <FormControl><Input placeholder="0x0000" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="scaleHidProductId" render={({ field }) => (
                        <FormItem>
                          <FormLabel>Product ID (HID)</FormLabel>
                          <FormControl><Input placeholder="0x0000" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  )}
                  {scaleMode === "serial" && (
                    <div className="grid grid-cols-2 gap-4">
                      <FormField control={form.control} name="scaleSerialPort" render={({ field }) => (
                        <FormItem>
                          <FormLabel>منفذ Serial</FormLabel>
                          <FormControl><Input placeholder="COM1" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                      <FormField control={form.control} name="scaleSerialBaudRate" render={({ field }) => (
                        <FormItem>
                          <FormLabel>Baud Rate</FormLabel>
                          <FormControl><Input type="number" {...field} /></FormControl>
                          <FormMessage />
                        </FormItem>
                      )} />
                    </div>
                  )}
                </>
              )}
            </div>

            {/* رأس وتذييل الطباعة */}
            <div className="space-y-4">
              <h3 className="font-semibold">رأس وتذييل الطباعة</h3>
              <div className="grid grid-cols-3 gap-4">
                <FormField control={form.control} name="printHeaderRightText" render={({ field }) => (
                  <FormItem>
                    <FormLabel>رأس الصفحة (يمين)</FormLabel>
                    <FormControl><Textarea rows={3} {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
                <FormField control={form.control} name="printHeaderCenterText" render={({ field }) => (
                  <FormItem>
                    <FormLabel>رأس الصفحة (وسط)</FormLabel>
                    <FormControl><Textarea rows={3} {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
                <FormField control={form.control} name="printHeaderLeftText" render={({ field }) => (
                  <FormItem>
                    <FormLabel>رأس الصفحة (يسار)</FormLabel>
                    <FormControl><Textarea rows={3} {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
              </div>
              <FormField control={form.control} name="printHeaderText" render={({ field }) => (
                <FormItem>
                  <FormLabel>نص رأس الطباعة (كامل)</FormLabel>
                  <FormControl><Textarea rows={3} {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
              <FormField control={form.control} name="printFooterText" render={({ field }) => (
                <FormItem>
                  <FormLabel>نص تذييل الطباعة</FormLabel>
                  <FormControl><Textarea rows={3} {...field} /></FormControl>
                  <FormMessage />
                </FormItem>
              )} />
            </div>

            {/* إعدادات الطباعة */}
            <div className="space-y-4">
              <h3 className="font-semibold">إعدادات الطباعة</h3>
              <div className="space-y-2">
                <FormField control={form.control} name="customPrintersEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل الطابعات المخصصة</FormLabel>
                  </FormItem>
                )} />
                <FormField control={form.control} name="printerAutoPrintEnabled" render={({ field }) => (
                  <FormItem className="flex flex-row items-center gap-2">
                    <FormControl>
                      <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                    </FormControl>
                    <FormLabel className="font-normal cursor-pointer">تفعيل الطباعة التلقائية</FormLabel>
                  </FormItem>
                )} />
              </div>
              <FormField control={form.control} name="printTransportMode" render={({ field }) => (
                <FormItem>
                  <FormLabel>وضع نقل الطباعة</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value}>
                    <FormControl>
                      <SelectTrigger><SelectValue /></SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="usb">USB</SelectItem>
                      <SelectItem value="network">شبكة (Network)</SelectItem>
                      <SelectItem value="bluetooth">بلوتوث (Bluetooth)</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )} />
              {customPrintersEnabled && (
                <>
                  <FormField control={form.control} name="defaultCustomerReceiptPrinterId" render={({ field }) => (
                    <FormItem>
                      <FormLabel>طابعة إيصال العميل الافتراضية</FormLabel>
                      <Select onValueChange={(v) => field.onChange(v === "__none__" ? "" : v)} value={field.value || "__none__"}>
                        <FormControl>
                          <SelectTrigger><SelectValue placeholder="اختر الطابعة" /></SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="__none__">بدون تحديد</SelectItem>
                          {printerFields.map((p) => (
                            <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )} />

                  {/* قائمة الطابعات */}
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <h4 className="text-sm font-medium">قائمة الطابعات</h4>
                      <Button type="button" variant="outline" size="sm" onClick={() =>
                        appendPrinter({ id: crypto.randomUUID(), name: "", ipAddress: "", port: 9100 })
                      }>
                        <PlusCircle className="h-4 w-4 ml-1" /> إضافة طابعة
                      </Button>
                    </div>
                    {printerFields.map((field, index) => (
                      <div key={field.id} className="grid grid-cols-4 gap-2 items-end border rounded p-3">
                        <FormField control={form.control} name={`printerConfigs.${index}.name`} render={({ field }) => (
                          <FormItem>
                            <FormLabel>الاسم</FormLabel>
                            <FormControl><Input {...field} /></FormControl>
                          </FormItem>
                        )} />
                        <FormField control={form.control} name={`printerConfigs.${index}.ipAddress`} render={({ field }) => (
                          <FormItem>
                            <FormLabel>عنوان IP</FormLabel>
                            <FormControl><Input {...field} /></FormControl>
                          </FormItem>
                        )} />
                        <FormField control={form.control} name={`printerConfigs.${index}.port`} render={({ field }) => (
                          <FormItem>
                            <FormLabel>المنفذ</FormLabel>
                            <FormControl><Input type="number" {...field} /></FormControl>
                          </FormItem>
                        )} />
                        <Button type="button" variant="ghost" size="icon" onClick={() => removePrinter(index)}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    ))}
                  </div>

                  {/* أقسام الطباعة */}
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <h4 className="text-sm font-medium">أقسام الطباعة</h4>
                      <Button type="button" variant="outline" size="sm" onClick={() =>
                        appendSection({ id: crypto.randomUUID(), name: "", printerId: "", autoPrint: false })
                      }>
                        <PlusCircle className="h-4 w-4 ml-1" /> إضافة قسم
                      </Button>
                    </div>
                    {sectionFields.map((field, index) => (
                      <div key={field.id} className="grid grid-cols-4 gap-2 items-end border rounded p-3">
                        <FormField control={form.control} name={`printSections.${index}.name`} render={({ field }) => (
                          <FormItem>
                            <FormLabel>اسم القسم</FormLabel>
                            <FormControl><Input {...field} /></FormControl>
                          </FormItem>
                        )} />
                        <FormField control={form.control} name={`printSections.${index}.printerId`} render={({ field }) => (
                          <FormItem>
                            <FormLabel>الطابعة</FormLabel>
                            <Select onValueChange={field.onChange} value={field.value}>
                              <FormControl>
                                <SelectTrigger><SelectValue placeholder="اختر" /></SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                {printerFields.map((p) => (
                                  <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </FormItem>
                        )} />
                        <FormField control={form.control} name={`printSections.${index}.autoPrint`} render={({ field }) => (
                          <FormItem className="flex items-center gap-2 pt-5">
                            <FormControl>
                              <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                            </FormControl>
                            <FormLabel className="font-normal">طباعة تلقائية</FormLabel>
                          </FormItem>
                        )} />
                        <Button type="button" variant="ghost" size="icon" onClick={() => removeSection(index)}>
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>

            {/* الذكاء الاصطناعي */}
            <div className="space-y-4">
              <h3 className="font-semibold">الذكاء الاصطناعي</h3>
              <FormField control={form.control} name="aiInvoiceEntryEnabled" render={({ field }) => (
                <FormItem className="flex flex-row items-center gap-2">
                  <FormControl>
                    <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                  </FormControl>
                  <FormLabel className="font-normal cursor-pointer">تفعيل إدخال الفواتير بالذكاء الاصطناعي</FormLabel>
                </FormItem>
              )} />
              {aiInvoiceEntryEnabled && (
                <FormField control={form.control} name="aiInvoiceApiKey" render={({ field }) => (
                  <FormItem>
                    <FormLabel>مفتاح API للذكاء الاصطناعي</FormLabel>
                    <FormControl><Input type="password" placeholder="sk-..." {...field} /></FormControl>
                    <FormMessage />
                  </FormItem>
                )} />
              )}
            </div>

            {/* الأمان */}
            <div className="space-y-4">
              <h3 className="font-semibold">الأمان</h3>
              <FormField control={form.control} name="showEditingMessageToUser" render={({ field }) => (
                <FormItem className="flex flex-row items-center gap-2">
                  <FormControl>
                    <Checkbox checked={field.value === true} onCheckedChange={(checked) => field.onChange(checked === true)} />
                  </FormControl>
                  <FormLabel className="font-normal cursor-pointer">إظهار رسالة التحرير للمستخدم</FormLabel>
                </FormItem>
              )} />
            </div>

          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
