import React, { useEffect, useState } from 'react';
import { Plus, Search, Edit, Trash2, X, Tag } from 'lucide-react';
import { ratePlanService, RatePlan, RatePlanType, RatePlanStatus, CreateRatePlanData } from '../../services/api';
import { roomService, Room } from '../../services/api';
import { toast } from 'react-toastify';
import Loading from '../../components/common/Loading';
import Pagination from '../../components/common/Pagination';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';

const RatePlanManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [ratePlans, setRatePlans] = useState<RatePlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingRatePlan, setEditingRatePlan] = useState<RatePlan | null>(null);
  const [roomTypes, setRoomTypes] = useState<Array<{ id: number; name: string }>>([]);
  const [filters, setFilters] = useState({
    search: '',
    status: '',
    plan_type: '',
    room_type_id: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 10;

  const [formData, setFormData] = useState<CreateRatePlanData>({
    name: '',
    code: '',
    description: '',
    plan_type: 'BAR',
    status: 'active',
    base_price_modifier: 1.0,
    discount_percentage: 0,
    fixed_discount: 0,
    room_type_id: undefined,
    min_nights: undefined,
    max_nights: undefined,
    advance_days_required: undefined,
    valid_from: '',
    valid_to: '',
    is_refundable: true,
    requires_deposit: false,
    deposit_percentage: 0,
    cancellation_hours: undefined,
    corporate_code: '',
    requires_verification: false,
    verification_type: '',
    long_stay_nights: undefined,
    is_package: false,
    package_id: undefined,
    priority: 100,
    extra_data: undefined,
  });

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    fetchRatePlans();
  }, [filters, currentPage]);

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

  const fetchRoomTypes = async () => {
    try {
      const response = await roomService.getRooms({ limit: 100, page: 1 });
      const allUniqueRoomTypes = new Map<number, { id: number; name: string }>();
      response.data.rooms.forEach((room: Room) => {
        if (room.room_type && !allUniqueRoomTypes.has(room.room_type.id)) {
          allUniqueRoomTypes.set(room.room_type.id, {
            id: room.room_type.id,
            name: room.room_type.name,
          });
        }
      });
      if (allUniqueRoomTypes.size > 0) {
        setRoomTypes(Array.from(allUniqueRoomTypes.values()));
      }
    } catch (err) {
      console.error('Failed to fetch room types:', err);
    }
  };

  const fetchRatePlans = async () => {
    try {
      setLoading(true);
      const params: any = {
        page: currentPage,
        limit: itemsPerPage,
      };
      if (filters.search) params.search = filters.search;
      if (filters.status) params.status = filters.status;
      if (filters.plan_type) params.plan_type = filters.plan_type;
      if (filters.room_type_id) params.room_type_id = parseInt(filters.room_type_id);

      const response = await ratePlanService.getRatePlans(params);
      setRatePlans(response.data.rate_plans);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
        setTotalItems(response.data.pagination.total);
      }
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Unable to load rate plans');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const submitData = {
        ...formData,
        room_type_id: formData.room_type_id ? parseInt(formData.room_type_id.toString()) : undefined,
        discount_percentage: formData.discount_percentage || undefined,
        fixed_discount: formData.fixed_discount || undefined,
        deposit_percentage: formData.deposit_percentage || undefined,
        valid_from: formData.valid_from || undefined,
        valid_to: formData.valid_to || undefined,
      };

      if (editingRatePlan) {
        await ratePlanService.updateRatePlan(editingRatePlan.id, submitData);
        toast.success('Rate plan updated successfully');
      } else {
        await ratePlanService.createRatePlan(submitData);
        toast.success('Rate plan created successfully');
      }
      setShowModal(false);
      resetForm();
      fetchRatePlans();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'An error occurred');
    }
  };

  const handleEdit = (ratePlan: RatePlan) => {
    setEditingRatePlan(ratePlan);
    setFormData({
      name: ratePlan.name,
      code: ratePlan.code,
      description: ratePlan.description || '',
      plan_type: ratePlan.plan_type,
      status: ratePlan.status,
      base_price_modifier: ratePlan.base_price_modifier,
      discount_percentage: ratePlan.discount_percentage,
      fixed_discount: ratePlan.fixed_discount,
      room_type_id: ratePlan.room_type_id,
      min_nights: ratePlan.min_nights,
      max_nights: ratePlan.max_nights,
      advance_days_required: ratePlan.advance_days_required,
      valid_from: ratePlan.valid_from?.split('T')[0] || '',
      valid_to: ratePlan.valid_to?.split('T')[0] || '',
      is_refundable: ratePlan.is_refundable,
      requires_deposit: ratePlan.requires_deposit,
      deposit_percentage: ratePlan.deposit_percentage,
      cancellation_hours: ratePlan.cancellation_hours,
      corporate_code: ratePlan.corporate_code || '',
      requires_verification: ratePlan.requires_verification,
      verification_type: ratePlan.verification_type || '',
      long_stay_nights: ratePlan.long_stay_nights,
      is_package: ratePlan.is_package,
      package_id: ratePlan.package_id,
      priority: ratePlan.priority,
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this rate plan?')) return;
    
    try {
      await ratePlanService.deleteRatePlan(id);
      toast.success('Rate plan deleted successfully');
      fetchRatePlans();
    } catch (error: any) {
      toast.error(error.response?.data?.detail || 'Unable to delete rate plan');
    }
  };

  const resetForm = () => {
    setEditingRatePlan(null);
    setFormData({
      name: '',
      code: '',
      description: '',
      plan_type: 'BAR',
      status: 'active',
      base_price_modifier: 1.0,
      discount_percentage: 0,
      fixed_discount: 0,
      room_type_id: undefined,
      min_nights: undefined,
      max_nights: undefined,
      advance_days_required: undefined,
      valid_from: '',
      valid_to: '',
      is_refundable: true,
      requires_deposit: false,
      deposit_percentage: 0,
      cancellation_hours: undefined,
      corporate_code: '',
      requires_verification: false,
      verification_type: '',
      long_stay_nights: undefined,
      is_package: false,
      package_id: undefined,
      priority: 100,
      extra_data: undefined,
    });
  };

  const getStatusBadge = (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'
      },
      scheduled: {
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50',
        text: 'text-blue-800',
        label: 'Scheduled',
        border: 'border-blue-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>
    );
  };

  const getPlanTypeBadge = (type: string) => {
    const types: Record<string, { bg: string; text: string; label: string }> = {
      BAR: { bg: 'bg-blue-100', text: 'text-blue-800', label: 'BAR' },
      non_refundable: { bg: 'bg-red-100', text: 'text-red-800', label: 'Non-Refundable' },
      advance_purchase: { bg: 'bg-purple-100', text: 'text-purple-800', label: 'Advance Purchase' },
      corporate: { bg: 'bg-indigo-100', text: 'text-indigo-800', label: 'Corporate' },
      government: { bg: 'bg-green-100', text: 'text-green-800', label: 'Government' },
      military: { bg: 'bg-amber-100', text: 'text-amber-800', label: 'Military' },
      long_stay: { bg: 'bg-teal-100', text: 'text-teal-800', label: 'Long Stay' },
      package: { bg: 'bg-pink-100', text: 'text-pink-800', label: 'Package' },
    };
    const typeInfo = types[type] || types.BAR;
    return (
      <span className={`px-3 py-1 rounded-full text-xs font-semibold ${typeInfo.bg} ${typeInfo.text}`}>
        {typeInfo.label}
      </span>
    );
  };

  if (loading && ratePlans.length === 0) {
    return <Loading />;
  }

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      <div className="flex justify-between items-center animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
            <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Rate Plan Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage pricing plans and rate structures</p>
        </div>
        <button
          onClick={() => {
            resetForm();
            setShowModal(true);
          }}
          className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl"
        >
          <Plus className="w-5 h-5" />
          Add Rate Plan
        </button>
      </div>

      {/* Filters */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-5">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search by name or code..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.plan_type}
            onChange={(e) => setFilters({ ...filters, plan_type: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Types</option>
            <option value="BAR">BAR</option>
            <option value="non_refundable">Non-Refundable</option>
            <option value="advance_purchase">Advance Purchase</option>
            <option value="corporate">Corporate</option>
            <option value="government">Government</option>
            <option value="military">Military</option>
            <option value="long_stay">Long Stay</option>
            <option value="package">Package</option>
          </select>
          <select
            value={filters.status}
            onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-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>
            <option value="scheduled">Scheduled</option>
            <option value="expired">Expired</option>
          </select>
          <select
            value={filters.room_type_id}
            onChange={(e) => setFilters({ ...filters, room_type_id: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All Room Types</option>
            {roomTypes.map((rt) => (
              <option key={rt.id} value={rt.id}>{rt.name}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Rate Plans Table */}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900">
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Code</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Name</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Type</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Pricing</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Room Type</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Status</th>
                <th className="px-8 py-5 text-right text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Actions</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-100">
              {ratePlans.map((plan) => (
                <tr 
                  key={plan.id} 
                  className="hover:bg-gradient-to-r hover:from-amber-50/30 hover:to-yellow-50/30 transition-all duration-200 group border-b border-slate-100"
                >
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-gradient-to-br from-amber-100 to-amber-200 rounded-lg">
                        <Tag className="w-4 h-4 text-amber-600" />
                      </div>
                      <span className="text-sm font-mono font-bold bg-gradient-to-r from-amber-600 to-amber-700 bg-clip-text text-transparent">{plan.code}</span>
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    <div className="text-sm font-semibold text-slate-900">{plan.name}</div>
                    <div className="text-xs text-slate-500 mt-0.5">{plan.description}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getPlanTypeBadge(plan.plan_type)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm">
                      {plan.discount_percentage ? (
                        <span className="font-bold text-emerald-600">{plan.discount_percentage}% off</span>
                      ) : plan.fixed_discount ? (
                        <span className="font-bold text-emerald-600">{formatCurrency(plan.fixed_discount)} off</span>
                      ) : (
                        <span className="text-slate-600">{plan.base_price_modifier}x base</span>
                      )}
                    </div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-600">{plan.room_type_name || 'All Types'}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getStatusBadge(plan.status)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleEdit(plan)}
                        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={() => handleDelete(plan.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>
          {ratePlans.length === 0 && (
            <div className="text-center py-12">
              <Tag className="w-16 h-16 text-slate-300 mx-auto mb-4" />
              <p className="text-slate-500">No rate plans found</p>
            </div>
          )}
        </div>
        {totalPages > 1 && (
          <div className="px-8 py-5 border-t border-slate-200">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              totalItems={totalItems}
              itemsPerPage={itemsPerPage}
            />
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-gradient-to-r from-amber-500 to-amber-600 px-8 py-6 flex justify-between items-center rounded-t-2xl">
              <h2 className="text-2xl font-bold text-white">
                {editingRatePlan ? 'Edit Rate Plan' : 'Create Rate Plan'}
              </h2>
              <button
                onClick={() => {
                  setShowModal(false);
                  resetForm();
                }}
                className="p-2 rounded-lg text-white hover:bg-white/20 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            <form onSubmit={handleSubmit} className="p-8 space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Name *</label>
                  <input
                    type="text"
                    required
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Code *</label>
                  <input
                    type="text"
                    required
                    disabled={!!editingRatePlan}
                    value={formData.code}
                    onChange={(e) => setFormData({ ...formData, code: e.target.value.toUpperCase() })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all disabled:bg-slate-100"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Description</label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                    rows={3}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Plan Type *</label>
                  <select
                    required
                    value={formData.plan_type}
                    onChange={(e) => setFormData({ ...formData, plan_type: e.target.value as RatePlanType })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  >
                    <option value="BAR">BAR (Best Available Rate)</option>
                    <option value="non_refundable">Non-Refundable</option>
                    <option value="advance_purchase">Advance Purchase</option>
                    <option value="corporate">Corporate</option>
                    <option value="government">Government</option>
                    <option value="military">Military</option>
                    <option value="long_stay">Long Stay</option>
                    <option value="package">Package</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Status *</label>
                  <select
                    required
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value as RatePlanStatus })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  >
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                    <option value="scheduled">Scheduled</option>
                    <option value="expired">Expired</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Room Type</label>
                  <select
                    value={formData.room_type_id || ''}
                    onChange={(e) => setFormData({ ...formData, room_type_id: e.target.value ? parseInt(e.target.value) : undefined })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  >
                    <option value="">All Room Types</option>
                    {roomTypes.map((rt) => (
                      <option key={rt.id} value={rt.id}>{rt.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-semibold text-slate-700 mb-2">Priority</label>
                  <input
                    type="number"
                    value={formData.priority}
                    onChange={(e) => setFormData({ ...formData, priority: parseInt(e.target.value) || 100 })}
                    className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                  />
                  <p className="text-xs text-slate-500 mt-1">Lower number = higher priority</p>
                </div>
              </div>

              <div className="border-t border-slate-200 pt-6">
                <h3 className="text-lg font-semibold text-slate-900 mb-4">Pricing</h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Base Price Modifier</label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.base_price_modifier}
                      onChange={(e) => setFormData({ ...formData, base_price_modifier: parseFloat(e.target.value) || 1.0 })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                    <p className="text-xs text-slate-500 mt-1">1.0 = 100%, 0.9 = 90%</p>
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Discount %</label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      max="100"
                      value={formData.discount_percentage || ''}
                      onChange={(e) => setFormData({ ...formData, discount_percentage: e.target.value ? parseFloat(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Fixed Discount</label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.fixed_discount || ''}
                      onChange={(e) => setFormData({ ...formData, fixed_discount: e.target.value ? parseFloat(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                </div>
              </div>

              <div className="border-t border-slate-200 pt-6">
                <h3 className="text-lg font-semibold text-slate-900 mb-4">Restrictions</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Min Nights</label>
                    <input
                      type="number"
                      min="1"
                      value={formData.min_nights || ''}
                      onChange={(e) => setFormData({ ...formData, min_nights: e.target.value ? parseInt(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Max Nights</label>
                    <input
                      type="number"
                      min="1"
                      value={formData.max_nights || ''}
                      onChange={(e) => setFormData({ ...formData, max_nights: e.target.value ? parseInt(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Advance Days Required</label>
                    <input
                      type="number"
                      min="0"
                      value={formData.advance_days_required || ''}
                      onChange={(e) => setFormData({ ...formData, advance_days_required: e.target.value ? parseInt(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Cancellation Hours</label>
                    <input
                      type="number"
                      min="0"
                      value={formData.cancellation_hours || ''}
                      onChange={(e) => setFormData({ ...formData, cancellation_hours: e.target.value ? parseInt(e.target.value) : undefined })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Valid From</label>
                    <input
                      type="date"
                      value={formData.valid_from}
                      onChange={(e) => setFormData({ ...formData, valid_from: e.target.value })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Valid To</label>
                    <input
                      type="date"
                      value={formData.valid_to}
                      onChange={(e) => setFormData({ ...formData, valid_to: e.target.value })}
                      className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                    />
                  </div>
                </div>
              </div>

              <div className="border-t border-slate-200 pt-6">
                <h3 className="text-lg font-semibold text-slate-900 mb-4">Options</h3>
                <div className="space-y-4">
                  <label className="flex items-center gap-3">
                    <input
                      type="checkbox"
                      checked={formData.is_refundable}
                      onChange={(e) => setFormData({ ...formData, is_refundable: e.target.checked })}
                      className="w-5 h-5 text-amber-600 border-slate-300 rounded focus:ring-amber-500"
                    />
                    <span className="text-sm font-medium text-slate-700">Refundable</span>
                  </label>
                  <label className="flex items-center gap-3">
                    <input
                      type="checkbox"
                      checked={formData.requires_deposit}
                      onChange={(e) => setFormData({ ...formData, requires_deposit: e.target.checked })}
                      className="w-5 h-5 text-amber-600 border-slate-300 rounded focus:ring-amber-500"
                    />
                    <span className="text-sm font-medium text-slate-700">Requires Deposit</span>
                  </label>
                  {formData.requires_deposit && (
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-2">Deposit Percentage</label>
                      <input
                        type="number"
                        step="0.01"
                        min="0"
                        max="100"
                        value={formData.deposit_percentage || ''}
                        onChange={(e) => setFormData({ ...formData, deposit_percentage: e.target.value ? parseFloat(e.target.value) : undefined })}
                        className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                      />
                    </div>
                  )}
                  {(formData.plan_type === 'corporate' || formData.plan_type === 'government' || formData.plan_type === 'military') && (
                    <>
                      <div>
                        <label className="block text-sm font-semibold text-slate-700 mb-2">Corporate/Code</label>
                        <input
                          type="text"
                          value={formData.corporate_code || ''}
                          onChange={(e) => setFormData({ ...formData, corporate_code: e.target.value })}
                          className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                        />
                      </div>
                      <label className="flex items-center gap-3">
                        <input
                          type="checkbox"
                          checked={formData.requires_verification}
                          onChange={(e) => setFormData({ ...formData, requires_verification: e.target.checked })}
                          className="w-5 h-5 text-amber-600 border-slate-300 rounded focus:ring-amber-500"
                        />
                        <span className="text-sm font-medium text-slate-700">Requires Verification</span>
                      </label>
                      {formData.requires_verification && (
                        <div>
                          <label className="block text-sm font-semibold text-slate-700 mb-2">Verification Type</label>
                          <select
                            value={formData.verification_type || ''}
                            onChange={(e) => setFormData({ ...formData, verification_type: e.target.value || undefined })}
                            className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                          >
                            <option value="">Select Type</option>
                            <option value="corporate_id">Corporate ID</option>
                            <option value="government_id">Government ID</option>
                            <option value="military_id">Military ID</option>
                          </select>
                        </div>
                      )}
                    </>
                  )}
                  {formData.plan_type === 'long_stay' && (
                    <div>
                      <label className="block text-sm font-semibold text-slate-700 mb-2">Long Stay Nights</label>
                      <input
                        type="number"
                        min="1"
                        value={formData.long_stay_nights || ''}
                        onChange={(e) => setFormData({ ...formData, long_stay_nights: e.target.value ? parseInt(e.target.value) : undefined })}
                        className="w-full px-4 py-3 border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all"
                      />
                    </div>
                  )}
                </div>
              </div>

              <div className="flex justify-end gap-4 pt-6 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="px-6 py-3 border-2 border-slate-300 text-slate-700 rounded-xl font-semibold hover:bg-slate-50 transition-all"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all shadow-lg hover:shadow-xl"
                >
                  {editingRatePlan ? 'Update' : 'Create'} Rate Plan
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default RatePlanManagementPage;

