// app/admin/communities/page.tsx

'use client';

import { useState } from 'react';
import {
  MapPin,
  Plus,
  Edit,
  Trash2,
  CheckCircle,
  XCircle,
  Search,
  Filter,
  X,
  Save,
  Eye,
  ChevronLeft,
  ChevronRight,
  Home,
  Phone,
  Star,
  Users,
  Calendar,
  DollarSign,
  Image as ImageIcon,
  Globe,
  Clock,
} from 'lucide-react';

// Types
interface CommunityFeature {
  id: string;
  name: string;
}

interface Community {
  id: string;
  name: string;
  state: string;
  city: string;
  address: string;
  phone: string;
  rating: number;
  reviews: number;
  image: string;
  availability: string;
  price: string;
  features: CommunityFeature[];
  isActive: boolean;
  displayOrder: number;
  createdAt: string;
  bedsAvailable: number;
  squareFeet: string;
  yearBuilt: string;
  amenities: string[];
}

// Mock data
const mockCommunities: Community[] = [
  {
    id: '1',
    name: 'Orlando Senior Village',
    state: 'florida',
    city: 'Orlando',
    address: '123 Lake Ave, Orlando, FL 32801',
    phone: '(407) 555-0123',
    rating: 4.9,
    reviews: 128,
    image: 'https://images.pexels.com/photos/1643383/pexels-photo-1643383.jpeg?auto=compress&cs=tinysrgb&w=800',
    availability: '2 rooms available',
    price: '3500',
    features: [
      { id: 'f1', name: 'Pool' },
      { id: 'f2', name: 'Garden' },
      { id: 'f3', name: 'Restaurant' },
      { id: 'f4', name: 'Fitness' },
    ],
    isActive: true,
    displayOrder: 1,
    createdAt: '2025-01-01',
    bedsAvailable: 12,
    squareFeet: '25000',
    yearBuilt: '2018',
    amenities: ['24/7 Nursing', 'Restaurant-Style Dining', 'Transportation', 'WiFi'],
  },
  {
    id: '2',
    name: 'Tampa Bay Gardens',
    state: 'florida',
    city: 'Tampa',
    address: '456 Beach Blvd, Tampa, FL 33602',
    phone: '(813) 555-0456',
    rating: 4.8,
    reviews: 96,
    image: 'https://images.pexels.com/photos/271624/pexels-photo-271624.jpeg?auto=compress&cs=tinysrgb&w=800',
    availability: '1 room available',
    price: '3200',
    features: [
      { id: 'f1', name: 'Garden' },
      { id: 'f2', name: 'Restaurant' },
      { id: 'f3', name: 'Walking Paths' },
      { id: 'f4', name: 'Spa' },
    ],
    isActive: true,
    displayOrder: 2,
    createdAt: '2025-01-01',
    bedsAvailable: 8,
    squareFeet: '22000',
    yearBuilt: '2020',
    amenities: ['Spa', 'Fitness Center', 'Library', 'Garden'],
  },
  {
    id: '3',
    name: 'Austin Heights',
    state: 'texas',
    city: 'Austin',
    address: '789 Hill Country Rd, Austin, TX 73301',
    phone: '(512) 555-0789',
    rating: 4.9,
    reviews: 112,
    image: 'https://images.pexels.com/photos/3771097/pexels-photo-3771097.jpeg?auto=compress&cs=tinysrgb&w=800',
    availability: '3 rooms available',
    price: '3400',
    features: [
      { id: 'f1', name: 'Pool' },
      { id: 'f2', name: 'Restaurant' },
      { id: 'f3', name: 'Fitness' },
      { id: 'f4', name: 'Spa' },
      { id: 'f5', name: 'Garden' },
    ],
    isActive: true,
    displayOrder: 3,
    createdAt: '2025-01-01',
    bedsAvailable: 15,
    squareFeet: '28000',
    yearBuilt: '2019',
    amenities: ['Pool', 'Spa', 'Restaurant', 'Fitness Center', 'Walking Trails'],
  },
  {
    id: '4',
    name: 'Dallas Heritage',
    state: 'texas',
    city: 'Dallas',
    address: '321 Park Ave, Dallas, TX 75201',
    phone: '(214) 555-0321',
    rating: 4.7,
    reviews: 84,
    image: 'https://images.pexels.com/photos/261579/pexels-photo-261579.jpeg?auto=compress&cs=tinysrgb&w=800',
    availability: '2 rooms available',
    price: '3100',
    features: [
      { id: 'f1', name: 'Garden' },
      { id: 'f2', name: 'Restaurant' },
      { id: 'f3', name: 'Walking Paths' },
      { id: 'f4', name: 'Library' },
    ],
    isActive: true,
    displayOrder: 4,
    createdAt: '2025-01-01',
    bedsAvailable: 10,
    squareFeet: '24000',
    yearBuilt: '2017',
    amenities: ['Library', 'Restaurant', 'Gardens', 'Activity Center'],
  },
  {
    id: '5',
    name: 'Phoenix Desert Gardens',
    state: 'arizona',
    city: 'Phoenix',
    address: '555 Sun Valley Rd, Phoenix, AZ 85001',
    phone: '(602) 555-0555',
    rating: 4.8,
    reviews: 76,
    image: 'https://images.pexels.com/photos/1643383/pexels-photo-1643383.jpeg?auto=compress&cs=tinysrgb&w=800',
    availability: '1 room available',
    price: '3300',
    features: [
      { id: 'f1', name: 'Pool' },
      { id: 'f2', name: 'Garden' },
      { id: 'f3', name: 'Restaurant' },
      { id: 'f4', name: 'Walking Paths' },
      { id: 'f5', name: 'Spa' },
    ],
    isActive: true,
    displayOrder: 5,
    createdAt: '2025-01-01',
    bedsAvailable: 6,
    squareFeet: '26000',
    yearBuilt: '2021',
    amenities: ['Pool', 'Spa', 'Restaurant', 'Fitness', 'Walking Paths'],
  },
];

