/**
 * Create Appointment Modal Component
 * Premium modal for creating manual appointments with customer selection/creation
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import {
  X,
  User,
  Phone,
  Mail,
  Calendar,
  Clock,
  FileText,
  Search,
  ChevronDown,
  Loader2,
  DollarSign,
  UserPlus,
  Briefcase,
  Layers,
} from "lucide-react";
import { useSectorFields } from "@/hooks/useSectorFields";
import { SectorFieldsForm } from "@/components/SectorFieldsForm";

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

interface CreateAppointmentModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  preselectedCustomer?: Customer | null;
  userIndustry?: string | null;
}

// Helper to get CSRF token from cookies
function getCSRFToken(): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(/csrf-token=([^;]+)/);
  return match ? match[1] : null;
}

interface AppointmentType {
  id: string;
  nameEn: string;
  nameAr: string;
  duration: number;
  price: number | null;
}

export default function CreateAppointmentModal({
  lang,
  isOpen,
  onClose,
  onSuccess,
  preselectedCustomer,
  userIndustry,
}: CreateAppointmentModalProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;

  // Customer selection state
  const [customerMode, setCustomerMode] = useState<"existing" | "new">("new");
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(
    null,
  );
  const [customerSearch, setCustomerSearch] = useState("");
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
  const [loadingCustomers, setLoadingCustomers] = useState(false);

  // Form state
  const [formData, setFormData] = useState({
    // Customer info (for new customer mode)
    customerName: "",
    customerPhone: "",
    customerEmail: "",
    // Appointment info
    service: "",
    customService: "",
    appointmentDate: "",
    appointmentTime: "",
    duration: 30,
    staffMember: "",
    totalAmount: "",
    depositAmount: "",
    depositPaid: false,
    notes: "",
    createCustomer: true,
  });

  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  const [isSaving, setIsSaving] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);

  // Sector-specific fields
  const { customFields } = useSectorFields(userIndustry);
  const [sectorMetadata, setSectorMetadata] = useState<Record<string, unknown>>(
    {},
  );
  const [stripeSettingsUrl, setStripeSettingsUrl] = useState<string | null>(
    null,
  );

  // Appointment types from API (replaces hardcoded list)
  const [appointmentTypes, setAppointmentTypes] = useState<AppointmentType[]>(
    [],
  );

  // Fetch appointment types from org settings
  const fetchAppointmentTypes = useCallback(async () => {
    try {
      const response = await fetch("/api/dashboard/appointment-types");
      const data = await response.json();
      if (data.success && data.types?.length > 0) {
        setAppointmentTypes(data.types);
      }
    } catch {
      // Silently ignore — dropdown will just show "Other" freetext
    }
  }, []);

  // Fetch customers for dropdown
  const fetchCustomers = useCallback(async () => {
    try {
      setLoadingCustomers(true);
      const response = await fetch("/api/user/customers");
      const data = await response.json();
      if (data.success) {
        setCustomers(data.customers || []);
      }
    } catch (error) {
      console.error("Failed to fetch customers:", error);
    } finally {
      setLoadingCustomers(false);
    }
  }, []);

  // Initialize on open
  useEffect(() => {
    if (isOpen) {
      fetchCustomers();
      fetchAppointmentTypes();

      // Set today's date as default
      const today = new Date();
      const dateStr = today.toISOString().split("T")[0];

      // Set default time to next hour
      const nextHour = new Date();
      nextHour.setHours(nextHour.getHours() + 1, 0, 0, 0);
      const timeStr = `${String(nextHour.getHours()).padStart(2, "0")}:00`;

      setFormData((prev) => ({
        ...prev,
        appointmentDate: dateStr,
        appointmentTime: timeStr,
      }));

      // Handle preselected customer
      if (preselectedCustomer) {
        setCustomerMode("existing");
        setSelectedCustomer(preselectedCustomer);
      } else {
        setCustomerMode("new");
        setSelectedCustomer(null);
      }
    }
  }, [isOpen, fetchCustomers, fetchAppointmentTypes, preselectedCustomer]);

  // Filter customers based on search
  const filteredCustomers = customers.filter((c) => {
    if (!customerSearch.trim()) return true;
    const query = customerSearch.toLowerCase();
    return (
      c.name?.toLowerCase().includes(query) ||
      c.phone?.includes(query) ||
      c.email?.toLowerCase().includes(query)
    );
  });

  // Form validation
  const validateForm = () => {
    const errors: Record<string, string> = {};

    // Customer validation
    if (customerMode === "existing" && !selectedCustomer) {
      errors.customer = isAr ? "يرجى اختيار عميل" : "Please select a customer";
    }

    if (customerMode === "new") {
      if (!formData.customerName.trim()) {
        errors.customerName = dt.requiredField;
      }
      if (!formData.customerPhone.trim()) {
        errors.customerPhone = dt.requiredField;
      } else if (!/^[\d\s+()-]+$/.test(formData.customerPhone)) {
        errors.customerPhone = dt.invalidPhone;
      }
      if (
        formData.customerEmail &&
        !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.customerEmail)
      ) {
        errors.customerEmail = dt.invalidEmail;
      }
    }

    // Appointment validation
    if (!formData.service) {
      errors.service = dt.requiredField;
    }

    if (!formData.appointmentDate) {
      errors.appointmentDate = dt.requiredField;
    }

    if (!formData.appointmentTime) {
      errors.appointmentTime = dt.requiredField;
    }

    // Check if date is in the past
    const appointmentDateTime = new Date(
      `${formData.appointmentDate}T${formData.appointmentTime}`,
    );
    if (appointmentDateTime < new Date()) {
      errors.appointmentDate = isAr
        ? "لا يمكن أن يكون الموعد في الماضي"
        : "Appointment cannot be in the past";
    }

    // Sector field validation
    for (const field of customFields) {
      if (field.required) {
        const val = sectorMetadata[field.key];
        if (val === undefined || val === null || val === "") {
          errors[`sector_${field.key}`] = isAr
            ? "يرجى ملء الحقول المطلوبة"
            : "Please fill in required fields";
        }
      }
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // Handle save
  const handleSave = async () => {
    if (!validateForm()) return;

    setIsSaving(true);
    setApiError(null);

    try {
      const csrfToken = getCSRFToken();
      const headers: HeadersInit = {
        "Content-Type": "application/json",
      };
      if (csrfToken) {
        headers["x-csrf-token"] = csrfToken;
      }

      // Determine service name
      const serviceName =
        formData.service === "__other__" || appointmentTypes.length === 0
          ? formData.customService
          : formData.service;

      // Build request body
      const requestBody: Record<string, unknown> = {
        service: serviceName,
        appointmentDate: formData.appointmentDate,
        appointmentTime: formData.appointmentTime,
        duration: formData.duration,
        staffMember: formData.staffMember || null,
        totalAmount: formData.totalAmount
          ? parseFloat(formData.totalAmount)
          : 0,
        depositAmount: formData.depositAmount
          ? parseFloat(formData.depositAmount)
          : null,
        depositPaid: formData.depositPaid,
        notes: formData.notes || null,
        source: "manual",
        language: lang, // Pass language for email template
        ...(Object.keys(sectorMetadata).length > 0 && { sectorMetadata }),
      };

      if (customerMode === "existing" && selectedCustomer) {
        requestBody.customerName = selectedCustomer.name;
        requestBody.customerPhone = selectedCustomer.phone;
        requestBody.customerEmail = selectedCustomer.email;
        requestBody.customerId = selectedCustomer.id;
      } else {
        requestBody.customerName = formData.customerName;
        requestBody.customerPhone = formData.customerPhone;
        requestBody.customerEmail = formData.customerEmail || null;
        requestBody.createCustomer = formData.createCustomer;
      }

      const response = await fetch("/api/bookings", {
        method: "POST",
        headers,
        body: JSON.stringify(requestBody),
      });

      const data = await response.json();

      if (!data.success) {
        // Use the detailed message from API if available (e.g., Stripe not configured)
        const errorMessage =
          data.message ||
          data.error ||
          (isAr ? "فشل في إنشاء الموعد" : "Failed to create appointment");
        setApiError(errorMessage);

        // Store settings URL for Stripe configuration error
        if (
          data.errorCode === "STRIPE_KEYS_NOT_CONFIGURED" &&
          data.settingsUrl
        ) {
          setStripeSettingsUrl(data.settingsUrl);
        } else {
          setStripeSettingsUrl(null);
        }
        return;
      }

      // Success - reset form and close
      resetForm();
      onSuccess();
      onClose();
    } catch (error) {
      console.error("Failed to create appointment:", error);
      setApiError(
        isAr
          ? "حدث خطأ أثناء إنشاء الموعد"
          : "An error occurred while creating the appointment",
      );
    } finally {
      setIsSaving(false);
    }
  };

  // Reset form
  const resetForm = () => {
    setFormData({
      customerName: "",
      customerPhone: "",
      customerEmail: "",
      service: "",
      customService: "",
      appointmentDate: "",
      appointmentTime: "",
      duration: 30,
      staffMember: "",
      totalAmount: "",
      depositAmount: "",
      depositPaid: false,
      notes: "",
      createCustomer: true,
    });
    setSelectedCustomer(null);
    setCustomerSearch("");
    setFormErrors({});
    setApiError(null);
    setStripeSettingsUrl(null);
    setSectorMetadata({});
  };

  // Handle close
  const handleClose = () => {
    resetForm();
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={handleClose}
    >
      {/* Backdrop */}
      <div className="absolute inset-0 bg-slate-900/95 backdrop-blur-sm" />

      {/* Modal Container */}
      <div
        className="relative w-full max-w-2xl transform transition-all duration-300 ease-out animate-fadeIn max-h-[90vh] overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Decorative gradient ring */}
        <div className="absolute -inset-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500 rounded-3xl opacity-20 blur-lg" />

        {/* Modal Content */}
        <div className="relative bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
          {/* Header with gradient accent */}
          <div className="relative px-8 pt-8 pb-6 shrink-0">
            {/* Top accent bar */}
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500" />

            <div className="flex items-start justify-between">
              <div className="flex items-center gap-4">
                {/* Icon container with gradient */}
                <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-green to-emerald-600 shadow-lg shadow-brand-green/30">
                  <Calendar className="w-7 h-7 text-white" />
                </div>
                <div>
                  <h3 className="text-2xl font-bold text-slate-900">
                    {dt.createAppointment ||
                      (isAr ? "إنشاء موعد" : "Create Appointment")}
                  </h3>
                  <p className="text-sm text-slate-500 mt-1">
                    {isAr
                      ? "أدخل تفاصيل الموعد أدناه"
                      : "Enter appointment details below"}
                  </p>
                </div>
              </div>
              <button
                onClick={handleClose}
                className="flex h-10 w-10 items-center justify-center rounded-xl text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-all duration-200"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Form Body - Scrollable */}
          <div className="px-8 pb-6 overflow-y-auto flex-1 space-y-6">
            {/* API Error */}
            {apiError && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-4">
                <p className="text-sm text-red-700">{apiError}</p>
                {stripeSettingsUrl && (
                  <a
                    href={stripeSettingsUrl}
                    className="mt-2 inline-flex items-center gap-2 text-sm font-semibold text-brand-green hover:underline"
                    onClick={handleClose}
                  >
                    {isAr ? "اذهب إلى الإعدادات" : "Go to Settings"}
                    <span>→</span>
                  </a>
                )}
              </div>
            )}

            {/* Customer Selection Section */}
            <div className="rounded-xl border-2 border-slate-200 p-5 space-y-4">
              <h4 className="flex items-center gap-2 text-sm font-bold text-slate-700">
                <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-emerald-100">
                  <User className="w-3.5 h-3.5 text-emerald-600" />
                </span>
                {dt.customer || (isAr ? "العميل" : "Customer")}
              </h4>

              {/* Customer Mode Toggle */}
              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={() => setCustomerMode("new")}
                  className={`flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                    customerMode === "new"
                      ? "bg-brand-green text-white"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  <UserPlus className="w-4 h-4 inline-block mr-2" />
                  {isAr ? "عميل جديد" : "New Customer"}
                </button>
                <button
                  type="button"
                  onClick={() => setCustomerMode("existing")}
                  className={`flex-1 px-4 py-2.5 rounded-xl text-sm font-semibold transition-all ${
                    customerMode === "existing"
                      ? "bg-brand-green text-white"
                      : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                  }`}
                >
                  <Search className="w-4 h-4 inline-block mr-2" />
                  {isAr ? "عميل موجود" : "Existing Customer"}
                </button>
              </div>

              {/* Existing Customer Selection */}
              {customerMode === "existing" && (
                <div className="relative">
                  <div className="relative">
                    <input
                      type="text"
                      value={
                        selectedCustomer
                          ? selectedCustomer.name
                          : customerSearch
                      }
                      onChange={(e) => {
                        setCustomerSearch(e.target.value);
                        setSelectedCustomer(null);
                        setShowCustomerDropdown(true);
                      }}
                      onFocus={() => setShowCustomerDropdown(true)}
                      placeholder={
                        isAr ? "ابحث عن عميل..." : "Search for a customer..."
                      }
                      className={`w-full h-14 px-5 pr-12 rounded-xl border-2 ${
                        formErrors.customer
                          ? "border-red-300 bg-red-50/50"
                          : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                      } text-base font-medium placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                    />
                    <Search className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                  </div>

                  {/* Customer Dropdown */}
                  {showCustomerDropdown && customerMode === "existing" && (
                    <div className="absolute z-10 w-full mt-2 bg-white rounded-xl border border-slate-200 shadow-lg max-h-60 overflow-y-auto">
                      {loadingCustomers ? (
                        <div className="flex items-center justify-center p-4">
                          <Loader2 className="w-5 h-5 text-brand-green animate-spin" />
                        </div>
                      ) : filteredCustomers.length === 0 ? (
                        <div className="p-4 text-center text-sm text-slate-500">
                          {isAr ? "لا يوجد عملاء" : "No customers found"}
                        </div>
                      ) : (
                        filteredCustomers.map((customer) => (
                          <button
                            key={customer.id}
                            type="button"
                            onClick={() => {
                              setSelectedCustomer(customer);
                              setCustomerSearch("");
                              setShowCustomerDropdown(false);
                            }}
                            className="w-full px-4 py-3 flex items-center gap-3 hover:bg-slate-50 transition-colors text-left"
                          >
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-brand-green/20 text-sm font-bold text-brand-green">
                              {customer.name?.charAt(0).toUpperCase() || "?"}
                            </div>
                            <div>
                              <p className="text-sm font-semibold text-slate-900">
                                {customer.name}
                              </p>
                              <p className="text-xs text-slate-500">
                                {customer.phone}
                              </p>
                            </div>
                          </button>
                        ))
                      )}
                    </div>
                  )}

                  {formErrors.customer && (
                    <p className="mt-2 text-sm text-red-500 flex items-center gap-1">
                      <span className="w-1 h-1 rounded-full bg-red-500" />
                      {formErrors.customer}
                    </p>
                  )}
                </div>
              )}

              {/* New Customer Form */}
              {customerMode === "new" && (
                <div className="grid gap-4 sm:grid-cols-2">
                  {/* Name */}
                  <div className="sm:col-span-2">
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                      <User className="w-3.5 h-3.5 text-slate-500" />
                      {dt.fullName}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={formData.customerName}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          customerName: e.target.value,
                        })
                      }
                      placeholder={dt.fullNamePlaceholder}
                      className={`w-full h-12 px-4 rounded-xl border-2 ${
                        formErrors.customerName
                          ? "border-red-300 bg-red-50/50"
                          : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                      } text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                    />
                    {formErrors.customerName && (
                      <p className="mt-1 text-sm text-red-500">
                        {formErrors.customerName}
                      </p>
                    )}
                  </div>

                  {/* Phone */}
                  <div>
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                      <Phone className="w-3.5 h-3.5 text-slate-500" />
                      {dt.mobileNumber}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="tel"
                      value={formData.customerPhone}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          customerPhone: e.target.value,
                        })
                      }
                      placeholder={dt.mobileNumberPlaceholder}
                      className={`w-full h-12 px-4 rounded-xl border-2 ${
                        formErrors.customerPhone
                          ? "border-red-300 bg-red-50/50"
                          : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                      } text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none font-mono`}
                      dir="ltr"
                    />
                    {formErrors.customerPhone && (
                      <p className="mt-1 text-sm text-red-500">
                        {formErrors.customerPhone}
                      </p>
                    )}
                  </div>

                  {/* Email */}
                  <div>
                    <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                      <Mail className="w-3.5 h-3.5 text-slate-500" />
                      {dt.emailAddress}
                      <span className="text-xs text-slate-400 ml-1">
                        ({isAr ? "اختياري" : "optional"})
                      </span>
                    </label>
                    <input
                      type="email"
                      value={formData.customerEmail}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          customerEmail: e.target.value,
                        })
                      }
                      placeholder={dt.emailPlaceholder}
                      className={`w-full h-12 px-4 rounded-xl border-2 ${
                        formErrors.customerEmail
                          ? "border-red-300 bg-red-50/50"
                          : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                      } text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                      dir="ltr"
                    />
                    {formErrors.customerEmail && (
                      <p className="mt-1 text-sm text-red-500">
                        {formErrors.customerEmail}
                      </p>
                    )}
                  </div>

                  {/* Save to Customer List */}
                  <div className="sm:col-span-2">
                    <label className="flex items-center gap-3 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.createCustomer}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            createCustomer: e.target.checked,
                          })
                        }
                        className="w-5 h-5 rounded-md border-2 border-slate-300 text-brand-green focus:ring-brand-green"
                      />
                      <span className="text-sm text-slate-700">
                        {isAr
                          ? "حفظ في قائمة العملاء"
                          : "Save to customer list"}
                      </span>
                    </label>
                  </div>
                </div>
              )}
            </div>

            {/* Appointment Details Section */}
            <div className="rounded-xl border-2 border-slate-200 p-5 space-y-4">
              <h4 className="flex items-center gap-2 text-sm font-bold text-slate-700">
                <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-blue-100">
                  <Calendar className="w-3.5 h-3.5 text-blue-600" />
                </span>
                {isAr ? "تفاصيل الموعد" : "Appointment Details"}
              </h4>

              <div className="grid gap-4 sm:grid-cols-2">
                {/* Service */}
                <div className="sm:col-span-2">
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                    <Briefcase className="w-3.5 h-3.5 text-slate-500" />
                    {dt.service}
                    <span className="text-red-500">*</span>
                  </label>
                  <div className="relative">
                    <select
                      value={formData.service}
                      onChange={(e) => {
                        const selected = appointmentTypes.find(
                          (t) =>
                            (isAr ? t.nameAr : t.nameEn) === e.target.value,
                        );
                        setFormData({
                          ...formData,
                          service: e.target.value,
                          duration: selected?.duration ?? formData.duration,
                          totalAmount:
                            selected?.price != null
                              ? String(selected.price)
                              : formData.totalAmount,
                        });
                      }}
                      className={`w-full h-12 px-4 rounded-xl border-2 ${
                        formErrors.service
                          ? "border-red-300 bg-red-50/50"
                          : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                      } text-base appearance-none cursor-pointer transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                    >
                      <option value="">
                        {isAr ? "اختر الخدمة" : "Select a service"}
                      </option>
                      {appointmentTypes.length > 0 ? (
                        appointmentTypes.map((t) => (
                          <option key={t.id} value={isAr ? t.nameAr : t.nameEn}>
                            {isAr ? t.nameAr : t.nameEn}
                          </option>
                        ))
                      ) : (
                        <option value="__other__">
                          {isAr ? "أخرى" : "Other"}
                        </option>
                      )}
                    </select>
                    <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400 pointer-events-none" />
                  </div>
                  {formErrors.service && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.service}
                    </p>
                  )}
                </div>

                {/* Custom Service Name — shown when no types configured or "Other" selected */}
                {(appointmentTypes.length === 0 ||
                  formData.service === "__other__") && (
                  <div className="sm:col-span-2">
                    <label className="text-sm font-semibold text-slate-700 mb-2 block">
                      {isAr ? "اسم الخدمة" : "Service Name"}
                      <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={formData.customService}
                      onChange={(e) =>
                        setFormData({
                          ...formData,
                          customService: e.target.value,
                        })
                      }
                      placeholder={
                        isAr ? "أدخل اسم الخدمة" : "Enter service name"
                      }
                      className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 focus:border-brand-green text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                    />
                  </div>
                )}

                {/* Date */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                    <Calendar className="w-3.5 h-3.5 text-slate-500" />
                    {dt.date}
                    <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="date"
                    value={formData.appointmentDate}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        appointmentDate: e.target.value,
                      })
                    }
                    min={new Date().toISOString().split("T")[0]}
                    className={`w-full h-12 px-4 rounded-xl border-2 ${
                      formErrors.appointmentDate
                        ? "border-red-300 bg-red-50/50"
                        : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                    } text-base transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                  />
                  {formErrors.appointmentDate && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.appointmentDate}
                    </p>
                  )}
                </div>

                {/* Time */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                    <Clock className="w-3.5 h-3.5 text-slate-500" />
                    {dt.time}
                    <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="time"
                    value={formData.appointmentTime}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        appointmentTime: e.target.value,
                      })
                    }
                    className={`w-full h-12 px-4 rounded-xl border-2 ${
                      formErrors.appointmentTime
                        ? "border-red-300 bg-red-50/50"
                        : "border-slate-200 bg-slate-50/50 focus:border-brand-green"
                    } text-base transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                  />
                  {formErrors.appointmentTime && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.appointmentTime}
                    </p>
                  )}
                </div>

                {/* Duration */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                    <Clock className="w-3.5 h-3.5 text-slate-500" />
                    {isAr ? "المدة (دقيقة)" : "Duration (minutes)"}
                  </label>
                  <select
                    value={formData.duration}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        duration: parseInt(e.target.value),
                      })
                    }
                    className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 focus:border-brand-green text-base appearance-none cursor-pointer transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                  >
                    <option value={15}>15 {isAr ? "دقيقة" : "min"}</option>
                    <option value={30}>30 {isAr ? "دقيقة" : "min"}</option>
                    <option value={45}>45 {isAr ? "دقيقة" : "min"}</option>
                    <option value={60}>
                      60 {isAr ? "دقيقة" : "min"} (1 {isAr ? "ساعة" : "hour"})
                    </option>
                    <option value={90}>
                      90 {isAr ? "دقيقة" : "min"} (1.5 {isAr ? "ساعة" : "hours"}
                      )
                    </option>
                    <option value={120}>
                      120 {isAr ? "دقيقة" : "min"} (2 {isAr ? "ساعات" : "hours"}
                      )
                    </option>
                  </select>
                </div>

                {/* Staff Member */}
                <div>
                  <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                    <User className="w-3.5 h-3.5 text-slate-500" />
                    {isAr ? "الموظف" : "Staff Member"}
                    <span className="text-xs text-slate-400 ml-1">
                      ({isAr ? "اختياري" : "optional"})
                    </span>
                  </label>
                  <input
                    type="text"
                    value={formData.staffMember}
                    onChange={(e) =>
                      setFormData({ ...formData, staffMember: e.target.value })
                    }
                    placeholder={isAr ? "اسم الموظف" : "Staff name"}
                    className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 focus:border-brand-green text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                  />
                </div>
              </div>
            </div>

            {/* Payment Section */}
            <div className="rounded-xl border-2 border-slate-200 p-5 space-y-4">
              <h4 className="flex items-center gap-2 text-sm font-bold text-slate-700">
                <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-violet-100">
                  <DollarSign className="w-3.5 h-3.5 text-violet-600" />
                </span>
                {isAr ? "معلومات الدفع" : "Payment Info"}
                <span className="text-xs text-slate-400 ml-1">
                  ({isAr ? "اختياري" : "optional"})
                </span>
              </h4>

              <div className="grid gap-4 sm:grid-cols-2">
                {/* Total Amount */}
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-2 block">
                    {isAr ? "المبلغ الإجمالي (QAR)" : "Total Amount (QAR)"}
                  </label>
                  <input
                    type="number"
                    value={formData.totalAmount}
                    onChange={(e) =>
                      setFormData({ ...formData, totalAmount: e.target.value })
                    }
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                    className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 focus:border-brand-green text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                    dir="ltr"
                  />
                </div>

                {/* Deposit Amount */}
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-2 block">
                    {dt.deposit} (QAR)
                  </label>
                  <input
                    type="number"
                    value={formData.depositAmount}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        depositAmount: e.target.value,
                      })
                    }
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                    className="w-full h-12 px-4 rounded-xl border-2 border-slate-200 bg-slate-50/50 focus:border-brand-green text-base placeholder-slate-400 transition-all duration-200 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                    dir="ltr"
                  />
                </div>

                {/* Deposit Paid Checkbox */}
                {formData.depositAmount && (
                  <div className="sm:col-span-2">
                    <label className="flex items-center gap-3 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.depositPaid}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            depositPaid: e.target.checked,
                          })
                        }
                        className="w-5 h-5 rounded-md border-2 border-slate-300 text-brand-green focus:ring-brand-green"
                      />
                      <span className="text-sm text-slate-700">
                        {dt.depositPaid}
                      </span>
                    </label>
                  </div>
                )}
              </div>
            </div>

            {/* Sector-Specific Fields */}
            {customFields.length > 0 && (
              <div className="rounded-xl border-2 border-slate-200 p-5 space-y-4">
                <h4 className="flex items-center gap-2 text-sm font-bold text-slate-700">
                  <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-violet-100">
                    <Layers className="w-3.5 h-3.5 text-violet-600" />
                  </span>
                  {isAr ? "تفاصيل القطاع" : "Sector Details"}
                </h4>
                <SectorFieldsForm
                  fields={customFields}
                  values={sectorMetadata}
                  onChange={(key, value) =>
                    setSectorMetadata((prev) => ({ ...prev, [key]: value }))
                  }
                  lang={lang}
                  errors={Object.fromEntries(
                    Object.entries(formErrors)
                      .filter(([k]) => k.startsWith("sector_"))
                      .map(([k, v]) => [k.replace("sector_", ""), v]),
                  )}
                />
              </div>
            )}

            {/* Notes Section */}
            <div>
              <label className="flex items-center gap-2 text-sm font-semibold text-slate-700 mb-2">
                <span className="flex h-6 w-6 items-center justify-center rounded-lg bg-slate-100">
                  <FileText className="w-3.5 h-3.5 text-slate-500" />
                </span>
                {dt.notes}
                <span className="text-xs text-slate-400 ml-1">
                  ({isAr ? "اختياري" : "optional"})
                </span>
              </label>
              <textarea
                value={formData.notes}
                onChange={(e) =>
                  setFormData({ ...formData, notes: e.target.value })
                }
                placeholder={dt.notesPlaceholder}
                rows={3}
                className="w-full px-4 py-3 rounded-xl border-2 border-slate-200 bg-slate-50/50 text-base placeholder-slate-400 transition-all duration-200 focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none resize-none"
              />
            </div>
          </div>

          {/* Footer with gradient background */}
          <div className="px-8 py-6 bg-gradient-to-r from-slate-50 via-slate-100/50 to-slate-50 border-t border-slate-200 shrink-0">
            <div className="flex items-center justify-end gap-4">
              <button
                onClick={handleClose}
                className="px-6 py-3 rounded-xl border-2 border-slate-200 bg-white text-sm font-bold text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all duration-200"
              >
                {dt.cancelAction}
              </button>
              <button
                onClick={handleSave}
                disabled={isSaving}
                className="px-8 py-3 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-sm font-bold text-white shadow-lg shadow-brand-green/30 hover:shadow-brand-green/50 hover:-translate-y-0.5 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0 inline-flex items-center gap-2"
              >
                {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
                {dt.createManualBooking}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
