import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useHostelStore, Hostel, Room } from '../../store/hostel';
import { Modal, ModalBody } from '../../components/ui/Modal';
import { 
  Home, Bed, Users, Search, Plus, Filter, 
  ChevronRight, CheckCircle2, XCircle, Trash2, 
  Edit2, Info, MapPin, Hash, X, Sparkles, 
  DoorOpen, LogOut, ArrowRightLeft, ClipboardCheck, History
} from 'lucide-react';
import AttendanceTakeView from '../../components/AttendanceTakeView';
import AttendanceHistoryView from '../../components/AttendanceHistoryView';
import api from '../../store/api';

export default function HostelPortal() {
  const { 
    hostels, rooms, assignments, roomTypes, loading,
    fetchHostels, fetchRooms, fetchAssignments, fetchRoomTypes,
    addHostel, addRoom, assignRoom, checkoutStudent
  } = useHostelStore();

  const [activeTab, setActiveTab] = useState('hostels'); // hostels, rooms, allocations, attendance, history
  const [selectedHostel, setSelectedHostel] = useState<Hostel | null>(null);
  const [search, setSearch] = useState('');
  
  const [showHostelModal, setShowHostelModal] = useState(false);
  const [showRoomModal, setShowRoomModal] = useState(false);
  const [showAssignModal, setShowAssignModal] = useState(false);
  const [students, setStudents] = useState<any[]>([]);
  const [staff, setStaff] = useState<any[]>([]);

  // Form states
  const [hostelForm, setHostelForm] = useState({
    name: '',
    code: '',
    type: 'boys',
    address: '',
    warden_id: '',
    phone: '',
    description: ''
  });

  const [roomForm, setRoomForm] = useState({
    room_number: '',
    floor: 1,
    room_type_id: '',
    bed_count: 2,
    description: ''
  });

  const [assignForm, setAssignForm] = useState({
    student_id: '',
    room_id: '',
    bed_number: '',
    start_date: '',
    end_date: '',
    remarks: ''
  });

  const [tempHostelId, setTempHostelId] = useState<string>('');
  const [studentSearchQuery, setStudentSearchQuery] = useState<string>('');
  const [roomSearchQuery, setRoomSearchQuery] = useState<string>('');

  const closeAssignModal = () => {
    setShowAssignModal(false);
    setTempHostelId('');
    setStudentSearchQuery('');
    setRoomSearchQuery('');
    setAssignForm({
      student_id: '',
      room_id: '',
      bed_number: '',
      start_date: '',
      end_date: '',
      remarks: ''
    });
  };

  const handleAddHostel = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await addHostel({
        ...hostelForm,
        warden_id: hostelForm.warden_id ? parseInt(hostelForm.warden_id) : null
      });
      setShowHostelModal(false);
      setHostelForm({
        name: '',
        code: '',
        type: 'boys',
        address: '',
        warden_id: '',
        phone: '',
        description: ''
      });
    } catch (err) {
      console.error('Error adding hostel:', err);
    }
  };

  const handleAddRoom = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedHostel) return;
    try {
      await addRoom({
        ...roomForm,
        hostel_id: selectedHostel.id,
        room_type_id: roomForm.room_type_id ? parseInt(roomForm.room_type_id) : null,
        floor: parseInt(roomForm.floor.toString()),
        bed_count: parseInt(roomForm.bed_count.toString())
      });
      setShowRoomModal(false);
      setRoomForm({
        room_number: '',
        floor: 1,
        room_type_id: '',
        bed_count: 2,
        description: ''
      });
      fetchRooms(selectedHostel.id);
    } catch (err) {
      console.error('Error adding room:', err);
    }
  };

  const handleAssignRoom = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await assignRoom({
        ...assignForm,
        student_id: parseInt(assignForm.student_id),
        room_id: parseInt(assignForm.room_id)
      });
      closeAssignModal();
      if (selectedHostel) {
        fetchRooms(selectedHostel.id);
      }
    } catch (err) {
      console.error('Error assigning room:', err);
    }
  };

  const handleRoomTypeChange = (typeIdStr: string) => {
    const typeId = parseInt(typeIdStr);
    const type = roomTypes.find(rt => rt.id === typeId);
    setRoomForm({
      ...roomForm,
      room_type_id: typeIdStr,
      bed_count: type ? type.bed_count : 2
    });
  };

  useEffect(() => {
    fetchHostels();
    fetchAssignments();
    fetchRoomTypes();
    
    api.get('/users', { params: { role: 'student', limit: 1000 } }).then(res => {
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      setStudents(data.map((s: any) => ({
        id: s.id,
        uid: s.uid,
        full_name: `${s.first_name} ${s.last_name}`,
        gender: s.gender,
        class_name: s.class_name
      })));
    });

    // Load staff for warden list
    api.get('/users', { params: { limit: 1000 } }).then(res => {
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      const staffList = data.filter((u: any) => !['student', 'parent'].includes(u.role));
      setStaff(staffList);
    });

    const interval = setInterval(() => {
        fetchHostels();
        fetchAssignments();
    }, 30000);

    return () => clearInterval(interval);
  }, [fetchHostels, fetchAssignments, fetchRoomTypes]);

  useEffect(() => {
    if (selectedHostel) {
      fetchRooms(selectedHostel.id);
    }
  }, [selectedHostel]);

  const stats = [
    { label: 'Total Hostels', value: hostels.length, icon: Home, color: 'blue' },
    { label: 'Total Capacity', value: hostels.reduce((acc, h) => acc + (h.total_capacity || 0), 0), icon: Bed, color: 'purple' },
    { label: 'Occupied Beds', value: hostels.reduce((acc, h) => acc + (h.occupied_count || 0), 0), icon: Users, color: 'emerald' },
    { label: 'Available Beds', value: hostels.reduce((acc, h) => acc + ((h.total_capacity || 0) - (h.occupied_count || 0)), 0), icon: CheckCircle2, color: 'orange' },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800';
      case 'orange': return 'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-900/20 dark:text-orange-400 dark:border-orange-800';
      case 'purple': return 'bg-purple-50 text-purple-600 border-purple-100 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const filteredStudents = students.filter(s => {
    const matchesSearch = s.full_name.toLowerCase().includes(search.toLowerCase()) ||
      (s.class_name && s.class_name.toLowerCase().includes(search.toLowerCase()));
    if (matchesSearch) return true;
    
    const activeAssignment = assignments.find(a => a.student_id === s.id && a.status === 'active');
    if (activeAssignment) {
      return activeAssignment.hostel_name.toLowerCase().includes(search.toLowerCase()) ||
        activeAssignment.room_number.toLowerCase().includes(search.toLowerCase());
    }
    return false;
  });

  const selectedRoom = rooms.find(r => r.id === parseInt(assignForm.room_id));
  const totalBeds = selectedRoom ? Array.from({ length: selectedRoom.bed_count }, (_, i) => i + 1) : [];
  const activeRoomAssignments = assignments.filter(
    a => (a as any).room_id === parseInt(assignForm.room_id) && a.status === 'active'
  );
  const occupiedBedNumbers = activeRoomAssignments.map(a => parseInt(a.bed_number));

  const currentHostelId = tempHostelId || (selectedHostel ? selectedHostel.id.toString() : '');
  const currentHostel = hostels.find(h => h.id.toString() === currentHostelId);
  const chosenStudent = students.find(s => s.id.toString() === assignForm.student_id);

  const filteredModalHostels = hostels.filter(h => {
    if (chosenStudent) {
      if (chosenStudent.gender === 'male') {
        return h.type === 'boys' || h.type === 'co-ed';
      } else if (chosenStudent.gender === 'female') {
        return h.type === 'girls' || h.type === 'co-ed';
      }
    }
    return true;
  });

  const filteredModalStudents = students.filter(s => {
    const matchesSearch = s.full_name.toLowerCase().includes(studentSearchQuery.toLowerCase()) ||
      (s.class_name && s.class_name.toLowerCase().includes(studentSearchQuery.toLowerCase()));
    if (!matchesSearch) return false;

    if (currentHostel) {
      if (currentHostel.type === 'boys') {
        return s.gender === 'male';
      } else if (currentHostel.type === 'girls') {
        return s.gender === 'female';
      }
    }
    return true;
  });

  const filteredModalRooms = rooms.filter(r =>
    r.room_number.toLowerCase().includes(roomSearchQuery.toLowerCase())
  );

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Hostel Portal</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Accommodation</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Hostel Summary</span>
          </nav>
        </div>
        <div className="flex gap-3">
          {activeTab === 'hostels' && (
            <button onClick={() => setShowHostelModal(true)} className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95">
              <Plus size={18} />
              Register Hostel
            </button>
          )}
          {activeTab === 'rooms' && selectedHostel && (
            <button onClick={() => setShowRoomModal(true)} className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg active:scale-95">
              <Plus size={18} />
              Add Room
            </button>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Tabs Control */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        <div className="flex p-1 bg-muted/50 rounded-2xl overflow-x-auto min-w-0 no-scrollbar">
          {[
            { id: 'hostels', label: 'Hostel Registry', icon: Home },
            { id: 'rooms', label: 'Room Management', icon: DoorOpen },
            { id: 'allocations', label: 'Allocations', icon: ArrowRightLeft },
            { id: 'attendance', label: 'Attendance', icon: ClipboardCheck },
            { id: 'history', label: 'History', icon: History },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`
                px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                ${activeTab === tab.id ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}
              `}
            >
              <tab.icon size={14} />
              {tab.label}
            </button>
          ))}
        </div>

        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text"
            placeholder="Search hostels, rooms or students..."
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
      </div>

      {/* Main Content */}
      <div className="min-h-[400px]">
        {loading ? (
          <div className="py-20 text-center">
            <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Accommodation Records...</p>
          </div>
        ) : activeTab === 'hostels' ? (
          <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            {hostels.map(h => (
              <div key={h.id} onClick={() => { setSelectedHostel(h); setActiveTab('rooms'); }} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl transition-all group cursor-pointer relative overflow-hidden flex flex-col">
                <div className="flex justify-between items-start mb-6">
                  <div className="w-16 h-16 rounded-[1.5rem] bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 flex items-center justify-center border border-blue-100 dark:border-blue-800 shadow-sm group-hover:scale-110 transition-transform">
                    <Home size={32} />
                  </div>
                  <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                    h.type === 'boys' ? 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800' : 
                    h.type === 'girls' ? 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-900/20 dark:text-rose-400 dark:border-rose-800' : 
                    'bg-purple-50 text-purple-600 border-purple-100 dark:bg-purple-900/20 dark:text-purple-400 dark:border-purple-800'
                  }`}>
                    {h.type} Hostel
                  </span>
                </div>
                <div className="space-y-1 mb-6">
                  <h3 className="text-2xl font-black text-text tracking-tight group-hover:text-primary transition-colors">{h.name}</h3>
                  <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-[3px]">{h.code} | {h.warden_name || 'No Warden'}</p>
                </div>
                <div className="grid grid-cols-2 gap-3 pt-6 border-t border-border">
                  <div className="p-3 bg-muted/50 rounded-xl border border-border">
                    <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest mb-1">Room Details</p>
                    <p className="text-sm font-bold text-text">{h.room_count || 0} Registered</p>
                  </div>
                  <div className="p-3 bg-muted/50 rounded-xl border border-border">
                    <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest mb-1">Occupancy</p>
                    <p className="text-sm font-bold text-text">{h.occupied_count || 0} / {h.total_capacity || 0}</p>
                  </div>
                </div>
                <div className="mt-8 pt-6 border-t border-border flex items-center justify-between">
                  <div className="flex items-center gap-2 text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                    <MapPin size={14} className="text-primary" /> {h.address}
                  </div>
                  <ChevronRight size={18} className="text-text-muted opacity-0 group-hover:opacity-100 group-hover:translate-x-2 transition-all" />
                </div>
              </div>
            ))}
          </div>
        ) : activeTab === 'rooms' ? (
          <div className="space-y-6">
            {!selectedHostel ? (
              <div className="bg-card border-2 border-dashed border-border rounded-[3rem] py-24 text-center">
                <Home size={64} className="mx-auto text-text-muted/20 mb-6" />
                <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Select a Hostel</h3>
                <p className="text-text-muted font-medium max-w-sm mx-auto">Please select a hostel from the list to manage individual room inventories and allocations.</p>
                <button onClick={() => setActiveTab('hostels')} className="mt-8 px-8 py-3 bg-primary text-white rounded-2xl font-black text-xs uppercase tracking-widest shadow-lg active:scale-95 transition-all">View Hostels</button>
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between bg-card border border-border p-6 rounded-[2rem] shadow-sm">
                  <div className="flex items-center gap-4">
                    <button onClick={() => setSelectedHostel(null)} className="p-2 hover:bg-muted rounded-xl transition-all"><X size={20} /></button>
                    <div>
                      <h4 className="text-xl font-black text-text uppercase tracking-tight">{selectedHostel.name}</h4>
                      <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">{selectedHostel.room_count} Total Rooms</p>
                    </div>
                  </div>
                  <div className="flex gap-4">
                    <div className="px-6 py-2 bg-muted/50 rounded-xl border border-border text-center">
                        <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Global Occupancy</p>
                        <p className="text-sm font-black text-primary">{((selectedHostel.occupied_count / selectedHostel.total_capacity) * 100).toFixed(1)}%</p>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-4 gap-6">
                  {rooms.map(room => (
                    <div key={room.id} className="bg-card border border-border rounded-[2.5rem] p-6 hover:shadow-lg transition-all group">
                      <div className="flex justify-between items-start mb-4">
                        <div className="w-12 h-12 rounded-2xl bg-muted flex items-center justify-center text-text-muted group-hover:bg-primary/10 group-hover:text-primary transition-all">
                          <DoorOpen size={24} />
                        </div>
                        <span className={`px-2.5 py-1 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border ${
                          room.status === 'available' ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-900/20 dark:text-emerald-400 dark:border-emerald-800' : 
                          room.status === 'occupied' ? 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800' : 
                          'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-900/20 dark:text-rose-400 dark:border-rose-800'
                        }`}>
                          {room.status}
                        </span>
                      </div>
                      <div className="space-y-1 mb-4">
                        <h5 className="text-lg font-black text-text">Room {room.room_number}</h5>
                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Floor {room.floor} | {room.type_name || 'Standard'}</p>
                      </div>
                      <div className="space-y-2 mb-6">
                        <div className="flex justify-between text-[0.65rem] font-black uppercase tracking-widest">
                          <span className="text-text-muted">Bed Availability</span>
                          <span className="text-text">{room.occupied_beds} / {room.bed_count}</span>
                        </div>
                        <div className="h-1.5 bg-muted rounded-full overflow-hidden">
                          <div 
                            className={`h-full transition-all duration-500 ${room.occupied_beds === room.bed_count ? 'bg-blue-500' : 'bg-emerald-500'}`} 
                            style={{ width: `${(room.occupied_beds || 0) / room.bed_count * 100}%` }}
                          />
                        </div>
                      </div>
                      <button 
                        onClick={() => { 
                          setAssignForm({
                            student_id: '',
                            room_id: room.id.toString(),
                            bed_number: '',
                            start_date: new Date().toISOString().split('T')[0],
                            end_date: '',
                            remarks: ''
                          }); 
                          setTempHostelId(selectedHostel ? selectedHostel.id.toString() : '');
                          setStudentSearchQuery('');
                          setRoomSearchQuery('');
                          setShowAssignModal(true); 
                        }} 
                        disabled={room.status === 'occupied'}
                        className="w-full py-3 bg-muted hover:bg-primary hover:text-white disabled:opacity-50 disabled:hover:bg-muted disabled:hover:text-text-muted rounded-xl font-black text-[0.6rem] uppercase tracking-widest transition-all"
                      >
                        {room.status === 'occupied' ? 'Fully Allocated' : 'Allocate Bed'}
                      </button>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        ) : activeTab === 'attendance' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceTakeView initialContext="hostel" showTabs={false} />
          </div>
        ) : activeTab === 'history' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceHistoryView studentOptions={students} tabs={['hostel']} />
          </div>
        ) : (
          <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm">
            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead>
                  <tr className="bg-muted/50 border-b border-border">
                    <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Resident Student</th>
                    <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest">Location Profile</th>
                    <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-center">Bed Assignment</th>
                    <th className="px-8 py-5 text-[0.65rem] font-black text-primary uppercase tracking-widest text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredStudents.map(s => {
                    const activeAssign = assignments.find(a => a.student_id === s.id && a.status === 'active');
                    const initials = s.full_name.split(' ').map((n: string) => n[0]).join('').toUpperCase().substring(0, 2);
                    return (
                      <tr key={s.id} className="hover:bg-muted/30 transition-colors">
                        <td className="px-8 py-5">
                          <div className="flex items-center gap-4">
                            <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center text-primary font-black text-sm uppercase">
                              {initials}
                            </div>
                            <div>
                              <p className="text-sm font-bold text-text">{s.full_name}</p>
                              <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-0.5">
                                {activeAssign 
                                  ? `RESIDENT ID: ${activeAssign.uid.substring(0, 8)} (${s.gender || 'N/A'})` 
                                  : `CLASS: ${s.class_name || 'N/A'} (${s.gender || 'N/A'})`}
                              </p>
                            </div>
                          </div>
                        </td>
                        <td className="px-8 py-5">
                          {activeAssign ? (
                            <>
                              <p className="text-xs font-bold text-text">{activeAssign.hostel_name}</p>
                              <p className="text-[0.6rem] text-text-muted font-black tracking-widest uppercase mt-1">ROOM {activeAssign.room_number}</p>
                            </>
                          ) : (
                            <span className="px-2.5 py-1 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-900/20 dark:text-rose-400 dark:border-rose-800/50">
                              Unallocated
                            </span>
                          )}
                        </td>
                        <td className="px-8 py-5 text-center">
                          {activeAssign ? (
                            <span className="px-3 py-1 bg-muted rounded-lg text-[0.6rem] font-black uppercase tracking-widest border border-border">
                              Bed No. {activeAssign.bed_number}
                            </span>
                          ) : (
                            <span className="text-text-muted/40 font-bold">—</span>
                          )}
                        </td>
                        <td className="px-8 py-5 text-right">
                          {activeAssign ? (
                            <button 
                              onClick={() => checkoutStudent(activeAssign.id)} 
                              className="px-4 py-2 bg-rose-50 text-rose-600 hover:bg-rose-100 rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all"
                            >
                              Checkout
                            </button>
                          ) : (
                            <button 
                              onClick={() => {
                                setAssignForm({
                                  student_id: s.id.toString(),
                                  room_id: '',
                                  bed_number: '',
                                  start_date: new Date().toISOString().split('T')[0],
                                  end_date: '',
                                  remarks: ''
                                });
                                setTempHostelId('');
                                setStudentSearchQuery('');
                                setRoomSearchQuery('');
                                setShowAssignModal(true);
                              }}
                              className="px-4 py-2 bg-primary/10 text-primary hover:bg-primary hover:text-white rounded-lg font-black text-[0.6rem] uppercase tracking-widest transition-all"
                            >
                              Allocate Bed
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* Register Hostel Modal */}
      {showHostelModal && (
        <Modal
          open={true}
          onClose={() => setShowHostelModal(false)}
          title="Register Hostel"
          icon={Home}
          maxWidth="max-w-lg"
          zIndex={1000}
        >
          <ModalBody className="p-8 md:p-10 my-8">
            <form id="hostel-register-form" onSubmit={handleAddHostel} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Hostel Name*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. Mandela Hall"
                    value={hostelForm.name}
                    onChange={e => setHostelForm({ ...hostelForm, name: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Code*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. MH1"
                    value={hostelForm.code}
                    onChange={e => setHostelForm({ ...hostelForm, code: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Type*</label>
                  <select
                    value={hostelForm.type}
                    onChange={e => setHostelForm({ ...hostelForm, type: e.target.value as any })}
                    className="form-input"
                  >
                    <option value="boys">Boys</option>
                    <option value="girls">Girls</option>
                    <option value="co-ed">Co-Ed</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Phone</label>
                  <input
                    type="text"
                    placeholder="Warden Phone"
                    value={hostelForm.phone}
                    onChange={e => setHostelForm({ ...hostelForm, phone: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Warden / Custodian</label>
                <select
                  value={hostelForm.warden_id}
                  onChange={e => setHostelForm({ ...hostelForm, warden_id: e.target.value })}
                  className="form-input"
                >
                  <option value="">Select Warden</option>
                  {staff.map(s => (
                    <option key={s.id} value={s.id}>{s.first_name} {s.last_name} [{s.role}]</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Address*</label>
                <input
                  required
                  type="text"
                  placeholder="e.g. West Campus Block A"
                  value={hostelForm.address}
                  onChange={e => setHostelForm({ ...hostelForm, address: e.target.value })}
                  className="form-input"
                />
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Description</label>
                <textarea
                  rows={3}
                  placeholder="Additional notes about the residence..."
                  value={hostelForm.description}
                  onChange={e => setHostelForm({ ...hostelForm, description: e.target.value })}
                  className="form-input resize-none"
                />
              </div>

              <div className="pt-4 border-t border-border flex justify-end gap-3">
                <button type="button" onClick={() => setShowHostelModal(false)} className="px-6 py-2.5 bg-muted hover:bg-muted-dark rounded-xl font-black text-xs uppercase tracking-widest text-text-secondary">Cancel</button>
                <button type="submit" form="hostel-register-form" className="px-8 py-2.5 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:opacity-90 shadow-md">Register</button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Add Room Modal */}
      {showRoomModal && (
        <Modal
          open={true}
          onClose={() => setShowRoomModal(false)}
          title="Add Room"
          icon={DoorOpen}
          maxWidth="max-w-xl"
          zIndex={1000}
        >
          <ModalBody className="p-6 md:p-8 my-6 max-h-[90vh] overflow-y-auto">
            <form id="hostel-add-room-form" onSubmit={handleAddRoom} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Room Number*</label>
                  <input
                    required
                    type="text"
                    placeholder="e.g. 101"
                    value={roomForm.room_number}
                    onChange={e => setRoomForm({ ...roomForm, room_number: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Floor*</label>
                  <input
                    required
                    type="number"
                    min={0}
                    value={roomForm.floor}
                    onChange={e => setRoomForm({ ...roomForm, floor: parseInt(e.target.value) || 0 })}
                    className="form-input"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Room Type*</label>
                  <select
                    required
                    value={roomForm.room_type_id}
                    onChange={e => handleRoomTypeChange(e.target.value)}
                    className="form-input"
                  >
                    <option value="">Select Type</option>
                    {roomTypes.map(rt => (
                      <option key={rt.id} value={rt.id}>{rt.name} ({rt.bed_count} Beds)</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Beds Limit*</label>
                  <input
                    required
                    type="number"
                    min={1}
                    value={roomForm.bed_count}
                    onChange={e => setRoomForm({ ...roomForm, bed_count: parseInt(e.target.value) || 1 })}
                    className="form-input"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Description</label>
                <textarea
                  rows={3}
                  placeholder="Notes about room layout, features..."
                  value={roomForm.description}
                  onChange={e => setRoomForm({ ...roomForm, description: e.target.value })}
                  className="form-input resize-none"
                />
              </div>

              <div className="pt-4 border-t border-border flex justify-end gap-3">
                <button type="button" onClick={() => setShowRoomModal(false)} className="px-6 py-2.5 bg-muted hover:bg-muted-dark rounded-xl font-black text-xs uppercase tracking-widest text-text-secondary">Cancel</button>
                <button type="submit" form="hostel-add-room-form" className="px-8 py-2.5 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:opacity-90 shadow-md">Add Room</button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* Allocate Bed Modal */}
      {showAssignModal && (
        <Modal
          open={true}
          onClose={closeAssignModal}
          title="Allocate Bed"
          icon={Bed}
          maxWidth="max-w-xl"
          zIndex={1000}
        >
          <ModalBody className="p-6 md:p-8 my-6 max-h-[90vh] overflow-y-auto">
            <form id="hostel-allocate-bed-form" onSubmit={handleAssignRoom} className="space-y-4">
              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Select Resident Student*</label>
                <div className="space-y-2">
                  <input
                    type="text"
                    placeholder="Search student by name or class..."
                    value={studentSearchQuery}
                    onChange={e => setStudentSearchQuery(e.target.value)}
                    className="w-full bg-muted/50 border border-border rounded-xl px-3 py-2 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text"
                  />
                  <select
                    required
                    value={assignForm.student_id}
                    onChange={e => setAssignForm({ ...assignForm, student_id: e.target.value })}
                    className="form-input"
                  >
                    <option value="">-- Choose Student --</option>
                    {filteredModalStudents.map(s => (
                      <option key={s.id} value={s.id}>{s.full_name} ({s.class_name || 'No Class'})</option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Select Hostel*</label>
                <select
                  required
                  value={tempHostelId}
                  onChange={e => {
                    const hId = e.target.value;
                    setTempHostelId(hId);
                    setAssignForm(prev => ({ ...prev, room_id: '', bed_number: '' }));
                    if (hId) {
                      fetchRooms(parseInt(hId));
                    }
                  }}
                  className="form-input"
                >
                  <option value="">-- Choose Hostel --</option>
                  {filteredModalHostels.map(h => (
                    <option key={h.id} value={h.id}>{h.name} ({h.type === 'boys' ? 'Boys' : h.type === 'girls' ? 'Girls' : 'Co-ed'})</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Select Room*</label>
                <div className="space-y-2">
                  <input
                    type="text"
                    placeholder="Search room number..."
                    value={roomSearchQuery}
                    onChange={e => setRoomSearchQuery(e.target.value)}
                    className="w-full bg-muted/50 border border-border rounded-xl px-3 py-2 text-xs font-medium focus:outline-none focus:ring-2 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text"
                    disabled={!tempHostelId}
                  />
                  <select
                    required
                    value={assignForm.room_id}
                    onChange={e => {
                      setAssignForm(prev => ({ ...prev, room_id: e.target.value, bed_number: '' }));
                    }}
                    className="form-input"
                    disabled={!tempHostelId}
                  >
                    {!tempHostelId ? (
                      <option value="">-- Choose Hostel First --</option>
                    ) : (
                      <>
                        <option value="">-- Choose Room --</option>
                        {filteredModalRooms.map(r => (
                          <option key={r.id} value={r.id} disabled={r.status === 'occupied'}>
                            Room {r.room_number} ({r.occupied_beds || 0} / {r.bed_count} Beds)
                          </option>
                        ))}
                      </>
                    )}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Select Bed*</label>
                <select
                  required
                  value={assignForm.bed_number}
                  onChange={e => setAssignForm({ ...assignForm, bed_number: e.target.value })}
                  className="form-input"
                  disabled={!assignForm.room_id}
                >
                  <option value="">-- Choose Bed --</option>
                  {totalBeds.map(bedNum => {
                    const isOccupied = occupiedBedNumbers.includes(bedNum);
                    return (
                      <option key={bedNum} value={bedNum.toString()} disabled={isOccupied}>
                        Bed {bedNum} {isOccupied ? '(Occupied)' : ''}
                      </option>
                    );
                  })}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Start Date*</label>
                  <input
                    required
                    type="date"
                    value={assignForm.start_date}
                    onChange={e => setAssignForm({ ...assignForm, start_date: e.target.value })}
                    className="form-input"
                  />
                </div>
                <div>
                  <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">End Date</label>
                  <input
                    type="date"
                    value={assignForm.end_date}
                    onChange={e => setAssignForm({ ...assignForm, end_date: e.target.value })}
                    className="form-input"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-black uppercase tracking-widest text-text-muted mb-1.5">Remarks</label>
                <textarea
                  rows={2}
                  placeholder="Key assignment details, keys issued, rules accepted..."
                  value={assignForm.remarks}
                  onChange={e => setAssignForm({ ...assignForm, remarks: e.target.value })}
                  className="form-input resize-none"
                />
              </div>

              <div className="pt-4 border-t border-border flex justify-end gap-3">
                <button type="button" onClick={closeAssignModal} className="px-6 py-2.5 bg-muted hover:bg-muted-dark rounded-xl font-black text-xs uppercase tracking-widest text-text-secondary">Cancel</button>
                <button type="submit" form="hostel-allocate-bed-form" className="px-8 py-2.5 bg-primary text-white rounded-xl font-black text-xs uppercase tracking-widest hover:opacity-90 shadow-md">Confirm Allocation</button>
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}