const states = [
  { id: 'florida', name: 'Florida', icon: '🌴' },
  { id: 'texas', name: 'Texas', icon: '🤠' },
  { id: 'arizona', name: 'Arizona', icon: '🌵' },
];

const stateColors: Record<string, string> = {
  florida: 'bg-emerald-100 text-emerald-700',
  texas: 'bg-blue-100 text-blue-700',
  arizona: 'bg-amber-100 text-amber-700',
};

const availableFeatures = [
  'Pool', 'Garden', 'Restaurant', 'Fitness', 'Spa', 'Walking Paths', 
  'Library', 'Movie Theater', 'Chapel', 'Salon', 'Courtyard', 
  'Game Room', 'Art Studio', 'Computer Lab', 'Cafe'
];

export default function CommunitiesManagementPage() {
  const [communities, setCommunities] = useState<Community[]>(mockCommunities);
  const [searchTerm, setSearchTerm] = useState('');
  const [stateFilter, setStateFilter] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedCommunity, setSelectedCommunity] = useState<Community | null>(null);
  const [editingCommunity, setEditingCommunity] = useState<Partial<Community>>({});
  const [featureInput, setFeatureInput] = useState('');
  const [imagePreview, setImagePreview] = useState('');

  const itemsPerPage = 10;

  const filteredCommunities = communities.filter((community) => {
    const matchesSearch = community.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      community.city.toLowerCase().includes(searchTerm.toLowerCase()) ||
      community.address.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesState = stateFilter === 'all' || community.state === stateFilter;
    return matchesSearch && matchesState;
  });

  const totalPages = Math.ceil(filteredCommunities.length / itemsPerPage);
  const paginatedCommunities = filteredCommunities.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // Statistics
  const stats = {
    total: communities.length,
    active: communities.filter(c => c.isActive).length,
    totalRooms: communities.reduce((sum, c) => sum + c.bedsAvailable, 0),
    avgRating: (communities.reduce((sum, c) => sum + c.rating, 0) / communities.length).toFixed(1),
  };

  const handleAddCommunity = () => {
    setEditingCommunity({
      name: '',
      state: 'florida',
      city: '',
      address: '',
      phone: '',
      rating: 4.5,
      reviews: 0,
      image: '',
      availability: '',
      price: '',
      features: [],
      isActive: true,
      displayOrder: communities.length + 1,
      bedsAvailable: 0,
      squareFeet: '',
      yearBuilt: '',
      amenities: [],
    });
    setFeatureInput('');
    setImagePreview('');
    setShowAddModal(true);
  };

  const handleEditCommunity = (community: Community) => {
    setEditingCommunity(community);
    setImagePreview(community.image);
    setShowEditModal(true);
  };

  const handleDeleteCommunity = (community: Community) => {
    setSelectedCommunity(community);
    setShowDeleteModal(true);
  };

  const handleToggleActive = (communityId: string) => {
    setCommunities(communities.map(c =>
      c.id === communityId ? { ...c, isActive: !c.isActive } : c
    ));
  };

  const handleAddFeature = () => {
    if (featureInput.trim() && !editingCommunity.features?.some(f => f.name === featureInput.trim())) {
      setEditingCommunity({
        ...editingCommunity,
        features: [
          ...(editingCommunity.features || []),
          { id: Date.now().toString(), name: featureInput.trim() }
        ]
      });
      setFeatureInput('');
    }
  };

  const handleRemoveFeature = (featureId: string) => {
    setEditingCommunity({
      ...editingCommunity,
      features: editingCommunity.features?.filter(f => f.id !== featureId) || []
    });
  };

  const handleAddAmenity = (amenity: string) => {
    if (!editingCommunity.amenities?.includes(amenity)) {
      setEditingCommunity({
        ...editingCommunity,
        amenities: [...(editingCommunity.amenities || []), amenity]
      });
    }
  };

  const handleRemoveAmenity = (amenity: string) => {
    setEditingCommunity({
      ...editingCommunity,
      amenities: editingCommunity.amenities?.filter(a => a !== amenity) || []
    });
  };

  const handleSaveCommunity = () => {
    if (showAddModal) {
      const newCommunity: Community = {
        id: Date.now().toString(),
        name: editingCommunity.name || '',
        state: editingCommunity.state || 'florida',
        city: editingCommunity.city || '',
        address: editingCommunity.address || '',
        phone: editingCommunity.phone || '',
        rating: editingCommunity.rating || 0,
        reviews: editingCommunity.reviews || 0,
        image: editingCommunity.image || 'https://images.pexels.com/photos/1643383/pexels-photo-1643383.jpeg?auto=compress&cs=tinysrgb&w=800',
        availability: editingCommunity.availability || '',
        price: editingCommunity.price || '',
        features: editingCommunity.features || [],
        isActive: editingCommunity.isActive || false,
        displayOrder: editingCommunity.displayOrder || communities.length + 1,
        createdAt: new Date().toISOString().split('T')[0],
        bedsAvailable: editingCommunity.bedsAvailable || 0,
        squareFeet: editingCommunity.squareFeet || '',
        yearBuilt: editingCommunity.yearBuilt || '',
        amenities: editingCommunity.amenities || [],
      };
      setCommunities([...communities, newCommunity]);
    } else if (showEditModal && selectedCommunity) {
      setCommunities(communities.map(c =>
        c.id === selectedCommunity.id
          ? { ...c, ...editingCommunity }
          : c
      ));
    }
    setShowAddModal(false);
    setShowEditModal(false);
    setSelectedCommunity(null);
  };

  const confirmDelete = () => {
    if (selectedCommunity) {
      setCommunities(communities.filter(c => c.id !== selectedCommunity.id));
      setShowDeleteModal(false);
      setSelectedCommunity(null);
    }
  };

  const getStateColor = (state: string) => {
    return stateColors[state] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Communities Management</h1>
          <p className="text-gray-500 mt-1">Manage senior living communities across all locations</p>
        </div>
        <button
          onClick={handleAddCommunity}
          className="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Community
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 bg-emerald-100 rounded-xl flex items-center justify-center">
              <Home className="w-6 h-6 text-emerald-600" />
            </div>
            <span className="text-2xl font-bold text-gray-900">{stats.total}</span>
          </div>
          <p className="text-sm text-gray-500 mt-2">Total Communities</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
            <span className="text-2xl font-bold text-gray-900">{stats.active}</span>
          </div>
          <p className="text-sm text-gray-500 mt-2">Active Communities</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
              <Users className="w-6 h-6 text-blue-600" />
            </div>
            <span className="text-2xl font-bold text-gray-900">{stats.totalRooms}</span>
          </div>
          <p className="text-sm text-gray-500 mt-2">Available Beds</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
          <div className="flex items-center justify-between">
            <div className="w-12 h-12 bg-amber-100 rounded-xl flex items-center justify-center">
              <Star className="w-6 h-6 text-amber-600" />
            </div>
            <span className="text-2xl font-bold text-gray-900">{stats.avgRating}</span>
          </div>
          <p className="text-sm text-gray-500 mt-2">Avg. Rating</p>
        </div>
      </div>

      {/* Filters Bar */}
      <div className="bg-white rounded-xl p-4 shadow-sm border border-gray-100">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder="Search by name, city or address..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900 placeholder:text-gray-400"
            />
          </div>
          <div className="flex items-center gap-2">
            <Filter className="w-5 h-5 text-gray-400" />
            <select
              value={stateFilter}
              onChange={(e) => setStateFilter(e.target.value)}
              className="px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 outline-none text-gray-900"
            >
              <option value="all">All States</option>
              <option value="florida">Florida</option>
              <option value="texas">Texas</option>
              <option value="arizona">Arizona</option>
            </select>
          </div>
        </div>
      </div>

      {/* Communities Table */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Order</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Community</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Location</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Rating</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Price</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Availability</th>
                <th className="text-left px-6 py-4 text-sm font-semibold text-gray-600">Status</th>
                <th className="text-center px-6 py-4 text-sm font-semibold text-gray-600">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {paginatedCommunities.map((community) => (
                <tr key={community.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4">
                    <span className="text-sm text-gray-600">{community.displayOrder}</span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-12 h-12 rounded-lg overflow-hidden">
                        <img src={community.image} alt={community.name} className="w-full h-full object-cover" />
                      </div>
                      <div>
                        <p className="font-medium text-gray-900">{community.name}</p>
                        <p className="text-xs text-gray-500">ID: {community.id}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="space-y-1">
                      <p className="text-sm text-gray-900">{community.city}</p>
                      <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${getStateColor(community.state)}`}>
                        {states.find(s => s.id === community.state)?.name}
                      </span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-1">
                      <Star className="w-4 h-4 text-amber-500 fill-current" />
                      <span className="text-sm font-semibold text-gray-900">{community.rating}</span>
                      <span className="text-xs text-gray-500">({community.reviews})</span>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-sm font-semibold text-gray-900">${parseInt(community.price).toLocaleString()}</span>
                    <span className="text-xs text-gray-500">/mo</span>
                  </td>
                  <td className="px-6 py-4">
                    <span className="text-sm text-gray-600">{community.availability}</span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      community.isActive 
                        ? 'bg-emerald-100 text-emerald-700' 
                        : 'bg-gray-100 text-gray-700'
                    }`}>
                      {community.isActive ? 'Active' : 'Inactive'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center justify-center gap-2">
                      <button
                        onClick={() => handleToggleActive(community.id)}
                        className={`p-1.5 rounded-lg transition-colors ${
                          community.isActive 
                            ? 'hover:bg-red-50' 
                            : 'hover:bg-emerald-50'
                        }`}
                        title={community.isActive ? 'Deactivate' : 'Activate'}
                      >
                        {community.isActive ? (
                          <XCircle className="w-4 h-4 text-red-500" />
                        ) : (
                          <CheckCircle className="w-4 h-4 text-emerald-500" />
                        )}
                      </button>
                      <button
                        onClick={() => handleEditCommunity(community)}
                        className="p-1.5 rounded-lg hover:bg-gray-100 transition-colors"
                        title="Edit"
                      >
                        <Edit className="w-4 h-4 text-gray-500" />
                      </button>
                      <button
                        onClick={() => handleDeleteCommunity(community)}
                        className="p-1.5 rounded-lg hover:bg-red-50 transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100">
            <p className="text-sm text-gray-500">
              Showing {(currentPage - 1) * itemsPerPage + 1} to {Math.min(currentPage * itemsPerPage, filteredCommunities.length)} of {filteredCommunities.length} results
            </p>
            <div className="flex gap-2">
              <button
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="p-2 rounded-lg border border-gray-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                <button
                  key={page}
                  onClick={() => setCurrentPage(page)}
                  className={`px-3 py-1 rounded-lg ${
                    currentPage === page
                      ? 'bg-emerald-600 text-white'
                      : 'border border-gray-200 hover:bg-gray-50 text-gray-700'
                  }`}
                >
                  {page}
                </button>
              ))}
              <button
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="p-2 rounded-lg border border-gray-200 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Add/Edit Community Modal */}
      {(showAddModal || showEditModal) && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-gray-100 px-6 py-4 flex items-center justify-between">
              <h2 className="text-xl font-bold text-gray-900">
                {showAddModal ? 'Add New Community' : 'Edit Community'}
              </h2>
              <button
                onClick={() => {
                  setShowAddModal(false);
                  setShowEditModal(false);
                }}
                className="p-2 rounded-lg hover:bg-gray-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-6 space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Community Name *
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.name || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, name: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="e.g., Orlando Senior Village"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    State *
                  </label>
                  <select
                    value={editingCommunity.state || 'florida'}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, state: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 outline-none text-gray-900"
                  >
                    {states.map((state) => (
                      <option key={state.id} value={state.id}>{state.name}</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    City *
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.city || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, city: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="e.g., Orlando"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Display Order
                  </label>
                  <input
                    type="number"
                    value={editingCommunity.displayOrder || 0}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, displayOrder: parseInt(e.target.value) })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Address *
                </label>
                <input
                  type="text"
                  value={editingCommunity.address || ''}
                  onChange={(e) => setEditingCommunity({ ...editingCommunity, address: e.target.value })}
                  className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                  placeholder="Full address"
                />
              </div>

              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Phone *
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.phone || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, phone: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="(555) 123-4567"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Price (per month) *
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.price || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, price: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="3500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Availability *
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.availability || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, availability: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="2 rooms available"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Rating
                  </label>
                  <input
                    type="number"
                    step="0.1"
                    value={editingCommunity.rating || 0}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, rating: parseFloat(e.target.value) })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Reviews Count
                  </label>
                  <input
                    type="number"
                    value={editingCommunity.reviews || 0}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, reviews: parseInt(e.target.value) })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Image URL *
                </label>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={editingCommunity.image || ''}
                    onChange={(e) => {
                      setEditingCommunity({ ...editingCommunity, image: e.target.value });
                      setImagePreview(e.target.value);
                    }}
                    className="flex-1 px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="https://..."
                  />
                  {imagePreview && (
                    <div className="w-12 h-12 rounded-lg overflow-hidden border border-gray-200">
                      <img src={imagePreview} alt="Preview" className="w-full h-full object-cover" />
                    </div>
                  )}
                </div>
              </div>

              {/* Features Section */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Features
                </label>
                <div className="flex gap-2 mb-3">
                  <input
                    type="text"
                    value={featureInput}
                    onChange={(e) => setFeatureInput(e.target.value)}
                    onKeyPress={(e) => e.key === 'Enter' && handleAddFeature()}
                    className="flex-1 px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="Add a feature..."
                  />
                  <button
                    onClick={handleAddFeature}
                    className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700"
                  >
                    Add
                  </button>
                </div>
                <div className="flex flex-wrap gap-2">
                  {editingCommunity.features?.map((feature) => (
                    <span
                      key={feature.id}
                      className="inline-flex items-center gap-1 px-3 py-1 bg-gray-100 rounded-full text-sm text-gray-700"
                    >
                      {feature.name}
                      <button
                        onClick={() => handleRemoveFeature(feature.id)}
                        className="ml-1 text-gray-400 hover:text-red-500"
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </span>
                  ))}
                </div>
              </div>

              {/* Additional Details */}
              <div className="grid grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Available Beds
                  </label>
                  <input
                    type="number"
                    value={editingCommunity.bedsAvailable || 0}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, bedsAvailable: parseInt(e.target.value) })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Square Feet
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.squareFeet || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, squareFeet: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="25000"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Year Built
                  </label>
                  <input
                    type="text"
                    value={editingCommunity.yearBuilt || ''}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, yearBuilt: e.target.value })}
                    className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 outline-none text-gray-900"
                    placeholder="2020"
                  />
                </div>
              </div>

              {/* Amenities */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Amenities
                </label>
                <div className="flex flex-wrap gap-2 mb-3">
                  {availableFeatures.map((amenity) => (
                    <button
                      key={amenity}
                      onClick={() => handleAddAmenity(amenity)}
                      className={`px-3 py-1.5 rounded-full text-sm transition-colors ${
                        editingCommunity.amenities?.includes(amenity)
                          ? 'bg-emerald-600 text-white'
                          : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                      }`}
                    >
                      {amenity}
                    </button>
                  ))}
                </div>
                {editingCommunity.amenities && editingCommunity.amenities.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-2">
                    {editingCommunity.amenities.map((amenity) => (
                      <span
                        key={amenity}
                        className="inline-flex items-center gap-1 px-3 py-1 bg-emerald-100 text-emerald-700 rounded-full text-sm"
                      >
                        {amenity}
                        <button
                          onClick={() => handleRemoveAmenity(amenity)}
                          className="ml-1 text-emerald-500 hover:text-red-500"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>

              <div className="flex items-center gap-4">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={editingCommunity.isActive || false}
                    onChange={(e) => setEditingCommunity({ ...editingCommunity, isActive: e.target.checked })}
                    className="w-4 h-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500"
                  />
                  <span className="text-sm text-gray-700">Active</span>
                </label>
              </div>

              <div className="flex gap-3 pt-4 border-t border-gray-100">
                <button
                  onClick={() => {
                    setShowAddModal(false);
                    setShowEditModal(false);
                  }}
                  className="flex-1 px-4 py-2 border border-gray-200 rounded-lg font-medium hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSaveCommunity}
                  className="flex-1 px-4 py-2 bg-emerald-600 text-white rounded-lg font-medium hover:bg-emerald-700 flex items-center justify-center gap-2"
                >
                  <Save className="w-4 h-4" />
                  Save Community
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteModal && selectedCommunity && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl max-w-md w-full p-6">
            <div className="text-center">
              <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <Trash2 className="w-8 h-8 text-red-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">Delete Community</h3>
              <p className="text-gray-500 mb-6">
                Are you sure you want to delete <span className="font-semibold">{selectedCommunity.name}</span>?
                This action cannot be undone.
              </p>
              <div className="flex gap-3">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="flex-1 px-4 py-2 border border-gray-200 rounded-lg font-medium hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={confirmDelete}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700"
                >
                  Delete
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}