"use client";

import { useState, useEffect, useMemo } from "react";
import {
  X,
  ChevronLeft,
  ChevronRight,
  Car,
  Loader2,
  Check,
  MapPin,
  User,
  Calendar,
  Search,
  Mail,
  CreditCard,
  AlertTriangle,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { Lang } from "@/lib/config";
import type { Vehicle } from "@/lib/types/vehicles.types";
import {
  VEHICLE_TYPE_LABELS,
  calculateRentalPrice,
  formatVehiclePrice,
} from "@/lib/types/vehicles.types";

interface NewRentalModalProps {
  lang: Lang;
  isOpen: boolean;
  onClose: () => void;
  onCreated: () => void;
}

type Step = 1 | 2 | 3;

export default function NewRentalModal({
  lang,
  isOpen,
  onClose,
  onCreated,
}: NewRentalModalProps) {
  const isAr = lang === "ar";
  const [step, setStep] = useState<Step>(1);
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Step 1: Dates & location
  const [pickupDate, setPickupDate] = useState("");
  const [returnDate, setReturnDate] = useState("");
  const [pickupLocation, setPickupLocation] = useState("");
  const [dropoffLocation, setDropoffLocation] = useState("");

  // Step 2: Vehicle selection
  const [selectedVehicle, setSelectedVehicle] = useState<Vehicle | null>(null);
  const [vehicleSearch, setVehicleSearch] = useState("");

  // Step 3: Customer details
  const [customerName, setCustomerName] = useState("");
  const [customerPhone, setCustomerPhone] = useState("");
  const [customerEmail, setCustomerEmail] = useState("");
  const [customerLicenseNumber, setCustomerLicenseNumber] = useState("");
  const [notes, setNotes] = useState("");
  const [depositPaid, setDepositPaid] = useState(false);
  const [depositPaymentId, setDepositPaymentId] = useState("");
  const [depositPaymentMethod, setDepositPaymentMethod] = useState("cash");
  const [agreementNumber, setAgreementNumber] = useState("");
  const [sendDepositLink, setSendDepositLink] = useState(false);
  const [hasStripeKeys, setHasStripeKeys] = useState(false);
  const [sendingLink, setSendingLink] = useState(false);
  const [existingCustomers, setExistingCustomers] = useState<
    { id: string; name: string; phone: string; email?: string }[]
  >([]);
  const [customerQuery, setCustomerQuery] = useState("");
  const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
  const [loadingCustomers, setLoadingCustomers] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setStep(1);
      setSelectedVehicle(null);
      setVehicleSearch("");
      setPickupDate("");
      setReturnDate("");
      setPickupLocation("");
      setDropoffLocation("");
      setCustomerName("");
      setCustomerPhone("");
      setCustomerEmail("");
      setCustomerLicenseNumber("");
      setNotes("");
      setDepositPaid(false);
      setDepositPaymentId("");
      setDepositPaymentMethod("cash");
      setAgreementNumber("");
      setSendDepositLink(false);
      setSendingLink(false);
      setError(null);
      setExistingCustomers([]);
      setCustomerQuery("");
      setShowCustomerDropdown(false);
      fetchVehicles();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  const fetchVehicles = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/dashboard/vehicles");
      if (res.ok) {
        const data = await res.json();
        setVehicles(
          (data.vehicles ?? []).filter((v: Vehicle) => v.isAvailable),
        );
      }
    } finally {
      setLoading(false);
    }
  };

  // Check Stripe keys when entering step 3
  useEffect(() => {
    if (step === 3) {
      fetch("/api/settings/stripe-keys")
        .then((r) => r.json())
        .then((data) => {
          setHasStripeKeys(data.success && data.hasKeys === true);
        })
        .catch(() => setHasStripeKeys(false));
    }
  }, [step]);

  // Fetch existing customers when entering step 3
  useEffect(() => {
    if (step === 3 && existingCustomers.length === 0) {
      setLoadingCustomers(true);
      fetch("/api/user/customers")
        .then((r) => r.json())
        .then((data) => {
          if (data.success && Array.isArray(data.customers)) {
            setExistingCustomers(
              data.customers.map(
                (c: { id: string; name: string; phone: string; email?: string }) => ({
                  id: c.id,
                  name: c.name || "",
                  phone: c.phone || "",
                  email: c.email || "",
                }),
              ),
            );
          }
        })
        .catch(() => {})
        .finally(() => setLoadingCustomers(false));
    }
  }, [step, existingCustomers.length]);

  const filteredCustomers = useMemo(() => {
    if (!customerQuery.trim()) return existingCustomers.slice(0, 5);
    const q = customerQuery.toLowerCase();
    return existingCustomers
      .filter(
        (c) =>
          c.name.toLowerCase().includes(q) ||
          c.phone.includes(q) ||
          (c.email?.toLowerCase().includes(q) ?? false),
      )
      .slice(0, 5);
  }, [customerQuery, existingCustomers]);

  const selectCustomer = (c: { name: string; phone: string; email?: string }) => {
    setCustomerName(c.name);
    setCustomerPhone(c.phone);
    setCustomerEmail(c.email || "");
    setCustomerQuery("");
    setShowCustomerDropdown(false);
  };

  // Price calculation
  const pricing = useMemo(() => {
    if (!selectedVehicle || !pickupDate || !returnDate) return null;
    const pickup = new Date(pickupDate).getTime();
    const ret = new Date(returnDate).getTime();
    if (ret <= pickup) return null;
    const durationDays = Math.ceil((ret - pickup) / 86400000);
    const { dailyRate, totalAmount } = calculateRentalPrice(
      selectedVehicle,
      durationDays,
    );
    return { durationDays, dailyRate, totalAmount };
  }, [selectedVehicle, pickupDate, returnDate]);

  const canGoNext = (): boolean => {
    if (step === 1) return !!pickupDate && !!returnDate;
    if (step === 2) return !!selectedVehicle;
    if (step === 3) return !!customerName && !!customerPhone;
    return false;
  };

  const handleSubmit = async () => {
    if (!selectedVehicle || !pricing) return;
    setSubmitting(true);
    setError(null);
    try {
      const pickup = new Date(pickupDate).getTime();
      const ret = new Date(returnDate).getTime();

      // API expects display values (it does *100 internally)
      const res = await fetchWithCSRF("/api/dashboard/rentals", {
        method: "POST",
        body: JSON.stringify({
          vehicleId: selectedVehicle._id,
          customerName,
          customerPhone,
          customerEmail: customerEmail || undefined,
          customerLicenseNumber: customerLicenseNumber || undefined,
          pickupDate: pickup,
          returnDate: ret,
          pickupLocation: pickupLocation || undefined,
          dropoffLocation: dropoffLocation || undefined,
          durationDays: pricing.durationDays,
          dailyRate: pricing.dailyRate / 100,
          totalAmount: pricing.totalAmount / 100,
          depositAmount: selectedVehicle.depositAmount
            ? selectedVehicle.depositAmount / 100
            : undefined,
          depositPaid,
          depositPaymentId: depositPaymentId || undefined,
          depositPaymentMethod: depositPaid ? depositPaymentMethod : undefined,
          agreementNumber: agreementNumber || undefined,
          notes: notes || undefined,
        }),
      });

      const result = await res.json();
      if (!res.ok) {
        throw new Error(result.error || "Failed to create rental");
      }

      // Send deposit payment link via email if requested
      if (
        sendDepositLink &&
        customerEmail &&
        selectedVehicle.depositAmount &&
        result.id
      ) {
        try {
          setSendingLink(true);
          await fetchWithCSRF("/api/dashboard/rentals/deposit-link", {
            method: "POST",
            body: JSON.stringify({
              rentalId: result.id,
              customerEmail,
              customerName,
              depositAmount: selectedVehicle.depositAmount / 100,
              vehicleName: `${selectedVehicle.make} ${selectedVehicle.model} ${selectedVehicle.year}`,
              agreementNumber: agreementNumber || undefined,
            }),
          });
        } catch {
          // Non-fatal — rental was already created
          console.error("Failed to send deposit link email");
        } finally {
          setSendingLink(false);
        }
      }

      onCreated();
      onClose();
    } catch (e) {
      setError(
        e instanceof Error ? e.message : isAr ? "حدث خطأ" : "An error occurred",
      );
    } finally {
      setSubmitting(false);
    }
  };

  if (!isOpen) return null;

  const inputClass =
    "w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30";
  const stepLabels = isAr
    ? ["التواريخ والموقع", "اختر المركبة", "بيانات العميل"]
    : ["Dates & Location", "Select Vehicle", "Customer Details"];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">
              {isAr ? "حجز جديد" : "New Rental"}
            </h2>
            <p className="text-sm text-slate-500">
              {isAr
                ? `الخطوة ${step} من 3 — ${stepLabels[step - 1]}`
                : `Step ${step} of 3 — ${stepLabels[step - 1]}`}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-slate-600 rounded-lg"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Step indicator */}
        <div className="px-6 pt-4">
          <div className="flex gap-2">
            {[1, 2, 3].map((s) => (
              <div
                key={s}
                className={`h-1.5 flex-1 rounded-full ${s <= step ? "bg-brand-green" : "bg-slate-200"}`}
              />
            ))}
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-6">
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
              {error}
            </div>
          )}

          {/* Step 1: Dates & Location */}
          {step === 1 && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    {isAr ? "تاريخ الاستلام" : "Pickup Date"} *
                  </label>
                  <input
                    type="date"
                    value={pickupDate}
                    onChange={(e) => setPickupDate(e.target.value)}
                    min={new Date().toISOString().split("T")[0]}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <Calendar className="w-3 h-3" />
                    {isAr ? "تاريخ الإرجاع" : "Return Date"} *
                  </label>
                  <input
                    type="date"
                    value={returnDate}
                    onChange={(e) => setReturnDate(e.target.value)}
                    min={pickupDate || new Date().toISOString().split("T")[0]}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <MapPin className="w-3 h-3" />
                    {isAr ? "موقع الاستلام" : "Pickup Location"}
                  </label>
                  <input
                    value={pickupLocation}
                    onChange={(e) => setPickupLocation(e.target.value)}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <MapPin className="w-3 h-3" />
                    {isAr ? "موقع التسليم" : "Dropoff Location"}
                  </label>
                  <input
                    value={dropoffLocation}
                    onChange={(e) => setDropoffLocation(e.target.value)}
                    className={inputClass}
                  />
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Select Vehicle */}
          {step === 2 && (
            <div className="space-y-3">
              {/* Search */}
              {!loading && vehicles.length > 0 && (
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <input
                    type="text"
                    value={vehicleSearch}
                    onChange={(e) => setVehicleSearch(e.target.value)}
                    placeholder={
                      isAr
                        ? "ابحث بالمركبة، اللوحة، أو السنة..."
                        : "Search by vehicle, plate, or year..."
                    }
                    className="w-full pl-9 pr-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30"
                  />
                </div>
              )}
              {loading ? (
                <div className="flex items-center justify-center py-12">
                  <Loader2 className="w-6 h-6 animate-spin text-slate-400" />
                </div>
              ) : vehicles.length === 0 ? (
                <div className="text-center py-12">
                  <Car className="w-12 h-12 text-slate-300 mx-auto mb-3" />
                  <p className="text-slate-500 text-sm">
                    {isAr ? "لا توجد مركبات متاحة" : "No available vehicles"}
                  </p>
                </div>
              ) : (
                vehicles
                  .filter((v) => {
                    if (!vehicleSearch.trim()) return true;
                    const q = vehicleSearch.toLowerCase();
                    return (
                      v.make.toLowerCase().includes(q) ||
                      v.model.toLowerCase().includes(q) ||
                      String(v.year).includes(q) ||
                      (v.licensePlate?.toLowerCase().includes(q) ?? false) ||
                      v.type.toLowerCase().includes(q) ||
                      (v.color?.toLowerCase().includes(q) ?? false)
                    );
                  })
                  .map((v) => (
                  <button
                    key={v._id}
                    onClick={() => setSelectedVehicle(v)}
                    className={`w-full text-left p-4 border rounded-xl transition-colors ${
                      selectedVehicle?._id === v._id
                        ? "border-brand-green bg-brand-green/5 ring-2 ring-brand-green/20"
                        : "border-slate-200 hover:border-slate-300"
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center">
                          <Car className="w-5 h-5 text-slate-500" />
                        </div>
                        <div>
                          <p className="font-medium text-slate-900 text-sm">
                            {v.make} {v.model} {v.year}
                          </p>
                          <p className="text-xs text-slate-500">
                            {isAr
                              ? VEHICLE_TYPE_LABELS[v.type].ar
                              : VEHICLE_TYPE_LABELS[v.type].en}
                            {v.seats &&
                              ` · ${v.seats} ${isAr ? "مقاعد" : "seats"}`}
                            {v.licensePlate && ` · ${v.licensePlate}`}
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="font-semibold text-slate-900 text-sm">
                          {formatVehiclePrice(v.pricePerDay, v.currency)}
                        </p>
                        <p className="text-xs text-slate-500">
                          {isAr ? "/يوم" : "/day"}
                        </p>
                      </div>
                    </div>
                    {selectedVehicle?._id === v._id && (
                      <div className="mt-2 flex items-center gap-1 text-brand-green text-xs">
                        <Check className="w-3 h-3" />
                        {isAr ? "تم الاختيار" : "Selected"}
                      </div>
                    )}
                  </button>
                ))
              )}

              {/* Pricing summary after vehicle selection */}
              {pricing && selectedVehicle && (
                <div className="border border-slate-200 rounded-xl p-4 bg-slate-50 space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-slate-600">
                      {isAr ? "المدة" : "Duration"}
                    </span>
                    <span className="font-medium">
                      {pricing.durationDays} {isAr ? "يوم" : "days"}
                    </span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-slate-600">
                      {isAr ? "السعر اليومي" : "Daily Rate"}
                    </span>
                    <span className="font-medium">
                      {formatVehiclePrice(
                        pricing.dailyRate,
                        selectedVehicle.currency,
                      )}
                    </span>
                  </div>
                  {selectedVehicle.depositAmount && (
                    <div className="flex justify-between text-sm">
                      <span className="text-slate-600">
                        {isAr ? "التأمين" : "Deposit"}
                      </span>
                      <span className="font-medium">
                        {formatVehiclePrice(
                          selectedVehicle.depositAmount,
                          selectedVehicle.currency,
                        )}
                      </span>
                    </div>
                  )}
                  <div className="border-t pt-2 flex justify-between text-sm">
                    <span className="font-semibold text-slate-900">
                      {isAr ? "الإجمالي" : "Total"}
                    </span>
                    <span className="font-bold text-brand-green text-base">
                      {formatVehiclePrice(
                        pricing.totalAmount,
                        selectedVehicle.currency,
                      )}
                    </span>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Step 3: Customer Details */}
          {step === 3 && (
            <div className="space-y-4">
              {/* Existing Customer Picker */}
              {existingCustomers.length > 0 && (
                <div className="relative">
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <Search className="w-3 h-3" />
                    {isAr
                      ? "ابحث عن عميل حالي أو أدخل بيانات جديدة"
                      : "Search existing customer or enter new details"}
                  </label>
                  <input
                    value={customerQuery}
                    onChange={(e) => {
                      setCustomerQuery(e.target.value);
                      setShowCustomerDropdown(true);
                    }}
                    onFocus={() => setShowCustomerDropdown(true)}
                    placeholder={
                      isAr
                        ? "اكتب اسم أو رقم العميل..."
                        : "Type customer name or phone..."
                    }
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-green/30"
                  />
                  {showCustomerDropdown && filteredCustomers.length > 0 && (
                    <>
                      <div
                        className="fixed inset-0 z-40"
                        onClick={() => setShowCustomerDropdown(false)}
                      />
                      <div className="absolute left-0 right-0 top-full mt-1 z-50 bg-white border border-slate-200 rounded-xl shadow-lg max-h-48 overflow-y-auto">
                        {filteredCustomers.map((c) => (
                          <button
                            key={c.id}
                            type="button"
                            onClick={() => selectCustomer(c)}
                            className="w-full text-left px-4 py-2.5 hover:bg-slate-50 transition-colors flex items-center justify-between"
                          >
                            <div>
                              <p className="text-sm font-medium text-slate-900">
                                {c.name}
                              </p>
                              <p className="text-xs text-slate-500">
                                {c.phone}
                                {c.email ? ` · ${c.email}` : ""}
                              </p>
                            </div>
                            <User className="w-3.5 h-3.5 text-slate-300" />
                          </button>
                        ))}
                      </div>
                    </>
                  )}
                  {loadingCustomers && (
                    <div className="absolute right-3 top-[calc(50%+8px)] -translate-y-1/2">
                      <Loader2 className="w-4 h-4 animate-spin text-slate-400" />
                    </div>
                  )}
                </div>
              )}

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-slate-600 mb-1 flex items-center gap-1">
                    <User className="w-3 h-3" />
                    {isAr ? "اسم العميل" : "Customer Name"} *
                  </label>
                  <input
                    value={customerName}
                    onChange={(e) => setCustomerName(e.target.value)}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "رقم الهاتف" : "Phone"} *
                  </label>
                  <input
                    value={customerPhone}
                    onChange={(e) => setCustomerPhone(e.target.value)}
                    placeholder="+974 5xxx xxxx"
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "البريد الإلكتروني" : "Email"}
                  </label>
                  <input
                    type="email"
                    value={customerEmail}
                    onChange={(e) => setCustomerEmail(e.target.value)}
                    className={inputClass}
                  />
                </div>
                <div>
                  <label className="text-xs text-slate-600 mb-1 block">
                    {isAr ? "رقم الرخصة" : "License Number"}
                  </label>
                  <input
                    value={customerLicenseNumber}
                    onChange={(e) => setCustomerLicenseNumber(e.target.value)}
                    className={inputClass}
                  />
                </div>
              </div>
              <div>
                <label className="text-xs text-slate-600 mb-1 block">
                  {isAr ? "ملاحظات" : "Notes"}
                </label>
                <textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  rows={2}
                  className={inputClass}
                />
              </div>

              {/* Agreement Number */}
              <div>
                <label className="text-xs text-slate-600 mb-1 block">
                  {isAr ? "رقم العقد" : "Agreement Number"}
                </label>
                <input
                  value={agreementNumber}
                  onChange={(e) => setAgreementNumber(e.target.value)}
                  placeholder={isAr ? "AGR-0001" : "AGR-0001"}
                  className={inputClass}
                />
              </div>

              {/* Deposit Payment */}
              {selectedVehicle?.depositAmount && (
                <div className="border border-slate-200 rounded-xl p-4 bg-slate-50 space-y-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm font-medium text-slate-900">
                        {isAr ? "التأمين / الإيداع" : "Deposit Payment"}
                      </p>
                      <p className="text-xs text-slate-500">
                        {formatVehiclePrice(
                          selectedVehicle.depositAmount,
                          selectedVehicle.currency,
                        )}
                      </p>
                    </div>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={depositPaid}
                        onChange={(e) => setDepositPaid(e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-brand-green/30 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-slate-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand-green" />
                      <span className="ms-2 text-xs font-medium text-slate-700">
                        {depositPaid
                          ? isAr
                            ? "تم الدفع"
                            : "Paid"
                          : isAr
                            ? "لم يتم الدفع"
                            : "Not Paid"}
                      </span>
                    </label>
                  </div>

                  {depositPaid && (
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="text-xs text-slate-600 mb-1 block">
                          {isAr ? "طريقة الدفع" : "Payment Method"}
                        </label>
                        <select
                          value={depositPaymentMethod}
                          onChange={(e) =>
                            setDepositPaymentMethod(e.target.value)
                          }
                          className={inputClass}
                        >
                          <option value="cash">
                            {isAr ? "نقداً" : "Cash"}
                          </option>
                          <option value="card">
                            {isAr ? "بطاقة" : "Card"}
                          </option>
                          <option value="bank_transfer">
                            {isAr ? "تحويل بنكي" : "Bank Transfer"}
                          </option>
                          <option value="mada">Mada</option>
                          <option value="apple_pay">Apple Pay</option>
                        </select>
                      </div>
                      <div>
                        <label className="text-xs text-slate-600 mb-1 block">
                          {isAr ? "رقم الإيصال / المعاملة" : "Receipt / Transaction ID"}
                        </label>
                        <input
                          value={depositPaymentId}
                          onChange={(e) => setDepositPaymentId(e.target.value)}
                          placeholder={isAr ? "اختياري" : "Optional"}
                          className={inputClass}
                        />
                      </div>
                    </div>
                  )}

                  {/* Send Deposit Link via Email */}
                  {!depositPaid && (
                    <div className="border-t border-slate-200 pt-3">
                      {hasStripeKeys ? (
                        <label className="flex items-center gap-3 cursor-pointer">
                          <input
                            type="checkbox"
                            checked={sendDepositLink}
                            onChange={(e) =>
                              setSendDepositLink(e.target.checked)
                            }
                            className="w-4 h-4 rounded border-slate-300 text-brand-green focus:ring-brand-green"
                          />
                          <div className="flex items-center gap-2">
                            <Mail className="w-4 h-4 text-blue-500" />
                            <div>
                              <p className="text-sm font-medium text-slate-700">
                                {isAr
                                  ? "إرسال رابط دفع التأمين بالبريد"
                                  : "Send deposit payment link via email"}
                              </p>
                              {customerEmail ? (
                                <p className="text-xs text-slate-500">
                                  {isAr ? "سيُرسل إلى" : "Will be sent to"}{" "}
                                  {customerEmail}
                                </p>
                              ) : (
                                <p className="text-xs text-amber-600">
                                  {isAr
                                    ? "يرجى إدخال البريد الإلكتروني أعلاه"
                                    : "Please enter customer email above"}
                                </p>
                              )}
                            </div>
                          </div>
                        </label>
                      ) : (
                        <div className="flex items-start gap-2 text-xs text-slate-500 bg-slate-100 rounded-lg p-3">
                          <AlertTriangle className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
                          <div>
                            <p className="font-medium text-slate-700">
                              {isAr
                                ? "رابط الدفع الإلكتروني غير متاح"
                                : "Online payment link unavailable"}
                            </p>
                            <p>
                              {isAr
                                ? "يجب إعداد مفاتيح Stripe في الإعدادات أولاً لإرسال روابط الدفع"
                                : "Set up Stripe keys in Settings first to send payment links"}
                            </p>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between p-6 border-t">
          <button
            onClick={() => (step > 1 ? setStep((step - 1) as Step) : onClose())}
            className="flex items-center gap-1 px-4 py-2 text-sm text-slate-600 hover:text-slate-800"
          >
            <ChevronLeft className="w-4 h-4" />
            {step > 1 ? (isAr ? "السابق" : "Back") : isAr ? "إغلاق" : "Close"}
          </button>
          {step < 3 ? (
            <button
              onClick={() => setStep((step + 1) as Step)}
              disabled={!canGoNext()}
              className="flex items-center gap-1 px-6 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 disabled:opacity-50"
            >
              {isAr ? "التالي" : "Next"}
              <ChevronRight className="w-4 h-4" />
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={!canGoNext() || submitting}
              className="flex items-center gap-2 px-6 py-2 bg-brand-green text-white rounded-lg text-sm font-medium hover:bg-brand-green/90 disabled:opacity-50"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              {isAr ? "إنشاء الحجز" : "Create Rental"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
