import React, { useEffect, useState } from 'react';
import { Plus, Search, Edit, Trash2, X, Package as PackageIcon } from 'lucide-react';
import packageService, { Package, PackageStatus, PackageItem, PackageItemType, CreatePackageData } from '../../features/loyalty/services/packageService';
import roomService, { Room } from '../../features/rooms/services/roomService';
import serviceService, { Service } from '../../features/hotel_services/services/serviceService';
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 { logger } from '../../shared/utils/logger';

const PackageManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [packages, setPackages] = useState<Package[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingPackage, setEditingPackage] = useState<Package | null>(null);
  const [roomTypes, setRoomTypes] = useState<Array<{ id: number; name: string }>>([]);
  const [, setServices] = useState<Service[]>([]);
  const [filters, setFilters] = useState({
    search: '',
    status: '',
    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<CreatePackageData>({
    name: '',
    code: '',
    description: '',
    status: 'active',
    base_price: undefined,
    price_modifier: 1.0,
    discount_percentage: undefined,
    room_type_id: undefined,
    min_nights: undefined,
    max_nights: undefined,
    valid_from: '',
    valid_to: '',
    image_url: '',
    highlights: [],
    terms_conditions: '',
    extra_data: undefined,
    items: [],
  });

  const [newItem, setNewItem] = useState<Partial<PackageItem>>({
    item_type: 'service',
    item_name: '',
    item_description: '',
    quantity: 1,
    unit: 'per_stay',
    price: undefined,
    included: true,
    display_order: 0,
  });

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

  useEffect(() => {
    fetchPackages();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

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

  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) {
        logger.error('Failed to fetch room types', err);
      }
  };

  const fetchServices = async () => {
    try {
      const response = await serviceService.getServices();
      if (response.data && response.data.services) {
        setServices(response.data.services);
      }
      } catch (err) {
        logger.error('Failed to fetch services', err);
      }
  };

  const fetchPackages = async () => {
    try {
      setLoading(true);
      const params: Record<string, unknown> = {
        page: currentPage,
        limit: itemsPerPage,
      };
      if (filters.search) params.search = filters.search;
      if (filters.status) params.status = filters.status;
      if (filters.room_type_id) params.room_type_id = parseInt(filters.room_type_id);

      const response = await packageService.getPackages(params);
      setPackages(response.data.packages);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
        setTotalItems(response.data.pagination.total);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load packages');
    } 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,
        base_price: formData.base_price || undefined,
        discount_percentage: formData.discount_percentage || undefined,
        valid_from: formData.valid_from || undefined,
        valid_to: formData.valid_to || undefined,
      };

      if (editingPackage) {
        await packageService.updatePackage(editingPackage.id, submitData);
        toast.success('Package updated successfully');
      } else {
        await packageService.createPackage(submitData);
        toast.success('Package created successfully');
      }
      setShowModal(false);
      resetForm();
      fetchPackages();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'An error occurred');
    }
  };

  const handleEdit = (pkg: Package) => {
    setEditingPackage(pkg);
    setFormData({
      name: pkg.name,
      code: pkg.code,
      description: pkg.description || '',
      status: pkg.status,
      base_price: pkg.base_price,
      price_modifier: pkg.price_modifier,
      discount_percentage: pkg.discount_percentage,
      room_type_id: pkg.room_type_id,
      min_nights: pkg.min_nights,
      max_nights: pkg.max_nights,
      valid_from: pkg.valid_from?.split('T')[0] || '',
      valid_to: pkg.valid_to?.split('T')[0] || '',
      image_url: pkg.image_url || '',
      highlights: pkg.highlights || [],
      terms_conditions: pkg.terms_conditions || '',
      items: pkg.items || [],
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this package?')) return;
    
    try {
      await packageService.deletePackage(id);
      toast.success('Package deleted successfully');
      fetchPackages();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to delete package');
    }
  };

  const resetForm = () => {
    setEditingPackage(null);
    setFormData({
      name: '',
      code: '',
      description: '',
      status: 'active',
      base_price: undefined,
      price_modifier: 1.0,
      discount_percentage: undefined,
      room_type_id: undefined,
      min_nights: undefined,
      max_nights: undefined,
      valid_from: '',
      valid_to: '',
      image_url: '',
      highlights: [],
      terms_conditions: '',
      extra_data: undefined,
      items: [],
    });
    setNewItem({
      item_type: 'service',
      item_name: '',
      item_description: '',
      quantity: 1,
      unit: 'per_stay',
      price: undefined,
      included: true,
      display_order: 0,
    });
  };

  const addItem = () => {
    if (!newItem.item_name) {
      toast.error('Please enter item name');
      return;
    }
    setFormData({
      ...formData,
      items: [
        ...(formData.items || []),
        {
          ...newItem,
          display_order: formData.items?.length || 0,
        } as PackageItem,
      ],
    });
    setNewItem({
      item_type: 'service',
      item_name: '',
      item_description: '',
      quantity: 1,
      unit: 'per_stay',
      price: undefined,
      included: true,
      display_order: 0,
    });
  };

  const removeItem = (index: number) => {
    const newItems = [...(formData.items || [])];
    newItems.splice(index, 1);
    setFormData({ ...formData, items: newItems });
  };

  const addHighlight = () => {
    const highlight = prompt('Enter highlight:');
    if (highlight) {
      setFormData({
        ...formData,
        highlights: [...(formData.highlights || []), highlight],
      });
    }
  };

  const removeHighlight = (index: number) => {
    const newHighlights = [...(formData.highlights || [])];
    newHighlights.splice(index, 1);
    setFormData({ ...formData, highlights: newHighlights });
  };

  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>
    );
  };

  if (loading && packages.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">
              Package Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage package deals and bundles</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 Package
        </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-3 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.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>

      {/* Packages 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">Items</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">
              {packages.map((pkg) => (
                <tr 
                  key={pkg.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">
                        <PackageIcon 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">{pkg.code}</span>
                    </div>
                  </td>
                  <td className="px-8 py-5">
                    <div className="text-sm font-semibold text-slate-900">{pkg.name}</div>
                    <div className="text-xs text-slate-500 mt-0.5">{pkg.description}</div>
                  </td>
                  <td className="px-8 py-5">
                    <div className="text-sm text-slate-600">
                      {pkg.items?.length || 0} item(s)
                    </div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm">
                      {pkg.base_price ? (
                        <span className="font-bold text-emerald-600">{formatCurrency(pkg.base_price)}</span>
                      ) : pkg.discount_percentage ? (
                        <span className="font-bold text-emerald-600">{pkg.discount_percentage}% off</span>
                      ) : (
                        <span className="text-slate-600">Custom pricing</span>
                      )}
                    </div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-600">{pkg.room_type_name || 'All Types'}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getStatusBadge(pkg.status)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleEdit(pkg)}
                        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(pkg.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>
          {packages.length === 0 && (
            <div className="text-center py-12">
              <PackageIcon className="w-16 h-16 text-slate-300 mx-auto mb-4" />
              <p className="text-slate-500">No packages 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/70 backdrop-blur-md z-50 flex items-center justify-center p-3 sm:p-4 animate-fade-in">
          <div className="bg-white rounded-2xl sm:rounded-3xl shadow-2xl max-w-5xl w-full max-h-[95vh] sm:max-h-[90vh] overflow-hidden border border-slate-200/50 animate-scale-in">
            <div className="sticky top-0 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 z-10">
              <div className="flex justify-between items-center">
                <div>
                  <h2 className="text-lg sm:text-xl md:text-2xl font-bold text-amber-100">
                    {editingPackage ? 'Edit Package' : 'Create Package'}
                  </h2>
                  <p className="text-amber-200/80 text-xs sm:text-sm font-light mt-1">
                    {editingPackage ? 'Modify package details' : 'Create a new package'}
                  </p>
                </div>
                <button
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="w-9 h-9 sm:w-10 sm:h-10 flex items-center justify-center rounded-xl text-amber-100 hover:text-white hover:bg-slate-700/50 transition-all duration-200 border border-slate-600 hover:border-amber-400"
                >
                  <X className="w-5 h-5 sm:w-6 sm:h-6" />
                </button>
              </div>
            </div>

            <div className="overflow-y-auto max-h-[calc(95vh-120px)] sm:max-h-[calc(90vh-120px)]">
              <form onSubmit={handleSubmit} className="p-4 sm:p-6 md:p-8 space-y-5 sm: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={!!editingPackage}
                    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">Status *</label>
                  <select
                    required
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value as PackageStatus })}
                    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>

              <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</label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.base_price || ''}
                      onChange={(e) => setFormData({ ...formData, base_price: 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"
                    />
                    <p className="text-xs text-slate-500 mt-1">Fixed price per night</p>
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-slate-700 mb-2">Price Modifier</label>
                    <input
                      type="number"
                      step="0.01"
                      min="0"
                      value={formData.price_modifier}
                      onChange={(e) => setFormData({ ...formData, 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"
                    />
                  </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>
              </div>

              <div className="border-t border-slate-200 pt-6">
                <h3 className="text-lg font-semibold text-slate-900 mb-4">Package Items</h3>
                <div className="space-y-4">
                  {formData.items?.map((item, index) => (
                    <div key={index} className="flex items-center gap-4 p-4 bg-slate-50 rounded-xl">
                      <div className="flex-1">
                        <div className="font-semibold text-slate-900">{item.item_name}</div>
                        <div className="text-sm text-slate-600">{item.item_type} - Qty: {item.quantity} {item.unit}</div>
                        {item.price && <div className="text-sm text-emerald-600">{formatCurrency(item.price)}</div>}
                      </div>
                      <button
                        type="button"
                        onClick={() => removeItem(index)}
                        className="p-2 text-rose-600 hover:bg-rose-50 rounded-lg"
                      >
                        <Trash2 className="w-5 h-5" />
                      </button>
                    </div>
                  ))}
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-4 p-4 bg-amber-50 rounded-xl">
                    <div>
                      <label className="block text-xs font-semibold text-slate-700 mb-1">Type</label>
                      <select
                        value={newItem.item_type}
                        onChange={(e) => setNewItem({ ...newItem, item_type: e.target.value as PackageItemType })}
                        className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                      >
                        <option value="service">Service</option>
                        <option value="breakfast">Breakfast</option>
                        <option value="activity">Activity</option>
                        <option value="amenity">Amenity</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-slate-700 mb-1">Name *</label>
                      <input
                        type="text"
                        value={newItem.item_name}
                        onChange={(e) => setNewItem({ ...newItem, item_name: e.target.value })}
                        className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                        placeholder="Item name"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-slate-700 mb-1">Quantity</label>
                      <input
                        type="number"
                        min="1"
                        value={newItem.quantity}
                        onChange={(e) => setNewItem({ ...newItem, quantity: parseInt(e.target.value) || 1 })}
                        className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm"
                      />
                    </div>
                    <div className="flex items-end">
                      <button
                        type="button"
                        onClick={addItem}
                        className="w-full px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors text-sm font-semibold"
                      >
                        Add Item
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <div className="border-t border-slate-200 pt-6">
                <h3 className="text-lg font-semibold text-slate-900 mb-4">Highlights</h3>
                <div className="space-y-2">
                  {formData.highlights?.map((highlight, index) => (
                    <div key={index} className="flex items-center gap-2 p-2 bg-slate-50 rounded-lg">
                      <span className="flex-1 text-sm text-slate-700">{highlight}</span>
                      <button
                        type="button"
                        onClick={() => removeHighlight(index)}
                        className="p-1 text-rose-600 hover:bg-rose-50 rounded"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  ))}
                  <button
                    type="button"
                    onClick={addHighlight}
                    className="px-4 py-2 border-2 border-dashed border-slate-300 text-slate-600 rounded-lg hover:border-amber-400 hover:text-amber-600 transition-colors text-sm font-semibold"
                  >
                    + Add Highlight
                  </button>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row justify-end gap-3 pt-6 border-t border-slate-200">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="w-full sm:w-auto px-6 py-3 border-2 border-slate-300 text-slate-700 rounded-xl font-semibold hover:bg-slate-50 transition-all duration-200 shadow-sm hover:shadow-md"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="w-full sm:w-auto 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"
                >
                  {editingPackage ? 'Update' : 'Create'} Package
                </button>
              </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default PackageManagementPage;

