import React, { useEffect, useState } from 'react';
import { 
  Tag,
  Search,
  Plus,
  Edit,
  Trash2,
  Filter,
  X,
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import Pagination from '../../shared/components/Pagination';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { useCurrency } from '../../features/payments/contexts/CurrencyContext';
import promotionService, { Promotion } from '../../features/loyalty/services/promotionService';
import { getRoomTypes } from '../../features/rooms/services/roomService';

interface RoomType {
  id: number;
  name: string;
}

const PromotionsManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const { currency } = useCurrency();
  
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [promotionsLoading, setPromotionsLoading] = useState(true);
  const [showPromotionModal, setShowPromotionModal] = useState(false);
  const [editingPromotion, setEditingPromotion] = useState<Promotion | null>(null);
  const [promotionFilters, setPromotionFilters] = useState({
    search: '',
    status: '',
    type: '',
  });
  const [promotionsCurrentPage, setPromotionsCurrentPage] = useState(1);
  const [promotionsTotalPages, setPromotionsTotalPages] = useState(1);
  const [promotionsTotalItems, setPromotionsTotalItems] = useState(0);
  const promotionsPerPage = 5;

  const [promotionFormData, setPromotionFormData] = useState({
    code: '',
    name: '',
    description: '',
    discount_type: 'percentage' as 'percentage' | 'fixed',
    discount_value: 0,
    min_booking_amount: 0,
    max_discount_amount: 0,
    min_stay_days: 0,
    max_stay_days: 0,
    advance_booking_days: 0,
    max_advance_booking_days: 0,
    allowed_check_in_days: [] as number[],
    allowed_check_out_days: [] as number[],
    allowed_room_type_ids: [] as number[],
    excluded_room_type_ids: [] as number[],
    min_guests: 0,
    max_guests: 0,
    first_time_customer_only: false,
    repeat_customer_only: false,
    blackout_dates: [] as string[],
    start_date: '',
    end_date: '',
    usage_limit: 0,
    status: 'active' as 'active' | 'inactive' | 'expired',
  });
  
  const [roomTypes, setRoomTypes] = useState<RoomType[]>([]);

  useEffect(() => {
    fetchPromotions();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [promotionFilters, promotionsCurrentPage]);

  useEffect(() => {
    fetchRoomTypes();
  }, []);

  useEffect(() => {
    setPromotionsCurrentPage(1);
  }, [promotionFilters]);

  const fetchRoomTypes = async () => {
    try {
      const response = await getRoomTypes();
      if (response.success && response.data.room_types) {
        setRoomTypes(response.data.room_types);
      }
    } catch (error: unknown) {
      console.error('Failed to fetch room types:', error);
    }
  };

  const fetchPromotions = async () => {
    try {
      setPromotionsLoading(true);
      const response = await promotionService.getPromotions({
        ...promotionFilters,
        page: promotionsCurrentPage,
        limit: promotionsPerPage,
      });
      setPromotions(response.data.promotions);
      if (response.data.pagination) {
        setPromotionsTotalPages(response.data.pagination.totalPages);
        setPromotionsTotalItems(response.data.pagination.total);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load promotions list');
    } finally {
      setPromotionsLoading(false);
    }
  };

  const handlePromotionSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const submitData: Record<string, unknown> = {
        ...promotionFormData,
        min_stay_days: promotionFormData.min_stay_days || undefined,
        max_stay_days: promotionFormData.max_stay_days || undefined,
        advance_booking_days: promotionFormData.advance_booking_days || undefined,
        max_advance_booking_days: promotionFormData.max_advance_booking_days || undefined,
        min_guests: promotionFormData.min_guests || undefined,
        max_guests: promotionFormData.max_guests || undefined,
        allowed_check_in_days: promotionFormData.allowed_check_in_days?.length ? promotionFormData.allowed_check_in_days : undefined,
        allowed_check_out_days: promotionFormData.allowed_check_out_days?.length ? promotionFormData.allowed_check_out_days : undefined,
        allowed_room_type_ids: promotionFormData.allowed_room_type_ids?.length ? promotionFormData.allowed_room_type_ids : undefined,
        excluded_room_type_ids: promotionFormData.excluded_room_type_ids?.length ? promotionFormData.excluded_room_type_ids : undefined,
        blackout_dates: promotionFormData.blackout_dates?.length ? promotionFormData.blackout_dates : undefined,
        min_booking_amount: promotionFormData.min_booking_amount || undefined,
        max_discount_amount: promotionFormData.max_discount_amount || undefined,
        usage_limit: promotionFormData.usage_limit || undefined,
      };
      
      if (editingPromotion) {
        await promotionService.updatePromotion(editingPromotion.id, submitData);
        toast.success('Promotion updated successfully');
      } else {
        await promotionService.createPromotion(submitData);
        toast.success('Promotion added successfully');
      }
      setShowPromotionModal(false);
      resetPromotionForm();
      fetchPromotions();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'An error occurred');
    }
  };

  const handleEditPromotion = (promotion: Promotion) => {
    setEditingPromotion(promotion);
    setPromotionFormData({
      code: promotion.code,
      name: promotion.name,
      description: promotion.description || '',
      discount_type: promotion.discount_type,
      discount_value: promotion.discount_value,
      min_booking_amount: promotion.min_booking_amount || 0,
      max_discount_amount: promotion.max_discount_amount || 0,
      min_stay_days: promotion.min_stay_days || 0,
      max_stay_days: promotion.max_stay_days || 0,
      advance_booking_days: promotion.advance_booking_days || 0,
      max_advance_booking_days: promotion.max_advance_booking_days || 0,
      allowed_check_in_days: promotion.allowed_check_in_days || [],
      allowed_check_out_days: promotion.allowed_check_out_days || [],
      allowed_room_type_ids: promotion.allowed_room_type_ids || [],
      excluded_room_type_ids: promotion.excluded_room_type_ids || [],
      min_guests: promotion.min_guests || 0,
      max_guests: promotion.max_guests || 0,
      first_time_customer_only: promotion.first_time_customer_only || false,
      repeat_customer_only: promotion.repeat_customer_only || false,
      blackout_dates: promotion.blackout_dates || [],
      start_date: promotion.start_date?.split('T')[0] || '',
      end_date: promotion.end_date?.split('T')[0] || '',
      usage_limit: promotion.usage_limit || 0,
      status: promotion.status,
    });
    setShowPromotionModal(true);
  };

  const handleDeletePromotion = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this promotion?')) return;
    
    try {
      await promotionService.deletePromotion(id);
      toast.success('Promotion deleted successfully');
      fetchPromotions();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to delete promotion');
    }
  };

  const resetPromotionForm = () => {
    setEditingPromotion(null);
    setPromotionFormData({
      code: '',
      name: '',
      description: '',
      discount_type: 'percentage',
      discount_value: 0,
      min_booking_amount: 0,
      max_discount_amount: 0,
      min_stay_days: 0,
      max_stay_days: 0,
      advance_booking_days: 0,
      max_advance_booking_days: 0,
      allowed_check_in_days: [],
      allowed_check_out_days: [],
      allowed_room_type_ids: [],
      excluded_room_type_ids: [],
      min_guests: 0,
      max_guests: 0,
      first_time_customer_only: false,
      repeat_customer_only: false,
      blackout_dates: [],
      start_date: '',
      end_date: '',
      usage_limit: 0,
      status: 'active',
    });
  };

  const getPromotionStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      active: { bg: 'bg-gradient-to-r from-emerald-50 to-green-50', text: 'text-emerald-800', label: 'Active', border: 'border-emerald-200' },
      inactive: { bg: 'bg-gradient-to-r from-slate-50 to-gray-50', text: 'text-slate-700', label: 'Inactive', border: 'border-slate-200' },
      expired: { bg: 'bg-gradient-to-r from-rose-50 to-red-50', text: 'text-rose-800', label: 'Expired', border: 'border-rose-200' },
    };
    const badge = badges[status] || badges.active;
    return (
      <span className={`px-4 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 -m-6 p-8">
      <div className="space-y-8">
        {}
        <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="p-2.5 rounded-xl bg-gradient-to-br from-purple-500/10 to-pink-500/10 border border-purple-200/40">
                  <Tag className="w-6 h-6 text-purple-600" />
                </div>
                <h2 className="text-3xl font-extrabold text-gray-900">Promotion Management</h2>
              </div>
              <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                Manage discount codes and promotional campaigns
              </p>
            </div>
            <button
              onClick={() => {
                resetPromotionForm();
                setShowPromotionModal(true);
              }}
              className="group relative px-8 py-4 bg-gradient-to-r from-purple-500 via-purple-500 to-pink-600 text-white font-semibold rounded-xl shadow-xl shadow-purple-500/30 hover:shadow-2xl hover:shadow-purple-500/40 transition-all duration-300 hover:scale-105 overflow-hidden"
            >
              <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
              <div className="relative flex items-center gap-3">
                <Plus className="w-5 h-5" />
                Add Promotion
              </div>
            </button>
          </div>
        </div>

        {}
        <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
          <div className="flex items-center gap-3 mb-6">
            <div className="p-2 rounded-xl bg-gradient-to-br from-amber-500/10 to-amber-600/10 border border-amber-200/40">
              <Filter className="w-5 h-5 text-amber-600" />
            </div>
            <h3 className="text-xl font-bold text-gray-900">Filters</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
            <div className="relative group">
              <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 group-focus-within:text-purple-500 transition-colors" />
              <input
                type="text"
                placeholder="Search by code or name..."
                value={promotionFilters.search}
                onChange={(e) => setPromotionFilters({ ...promotionFilters, search: e.target.value })}
                className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 placeholder-gray-400 font-medium shadow-sm hover:shadow-md"
              />
            </div>
            <select
              value={promotionFilters.type}
              onChange={(e) => setPromotionFilters({ ...promotionFilters, type: e.target.value })}
              className="px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
            >
              <option value="">All Types</option>
              <option value="percentage">Percentage</option>
              <option value="fixed">Fixed Amount</option>
            </select>
            <select
              value={promotionFilters.status}
              onChange={(e) => setPromotionFilters({ ...promotionFilters, status: e.target.value })}
              className="px-4 py-3.5 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
            >
              <option value="">All Statuses</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </div>

        {}
        {promotionsLoading && promotions.length === 0 ? (
          <Loading fullScreen text="Loading promotions..." />
        ) : (
          <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                  <tr>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Code</th>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Program Name</th>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Value</th>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Period</th>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Used</th>
                    <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Status</th>
                    <th className="px-8 py-5 text-right text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Actions</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-100">
                  {promotions.map((promotion) => (
                    <tr key={promotion.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-8 py-5 whitespace-nowrap">
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-gradient-to-br from-purple-100 to-purple-200 rounded-lg">
                            <Tag className="w-4 h-4 text-purple-600" />
                          </div>
                          <span className="text-sm font-mono font-bold bg-gradient-to-r from-purple-600 to-purple-700 bg-clip-text text-transparent">{promotion.code}</span>
                        </div>
                      </td>
                      <td className="px-8 py-5">
                        <div className="text-sm font-semibold text-gray-900">{promotion.name}</div>
                        <div className="text-xs text-gray-500 mt-0.5">{promotion.description}</div>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        <div className="text-sm font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent">
                          {promotion.discount_type === 'percentage' 
                            ? `${promotion.discount_value}%` 
                            : formatCurrency(promotion.discount_value)}
                        </div>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        <div className="text-xs text-gray-600">
                          {promotion.start_date ? new Date(promotion.start_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : 'N/A'}
                          <span className="text-gray-400 mx-1">→</span>
                          {promotion.end_date ? new Date(promotion.end_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : 'N/A'}
                        </div>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        <div className="text-sm font-medium text-gray-700">
                          <span className="text-purple-600 font-semibold">{promotion.used_count || 0}</span>
                          <span className="text-gray-400 mx-1">/</span>
                          <span className="text-gray-600">{promotion.usage_limit || '∞'}</span>
                        </div>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        {getPromotionStatusBadge(promotion.status)}
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => handleEditPromotion(promotion)}
                            className="p-2 rounded-lg text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-all duration-200 shadow-sm hover:shadow-md border border-blue-200 hover:border-blue-300"
                            title="Edit"
                          >
                            <Edit className="w-5 h-5" />
                          </button>
                          <button
                            onClick={() => handleDeletePromotion(promotion.id)}
                            className="p-2 rounded-lg text-rose-600 hover:text-rose-700 hover:bg-rose-50 transition-all duration-200 shadow-sm hover:shadow-md border border-rose-200 hover:border-rose-300"
                            title="Delete"
                          >
                            <Trash2 className="w-5 h-5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination
              currentPage={promotionsCurrentPage}
              totalPages={promotionsTotalPages}
              onPageChange={setPromotionsCurrentPage}
              totalItems={promotionsTotalItems}
              itemsPerPage={promotionsPerPage}
            />
          </div>
        )}
      </div>

      {}
      {showPromotionModal && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-md z-50 overflow-y-auto p-3 sm:p-4">
          <div className="min-h-full flex items-center justify-center py-4">
            <div className="bg-white rounded-2xl sm:rounded-3xl shadow-2xl max-w-5xl w-full my-4 flex flex-col border border-gray-200" style={{ maxHeight: 'calc(100vh - 2rem)' }}>
              <div className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 px-4 sm:px-6 md:px-8 py-4 sm:py-5 md:py-6 border-b border-slate-700 flex-shrink-0">
                <div className="flex justify-between items-center">
                  <div>
                    <h2 className="text-xl sm:text-2xl md:text-3xl font-bold text-purple-100 mb-1">
                      {editingPromotion ? 'Update Promotion' : 'Add New Promotion'}
                    </h2>
                    <p className="text-purple-200/80 text-xs sm:text-sm font-light">
                      {editingPromotion ? 'Modify promotion details' : 'Create a new promotion program'}
                    </p>
                  </div>
                  <button 
                    onClick={() => setShowPromotionModal(false)}
                    className="w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-xl text-purple-100 hover:text-white hover:bg-slate-700/50 transition-all duration-200 border border-slate-600 hover:border-purple-400"
                  >
                    <X className="w-5 h-5 sm:w-6 sm:h-6" />
                  </button>
                </div>
              </div>
              
              <div className="flex-1 overflow-y-auto min-h-0">
                <form onSubmit={handlePromotionSubmit} className="p-4 sm:p-6 md:p-8 space-y-4 sm:space-y-5 md:space-y-6">
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Code <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        value={promotionFormData.code}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, code: e.target.value.toUpperCase() })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm font-mono"
                        placeholder="e.g: SUMMER2024"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Program Name <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        value={promotionFormData.name}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, name: e.target.value })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        placeholder="e.g: Summer Sale"
                        required
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                      Description
                    </label>
                    <textarea
                      value={promotionFormData.description}
                      onChange={(e) => setPromotionFormData({ ...promotionFormData, description: e.target.value })}
                      className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                      rows={3}
                      placeholder="Detailed description of the program..."
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Discount Type <span className="text-red-500">*</span>
                      </label>
                      <select
                        value={promotionFormData.discount_type}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, discount_type: e.target.value as 'percentage' | 'fixed' })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm cursor-pointer"
                      >
                        <option value="percentage">Percentage (%)</option>
                        <option value="fixed">Fixed Amount ({currency})</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Discount Value <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.discount_value}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, discount_value: parseFloat(e.target.value) })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                        max={promotionFormData.discount_type === 'percentage' ? 100 : undefined}
                        required
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Minimum Order Value ({currency})
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.min_booking_amount}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, min_booking_amount: parseFloat(e.target.value) })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Maximum Discount ({currency})
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.max_discount_amount}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, max_discount_amount: parseFloat(e.target.value) })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                      />
                    </div>
                  </div>

                  {/* Enterprise Booking Conditions Section */}
                  <div className="border-t-2 border-purple-200 pt-6 mt-6">
                    <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                      <div className="h-1 w-8 bg-gradient-to-r from-purple-400 to-purple-600 rounded-full"></div>
                      Enterprise Booking Conditions
                    </h3>
                    <p className="text-sm text-gray-600 mb-6">Configure advanced conditions for when this promotion applies</p>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Minimum Stay (nights)
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.min_stay_days || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, min_stay_days: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                        placeholder="0 = no minimum"
                      />
                      <p className="text-xs text-gray-500 mt-1">Minimum number of nights required for booking</p>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Advance Booking (days)
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.advance_booking_days || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, advance_booking_days: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                        placeholder="0 = no requirement"
                      />
                      <p className="text-xs text-gray-500 mt-1">Minimum days in advance the booking must be made</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Maximum Stay (nights)
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.max_stay_days || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, max_stay_days: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                        placeholder="0 = no maximum"
                      />
                      <p className="text-xs text-gray-500 mt-1">Maximum number of nights allowed for booking</p>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Max Advance Booking (days)
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.max_advance_booking_days || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, max_advance_booking_days: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                        placeholder="0 = no maximum"
                      />
                      <p className="text-xs text-gray-500 mt-1">Maximum days in advance the booking can be made</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Allowed Check-in Days
                      </label>
                      <div className="grid grid-cols-7 gap-2">
                        {['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map((day, index) => (
                          <label key={day} className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={promotionFormData.allowed_check_in_days?.includes(index) || false}
                              onChange={(e) => {
                                const current = promotionFormData.allowed_check_in_days || [];
                                if (e.target.checked) {
                                  setPromotionFormData({ ...promotionFormData, allowed_check_in_days: [...current, index] });
                                } else {
                                  setPromotionFormData({ ...promotionFormData, allowed_check_in_days: current.filter(d => d !== index) });
                                }
                              }}
                              className="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                            />
                            <span className="text-xs text-gray-700">{day}</span>
                          </label>
                        ))}
                      </div>
                      <p className="text-xs text-gray-500 mt-1">Leave empty to allow all days</p>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Allowed Check-out Days
                      </label>
                      <div className="grid grid-cols-7 gap-2">
                        {['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map((day, index) => (
                          <label key={day} className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={promotionFormData.allowed_check_out_days?.includes(index) || false}
                              onChange={(e) => {
                                const current = promotionFormData.allowed_check_out_days || [];
                                if (e.target.checked) {
                                  setPromotionFormData({ ...promotionFormData, allowed_check_out_days: [...current, index] });
                                } else {
                                  setPromotionFormData({ ...promotionFormData, allowed_check_out_days: current.filter(d => d !== index) });
                                }
                              }}
                              className="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                            />
                            <span className="text-xs text-gray-700">{day}</span>
                          </label>
                        ))}
                      </div>
                      <p className="text-xs text-gray-500 mt-1">Leave empty to allow all days</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Allowed Room Types
                      </label>
                      <select
                        multiple
                        value={promotionFormData.allowed_room_type_ids?.map(String) || []}
                        onChange={(e) => {
                          const selected = Array.from(e.target.selectedOptions, option => parseInt(option.value));
                          setPromotionFormData({ ...promotionFormData, allowed_room_type_ids: selected });
                        }}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        size={4}
                      >
                        {roomTypes.map(rt => (
                          <option key={rt.id} value={rt.id}>{rt.name}</option>
                        ))}
                      </select>
                      <p className="text-xs text-gray-500 mt-1">Hold Ctrl/Cmd to select multiple. Leave empty to allow all room types.</p>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Excluded Room Types
                      </label>
                      <select
                        multiple
                        value={promotionFormData.excluded_room_type_ids?.map(String) || []}
                        onChange={(e) => {
                          const selected = Array.from(e.target.selectedOptions, option => parseInt(option.value));
                          setPromotionFormData({ ...promotionFormData, excluded_room_type_ids: selected });
                        }}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        size={4}
                      >
                        {roomTypes.map(rt => (
                          <option key={rt.id} value={rt.id}>{rt.name}</option>
                        ))}
                      </select>
                      <p className="text-xs text-gray-500 mt-1">Hold Ctrl/Cmd to select multiple. These room types cannot use this promotion.</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Minimum Guests
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.min_guests || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, min_guests: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="1"
                        placeholder="0 = no minimum"
                      />
                      <p className="text-xs text-gray-500 mt-1">Minimum number of guests required</p>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Maximum Guests
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.max_guests || ''}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, max_guests: parseInt(e.target.value) || 0 })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="1"
                        placeholder="0 = no maximum"
                      />
                      <p className="text-xs text-gray-500 mt-1">Maximum number of guests allowed</p>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="flex items-center gap-3 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={promotionFormData.first_time_customer_only || false}
                          onChange={(e) => setPromotionFormData({ ...promotionFormData, first_time_customer_only: e.target.checked, repeat_customer_only: e.target.checked ? false : promotionFormData.repeat_customer_only })}
                          className="w-5 h-5 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                        />
                        <span className="text-sm font-semibold text-gray-700">First-Time Customer Only</span>
                      </label>
                      <p className="text-xs text-gray-500 mt-1 ml-8">Only available to first-time customers</p>
                    </div>
                    <div>
                      <label className="flex items-center gap-3 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={promotionFormData.repeat_customer_only || false}
                          onChange={(e) => setPromotionFormData({ ...promotionFormData, repeat_customer_only: e.target.checked, first_time_customer_only: e.target.checked ? false : promotionFormData.first_time_customer_only })}
                          className="w-5 h-5 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                        />
                        <span className="text-sm font-semibold text-gray-700">Repeat Customer Only</span>
                      </label>
                      <p className="text-xs text-gray-500 mt-1 ml-8">Only available to returning customers</p>
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                      Blackout Dates
                    </label>
                    <textarea
                      value={promotionFormData.blackout_dates?.join('\n') || ''}
                      onChange={(e) => {
                        const dates = e.target.value.split('\n').filter(d => d.trim()).map(d => d.trim());
                        setPromotionFormData({ ...promotionFormData, blackout_dates: dates });
                      }}
                      className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                      rows={3}
                      placeholder="Enter dates (one per line) in YYYY-MM-DD format&#10;Example:&#10;2024-12-25&#10;2024-12-31&#10;2025-01-01"
                    />
                    <p className="text-xs text-gray-500 mt-1">Dates when promotion doesn't apply. One date per line (YYYY-MM-DD format).</p>
                  </div>

                  {/* Dates & Status Section */}
                  <div className="border-t-2 border-purple-200 pt-6 mt-6">
                    <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                      <div className="h-1 w-8 bg-gradient-to-r from-purple-400 to-purple-600 rounded-full"></div>
                      Promotion Period & Status
                    </h3>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Start Date <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="date"
                        value={promotionFormData.start_date}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, start_date: e.target.value })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        required
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        End Date <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="date"
                        value={promotionFormData.end_date}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, end_date: e.target.value })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        required
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Usage Limit (0 = unlimited)
                      </label>
                      <input
                        type="number"
                        value={promotionFormData.usage_limit}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, usage_limit: parseInt(e.target.value) })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm"
                        min="0"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-600 uppercase tracking-wider mb-2">
                        Status
                      </label>
                      <select
                        value={promotionFormData.status}
                        onChange={(e) => setPromotionFormData({ ...promotionFormData, status: e.target.value as 'active' | 'inactive' })}
                        className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-purple-400 focus:ring-4 focus:ring-purple-100 transition-all duration-200 text-gray-700 font-medium shadow-sm cursor-pointer"
                      >
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                      </select>
                    </div>
                  </div>

                  <div className="sticky bottom-0 bg-white border-t border-gray-200 mt-8 -mx-4 sm:-mx-6 md:-mx-8 px-4 sm:px-6 md:px-8 py-4 flex justify-end gap-3">
                    <button
                      type="button"
                      onClick={() => setShowPromotionModal(false)}
                      className="px-8 py-3 border-2 border-gray-300 rounded-xl text-gray-700 font-semibold hover:bg-gray-50 transition-all duration-200 shadow-sm hover:shadow-md"
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      className="px-8 py-3 bg-gradient-to-r from-purple-500 to-purple-600 text-white rounded-xl font-semibold hover:from-purple-600 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl"
                    >
                      {editingPromotion ? 'Update' : 'Create'}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PromotionsManagementPage;

