/**
 * Create Viewing Modal Component
 * Schedule a property viewing with property search, client info, broker assignment,
 * viewing type selection (Individual/Tour/Open House/Virtual/Second Viewing),
 * and tour multi-property selector with drag-to-reorder
 */

"use client";

import { useState, useEffect, useCallback } from "react";
import type { Lang } from "@/lib/config";
import { fetchWithCSRF } from "@/lib/csrf-client";
import {
  X,
  Building2,
  User,
  Phone,
  Mail,
  Calendar,
  Clock,
  Search,
  Loader2,
  Eye,
  UserCheck,
  GripVertical,
  Trash2,
  Plus,
  ArrowUp,
  ArrowDown,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface CreateViewingModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  preselectedDate?: string;
  preselectedTime?: string;
  preselectedPropertyId?: string;
}

interface PropertyOption {
  id: string;
  titleEn: string;
  titleAr: string;
  district?: string;
  city: string;
  propertyType?: string;
}

interface BrokerOption {
  id: string;
  nameEn: string;
  nameAr: string;
}

const VIEWING_TYPES = [
  { value: "INDIVIDUAL", label: "Individual", icon: "1" },
  { value: "TOUR", label: "Tour", icon: "T" },
  { value: "OPEN_HOUSE", label: "Open House", icon: "O" },
  { value: "VIRTUAL", label: "Virtual", icon: "V" },
  { value: "SECOND_VIEWING", label: "Second Viewing", icon: "2" },
];

const DURATION_OPTIONS = [
  { value: 15, label: "15 min" },
  { value: 30, label: "30 min" },
  { value: 45, label: "45 min" },
  { value: 60, label: "1 hour" },
  { value: 90, label: "1.5 hours" },
  { value: 120, label: "2 hours" },
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function showToast(
  type: "success" | "error" | "info" | "warning",
  title: string,
  message: string,
) {
  const event = new CustomEvent("showToast", {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export default function CreateViewingModal({
  lang,
  isOpen,
  onClose,
  onSuccess,
  preselectedDate,
  preselectedTime,
  preselectedPropertyId,
}: CreateViewingModalProps) {
  const isAr = lang === "ar";

  const [formData, setFormData] = useState({
    propertyId: preselectedPropertyId || "",
    clientName: "",
    clientPhone: "",
    clientEmail: "",
    viewingDate: preselectedDate || "",
    viewingTime: preselectedTime || "",
    viewingType: "INDIVIDUAL",
    brokerId: "",
    autoAssign: true,
    duration: 30,
    notes: "",
  });

  const [properties, setProperties] = useState<PropertyOption[]>([]);
  const [brokers, setBrokers] = useState<BrokerOption[]>([]);
  const [propertySearch, setPropertySearch] = useState("");
  const [showPropertyDropdown, setShowPropertyDropdown] = useState(false);
  const [selectedProperty, setSelectedProperty] =
    useState<PropertyOption | null>(null);
  const [loadingProperties, setLoadingProperties] = useState(false);

  // Tour mode: multiple properties
  const [tourProperties, setTourProperties] = useState<PropertyOption[]>([]);
  const [tourSearch, setTourSearch] = useState("");
  const [showTourDropdown, setShowTourDropdown] = useState(false);

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

  const isTour = formData.viewingType === "TOUR";

  const fetchProperties = useCallback(async (query: string) => {
    try {
      setLoadingProperties(true);
      const params = new URLSearchParams();
      if (query) params.set("search", query);
      params.set("status", "available");
      params.set("limit", "20");
      const res = await fetch(
        `/api/real-estate/properties?${params.toString()}`,
      );
      const data = await res.json();
      if (data.success) {
        setProperties(data.properties || []);
      }
    } catch (error) {
      console.error("Failed to fetch properties:", error);
    } finally {
      setLoadingProperties(false);
    }
  }, []);

  const fetchBrokers = useCallback(async () => {
    try {
      const res = await fetch("/api/real-estate/brokers?activeOnly=true");
      const data = await res.json();
      if (data.success) {
        setBrokers(data.brokers || []);
      }
    } catch (error) {
      console.error("Failed to fetch brokers:", error);
    }
  }, []);

  useEffect(() => {
    if (isOpen) {
      fetchBrokers();
      fetchProperties("");

      if (!preselectedDate) {
        const today = new Date().toISOString().split("T")[0];
        setFormData((prev) => ({ ...prev, viewingDate: today }));
      }
      if (!preselectedTime) {
        const nextHour = new Date();
        nextHour.setHours(nextHour.getHours() + 1, 0, 0, 0);
        const timeStr = `${String(nextHour.getHours()).padStart(2, "0")}:00`;
        setFormData((prev) => ({ ...prev, viewingTime: timeStr }));
      }
    }
  }, [isOpen, fetchBrokers, fetchProperties, preselectedDate, preselectedTime]);

  // Debounced property search
  useEffect(() => {
    if (!isOpen) return;
    const timer = setTimeout(() => {
      if (propertySearch.length >= 2) {
        fetchProperties(propertySearch);
        setShowPropertyDropdown(true);
      } else if (propertySearch.length === 0) {
        setShowPropertyDropdown(false);
      }
    }, 300);
    return () => clearTimeout(timer);
  }, [propertySearch, isOpen, fetchProperties]);

  // Debounced tour search
  useEffect(() => {
    if (!isOpen || !isTour) return;
    const timer = setTimeout(() => {
      if (tourSearch.length >= 2) {
        fetchProperties(tourSearch);
        setShowTourDropdown(true);
      } else {
        setShowTourDropdown(false);
      }
    }, 300);
    return () => clearTimeout(timer);
  }, [tourSearch, isOpen, isTour, fetchProperties]);

  const updateField = (field: string, value: string | boolean | number) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    if (formErrors[field]) {
      setFormErrors((prev) => {
        const next = { ...prev };
        delete next[field];
        return next;
      });
    }
  };

  const selectProperty = (property: PropertyOption) => {
    setSelectedProperty(property);
    updateField("propertyId", property.id);
    setPropertySearch("");
    setShowPropertyDropdown(false);
  };

  // Tour property management
  const addTourProperty = (property: PropertyOption) => {
    if (tourProperties.find((p) => p.id === property.id)) return;
    setTourProperties((prev) => [...prev, property]);
    setTourSearch("");
    setShowTourDropdown(false);
  };

  const removeTourProperty = (id: string) => {
    setTourProperties((prev) => prev.filter((p) => p.id !== id));
  };

  const moveTourProperty = (index: number, direction: "up" | "down") => {
    const newList = [...tourProperties];
    const swapIndex = direction === "up" ? index - 1 : index + 1;
    if (swapIndex < 0 || swapIndex >= newList.length) return;
    [newList[index], newList[swapIndex]] = [newList[swapIndex], newList[index]];
    setTourProperties(newList);
  };

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

    if (isTour) {
      if (tourProperties.length < 2) {
        errors.tourProperties = "Add at least 2 properties for a tour";
      }
    } else {
      if (!formData.propertyId && !selectedProperty) {
        errors.propertyId = "Please select a property";
      }
    }

    if (!formData.clientName.trim()) errors.clientName = "Required";
    if (!formData.clientPhone.trim()) errors.clientPhone = "Required";
    if (!formData.viewingDate) errors.viewingDate = "Required";
    if (!formData.viewingTime) errors.viewingTime = "Required";
    if (!formData.autoAssign && !formData.brokerId) {
      errors.brokerId = "Select a broker or enable auto-assign";
    }

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

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

    setIsSaving(true);
    setApiError(null);

    try {
      const body: Record<string, unknown> = {
        clientName: formData.clientName.trim(),
        clientPhone: formData.clientPhone.trim(),
        clientEmail: formData.clientEmail.trim() || null,
        viewingDate: formData.viewingDate,
        viewingTime: formData.viewingTime,
        viewingType: formData.viewingType,
        duration: formData.duration,
        notes: formData.notes.trim() || null,
        autoAssignBroker: formData.autoAssign,
      };

      if (isTour) {
        body.propertyIds = tourProperties.map((p) => p.id);
      } else {
        body.propertyId = selectedProperty?.id || formData.propertyId;
      }

      if (!formData.autoAssign && formData.brokerId) {
        body.brokerId = formData.brokerId;
      }

      const response = await fetchWithCSRF("/api/real-estate/viewings", {
        method: "POST",
        body: JSON.stringify(body),
      });

      const data = await response.json();
      if (!data.success) {
        setApiError(data.error || "Failed to schedule viewing");
        return;
      }

      showToast(
        "success",
        "Viewing Scheduled",
        "The viewing has been created successfully",
      );
      resetForm();
      onSuccess();
    } catch (error) {
      console.error("Failed to create viewing:", error);
      setApiError("An error occurred while scheduling the viewing");
    } finally {
      setIsSaving(false);
    }
  };

  const resetForm = () => {
    setFormData({
      propertyId: "",
      clientName: "",
      clientPhone: "",
      clientEmail: "",
      viewingDate: "",
      viewingTime: "",
      viewingType: "INDIVIDUAL",
      brokerId: "",
      autoAssign: true,
      duration: 30,
      notes: "",
    });
    setSelectedProperty(null);
    setPropertySearch("");
    setTourProperties([]);
    setTourSearch("");
    setFormErrors({});
    setApiError(null);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  if (!isOpen) return null;

  const inputClass = (field: string) =>
    `w-full h-12 px-4 rounded-xl border-2 ${
      formErrors[field]
        ? "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`;

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

      <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()}
      >
        <div className="absolute -inset-1 bg-gradient-to-r from-brand-green via-emerald-400 to-teal-500 rounded-3xl opacity-20 blur-lg" />

        <div className="relative bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
          {/* Header */}
          <div className="relative px-8 pt-8 pb-6 shrink-0">
            <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">
                <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">
                  <Eye className="w-7 h-7 text-white" />
                </div>
                <div>
                  <h3 className="text-2xl font-bold text-slate-900">
                    Schedule Viewing
                  </h3>
                  <p className="text-sm text-slate-500 mt-1">
                    Book a property viewing for a client
                  </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"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Form Body */}
          <div className="px-8 pb-6 overflow-y-auto flex-1 space-y-6">
            {apiError && (
              <div className="rounded-xl bg-red-50 border border-red-200 p-4">
                <p className="text-sm text-red-700">{apiError}</p>
              </div>
            )}

            {/* Viewing Type Radio */}
            <div>
              <label className="text-sm font-semibold text-slate-700 mb-3 block">
                Viewing Type
              </label>
              <div className="flex flex-wrap gap-2">
                {VIEWING_TYPES.map((vt) => (
                  <button
                    key={vt.value}
                    type="button"
                    onClick={() => updateField("viewingType", vt.value)}
                    className={`inline-flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium transition-all ${
                      formData.viewingType === vt.value
                        ? "bg-brand-green text-white shadow-sm shadow-brand-green/30"
                        : "bg-slate-100 text-slate-600 hover:bg-slate-200"
                    }`}
                  >
                    <span
                      className={`flex h-5 w-5 items-center justify-center rounded-md text-[10px] font-bold ${
                        formData.viewingType === vt.value
                          ? "bg-white/20 text-white"
                          : "bg-slate-200 text-slate-500"
                      }`}
                    >
                      {vt.icon}
                    </span>
                    {vt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Property Selection (single or tour) */}
            {!isTour ? (
              <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">
                    <Building2 className="w-3.5 h-3.5 text-emerald-600" />
                  </span>
                  Property <span className="text-red-500">*</span>
                </h4>

                <div className="relative">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
                    <input
                      type="text"
                      value={
                        selectedProperty
                          ? selectedProperty.titleEn
                          : propertySearch
                      }
                      onChange={(e) => {
                        setPropertySearch(e.target.value);
                        setSelectedProperty(null);
                        setShowPropertyDropdown(true);
                      }}
                      onFocus={() => {
                        if (properties.length > 0 && !selectedProperty)
                          setShowPropertyDropdown(true);
                      }}
                      placeholder="Search for a property..."
                      className={`w-full h-12 pl-10 pr-4 rounded-xl border-2 ${
                        formErrors.propertyId
                          ? "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 focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                    />
                    {loadingProperties && (
                      <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-brand-green animate-spin" />
                    )}
                  </div>

                  {showPropertyDropdown && properties.length > 0 && (
                    <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">
                      {properties.map((property) => (
                        <button
                          key={property.id}
                          type="button"
                          onClick={() => selectProperty(property)}
                          className="w-full px-4 py-3 flex items-center gap-3 hover:bg-slate-50 transition-colors text-left border-b border-slate-100 last:border-0"
                        >
                          <Building2 className="w-5 h-5 text-slate-400 shrink-0" />
                          <div>
                            <p className="text-sm font-semibold text-slate-900">
                              {property.titleEn}
                            </p>
                            <p className="text-xs text-slate-500">
                              {property.propertyType
                                ? `${property.propertyType} - `
                                : ""}
                              {property.district
                                ? `${property.district}, `
                                : ""}
                              {property.city}
                            </p>
                          </div>
                        </button>
                      ))}
                    </div>
                  )}
                  {formErrors.propertyId && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.propertyId}
                    </p>
                  )}
                </div>
              </div>
            ) : (
              /* Tour: Multi-property selector */
              <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">
                    <Building2 className="w-3.5 h-3.5 text-emerald-600" />
                  </span>
                  Tour Properties <span className="text-red-500">*</span>
                  <span className="text-xs text-slate-400 font-normal ml-1">
                    (min 2, reorder with arrows)
                  </span>
                </h4>

                {/* Property list with reorder */}
                {tourProperties.length > 0 && (
                  <div className="space-y-2">
                    {tourProperties.map((p, idx) => (
                      <div
                        key={p.id}
                        className="flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 p-2.5"
                      >
                        <div className="flex flex-col gap-0.5">
                          <button
                            type="button"
                            onClick={() => moveTourProperty(idx, "up")}
                            disabled={idx === 0}
                            className="text-slate-400 hover:text-slate-600 disabled:opacity-20 p-0.5"
                          >
                            <ArrowUp className="w-3 h-3" />
                          </button>
                          <button
                            type="button"
                            onClick={() => moveTourProperty(idx, "down")}
                            disabled={idx === tourProperties.length - 1}
                            className="text-slate-400 hover:text-slate-600 disabled:opacity-20 p-0.5"
                          >
                            <ArrowDown className="w-3 h-3" />
                          </button>
                        </div>
                        <span className="flex h-6 w-6 items-center justify-center rounded-full bg-brand-green text-white text-xs font-bold shrink-0">
                          {idx + 1}
                        </span>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-slate-800 truncate">
                            {p.titleEn}
                          </p>
                          <p className="text-xs text-slate-500">
                            {p.district ? `${p.district}, ` : ""}
                            {p.city}
                          </p>
                        </div>
                        <button
                          type="button"
                          onClick={() => removeTourProperty(p.id)}
                          className="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    ))}
                  </div>
                )}

                {/* Add property to tour */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none" />
                  <input
                    type="text"
                    value={tourSearch}
                    onChange={(e) => setTourSearch(e.target.value)}
                    placeholder="Search to add properties to tour..."
                    className="w-full h-10 pl-10 pr-4 rounded-xl border-2 border-dashed border-slate-300 bg-slate-50/50 text-sm placeholder-slate-400 transition-all focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                  />
                  {loadingProperties && (
                    <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-brand-green animate-spin" />
                  )}

                  {showTourDropdown && properties.length > 0 && (
                    <div className="absolute z-10 w-full mt-1 bg-white rounded-xl border border-slate-200 shadow-lg max-h-48 overflow-y-auto">
                      {properties
                        .filter(
                          (p) => !tourProperties.find((tp) => tp.id === p.id),
                        )
                        .map((p) => (
                          <button
                            key={p.id}
                            type="button"
                            onClick={() => addTourProperty(p)}
                            className="w-full text-left px-4 py-3 hover:bg-emerald-50 transition-colors border-b border-slate-100 last:border-0 flex items-center gap-2"
                          >
                            <Plus className="w-4 h-4 text-brand-green shrink-0" />
                            <div>
                              <p className="text-sm font-medium text-slate-900">
                                {p.titleEn}
                              </p>
                              <p className="text-xs text-slate-500">{p.city}</p>
                            </div>
                          </button>
                        ))}
                    </div>
                  )}
                </div>
                {formErrors.tourProperties && (
                  <p className="text-sm text-red-500">
                    {formErrors.tourProperties}
                  </p>
                )}
              </div>
            )}

            {/* Client Info */}
            <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">
                  <User className="w-3.5 h-3.5 text-blue-600" />
                </span>
                Client Information
              </h4>

              <div className="grid gap-4 sm:grid-cols-2">
                <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" />
                    Client Name <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.clientName}
                    onChange={(e) => updateField("clientName", e.target.value)}
                    placeholder="Full name"
                    className={inputClass("clientName")}
                  />
                  {formErrors.clientName && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.clientName}
                    </p>
                  )}
                </div>
                <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" />
                    Phone <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="tel"
                    value={formData.clientPhone}
                    onChange={(e) => updateField("clientPhone", e.target.value)}
                    placeholder="+974 xxxx xxxx"
                    className={inputClass("clientPhone")}
                    dir="ltr"
                  />
                  {formErrors.clientPhone && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.clientPhone}
                    </p>
                  )}
                </div>
                <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" />
                    Email
                    <span className="text-xs text-slate-400 ml-1">
                      (optional)
                    </span>
                  </label>
                  <input
                    type="email"
                    value={formData.clientEmail}
                    onChange={(e) => updateField("clientEmail", e.target.value)}
                    placeholder="email@example.com"
                    className={inputClass("clientEmail")}
                    dir="ltr"
                  />
                </div>
              </div>
            </div>

            {/* Schedule */}
            <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">
                  <Calendar className="w-3.5 h-3.5 text-violet-600" />
                </span>
                Schedule
              </h4>

              <div className="grid gap-4 sm:grid-cols-3">
                <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" />
                    Date <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="date"
                    value={formData.viewingDate}
                    onChange={(e) => updateField("viewingDate", e.target.value)}
                    min={new Date().toISOString().split("T")[0]}
                    className={inputClass("viewingDate")}
                  />
                  {formErrors.viewingDate && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.viewingDate}
                    </p>
                  )}
                </div>
                <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" />
                    Time <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="time"
                    value={formData.viewingTime}
                    onChange={(e) => updateField("viewingTime", e.target.value)}
                    className={inputClass("viewingTime")}
                  />
                  {formErrors.viewingTime && (
                    <p className="mt-1 text-sm text-red-500">
                      {formErrors.viewingTime}
                    </p>
                  )}
                </div>
                <div>
                  <label className="text-sm font-semibold text-slate-700 mb-2 block">
                    Duration
                  </label>
                  <select
                    value={formData.duration}
                    onChange={(e) =>
                      updateField("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 focus:ring-4 focus:ring-brand-green/20 focus:outline-none"
                  >
                    {DURATION_OPTIONS.map((d) => (
                      <option key={d.value} value={d.value}>
                        {d.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>

            {/* Broker Assignment */}
            <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-amber-100">
                  <UserCheck className="w-3.5 h-3.5 text-amber-600" />
                </span>
                Broker Assignment
              </h4>

              <div className="space-y-3">
                <label className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.autoAssign}
                    onChange={(e) =>
                      updateField("autoAssign", 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">
                    Auto-assign based on availability
                  </span>
                </label>

                {!formData.autoAssign && (
                  <div>
                    <select
                      value={formData.brokerId}
                      onChange={(e) => updateField("brokerId", e.target.value)}
                      className={`w-full h-12 px-4 rounded-xl border-2 ${
                        formErrors.brokerId
                          ? "border-red-300"
                          : "border-slate-200"
                      } bg-slate-50/50 focus:border-brand-green text-base appearance-none cursor-pointer transition-all focus:ring-4 focus:ring-brand-green/20 focus:outline-none`}
                    >
                      <option value="">Select a broker...</option>
                      {brokers.map((b) => (
                        <option key={b.id} value={b.id}>
                          {b.nameEn}
                        </option>
                      ))}
                    </select>
                    {formErrors.brokerId && (
                      <p className="mt-1 text-sm text-red-500">
                        {formErrors.brokerId}
                      </p>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Notes */}
            <div>
              <label className="text-sm font-semibold text-slate-700 mb-2 block">
                Notes{" "}
                <span className="text-xs text-slate-400 ml-1">(optional)</span>
              </label>
              <textarea
                value={formData.notes}
                onChange={(e) => updateField("notes", e.target.value)}
                rows={3}
                placeholder="Any additional notes about this viewing..."
                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 focus:border-brand-green focus:ring-4 focus:ring-brand-green/20 focus:outline-none resize-none"
              />
            </div>
          </div>

          {/* Footer */}
          <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"
              >
                Cancel
              </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 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2"
              >
                {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
                Schedule Viewing
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
