import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
  Trophy, Search, Plus, User, Calendar, Edit2, Trash2, X, AlertCircle,
  ClipboardCheck, History, List, Package
} from 'lucide-react';
import api from '../../store/api';
import AttendanceTakeView from '../../components/AttendanceTakeView';
import AttendanceHistoryView from '../../components/AttendanceHistoryView';
import { useInventoryStore } from '../../store/inventory';

interface Club {
  id: number;
  name: string;
  type: 'club' | 'sport';
  description: string;
  teacher_in_charge_id: number;
  teacher_name?: string;
  schedule: string;
  max_members?: number;
  current_members?: number;
  status: 'active' | 'inactive';
}

interface Teacher {
  id: number;
  first_name: string;
  last_name: string;
}

export default function ClubManagement() {
  const [clubs, setClubs] = useState<Club[]>([]);
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [students, setStudents] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState('registry'); // registry, attendance, history, inventory
  
  const [showModal, setShowModal] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit'>('create');
  const [selectedClub, setSelectedClub] = useState<Club | null>(null);
  const [submitting, setSubmitting] = useState(false);

  // Inventory state integration
  const {
    items, locations, issues, loading: inventoryLoading,
    fetchItems, fetchLocations, fetchIssues, issueItem, returnItem
  } = useInventoryStore();

  const [inventorySubTab, setInventorySubTab] = useState<'catalog' | 'borrowed'>('catalog');
  const [searchInventory, setSearchInventory] = useState('');
  
  const [borrowModalOpen, setBorrowModalOpen] = useState(false);
  const [selectedInventoryItem, setSelectedInventoryItem] = useState<any>(null);
  const [borrowSubmitting, setBorrowSubmitting] = useState(false);
  const [borrowForm, setBorrowForm] = useState({
    issued_to_type: 'club' as 'club' | 'sport',
    issued_to_id: '',
    quantity: 1,
    purpose: '',
    return_due_date: '',
    store_id: '',
    notes: ''
  });

  const [returnModalOpen, setReturnModalOpen] = useState(false);
  const [selectedIssueForReturn, setSelectedIssueForReturn] = useState<any>(null);
  const [returnSubmitting, setReturnSubmitting] = useState(false);
  const [returnForm, setReturnForm] = useState({
    quantity: 1,
    condition: 'Good',
    store_id: ''
  });

  useEffect(() => {
    if (activeTab === 'inventory') {
      fetchItems();
      fetchLocations();
      fetchIssues();
    }
  }, [activeTab]);

  const handleOpenBorrow = (item: any) => {
    setSelectedInventoryItem(item);
    setBorrowForm({
      issued_to_type: clubs[0]?.type || 'club',
      issued_to_id: clubs[0]?.id?.toString() || '',
      quantity: 1,
      purpose: '',
      return_due_date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      store_id: locations[0]?.id?.toString() || '',
      notes: ''
    });
    setBorrowModalOpen(true);
  };

  const handleOpenReturn = (issue: any) => {
    setSelectedIssueForReturn(issue);
    setReturnForm({
      quantity: issue.quantity - (issue.returned_quantity || 0),
      condition: 'Good',
      store_id: locations[0]?.id?.toString() || ''
    });
    setReturnModalOpen(true);
  };

  const handleBorrowSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedInventoryItem) return;
    
    if (!borrowForm.issued_to_id) {
      alert('Please select a Club or Sport to issue the item to.');
      return;
    }
    if (!borrowForm.store_id) {
      alert('Please select a store location.');
      return;
    }

    const targetClub = clubs.find(c => c.id === parseInt(borrowForm.issued_to_id));
    setBorrowSubmitting(true);
    try {
      await issueItem({
        item_id: selectedInventoryItem.id,
        store_id: parseInt(borrowForm.store_id),
        issued_to_type: targetClub?.type || 'club',
        issued_to_id: parseInt(borrowForm.issued_to_id),
        quantity: borrowForm.quantity,
        purpose: borrowForm.purpose,
        return_due_date: borrowForm.return_due_date,
        notes: borrowForm.notes
      });
      setBorrowModalOpen(false);
      alert('Equipment borrowed successfully.');
      fetchItems();
      fetchIssues();
    } catch (err: any) {
      alert(err.response?.data?.error || err.message || 'Failed to borrow equipment');
    } finally {
      setBorrowSubmitting(false);
    }
  };

  const handleReturnSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedIssueForReturn) return;

    if (!returnForm.store_id) {
      alert('Please select a store location to return the item to.');
      return;
    }

    setReturnSubmitting(true);
    try {
      await returnItem(selectedIssueForReturn.id, {
        quantity: returnForm.quantity,
        condition: returnForm.condition,
        store_id: parseInt(returnForm.store_id)
      });
      setReturnModalOpen(false);
      alert('Equipment returned successfully.');
      fetchItems();
      fetchIssues();
    } catch (err: any) {
      alert(err.response?.data?.error || err.message || 'Failed to return equipment');
    } finally {
      setReturnSubmitting(false);
    }
  };
  
  const [formData, setFormData] = useState({
    name: '',
    type: 'club' as 'club' | 'sport',
    description: '',
    teacher_in_charge_id: '',
    schedule: '',
    max_members: '',
    status: 'active' as 'active' | 'inactive'
  });

  const fetchClubs = async () => {
    try {
      setLoading(true);
      const response = await api.get('/clubs');
      setClubs(response.data);
    } catch (error) {
      console.error('Error fetching clubs:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchTeachers = async () => {
    try {
      const response = await api.get('/users?role=teacher&limit=200');
      const data = Array.isArray(response.data) ? response.data : (response.data?.users || []);
      setTeachers(data);
    } catch (error) {
      console.error('Error fetching teachers:', error);
    }
  };

  const fetchStudents = async () => {
    try {
        const res = await api.get('/users', { params: { role: 'student', limit: 1000 } });
        const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
        setStudents(data.map((s: any) => ({
          id: s.id,
          full_name: `${s.first_name} ${s.last_name}`,
          class_name: s.class_name
        })));
    } catch (err) {
        console.error('Error fetching students');
    }
  };

  useEffect(() => {
    fetchClubs();
    fetchTeachers();
    fetchStudents();

    const interval = setInterval(() => {
        fetchClubs();
    }, 30000); // 30s polling

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

  const handleOpenCreate = () => {
    setModalType('create');
    setFormData({
      name: '',
      type: 'club',
      description: '',
      teacher_in_charge_id: teachers[0]?.id?.toString() || '',
      schedule: '',
      max_members: '',
      status: 'active'
    });
    setShowModal(true);
  };

  const handleOpenEdit = (club: Club) => {
    setModalType('edit');
    setSelectedClub(club);
    setFormData({
      name: club.name,
      type: club.type,
      description: club.description || '',
      teacher_in_charge_id: club.teacher_in_charge_id?.toString() || '',
      schedule: club.schedule || '',
      max_members: club.max_members?.toString() || '',
      status: club.status
    });
    setShowModal(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    
    const payload = {
      ...formData,
      teacher_in_charge_id: formData.teacher_in_charge_id ? parseInt(formData.teacher_in_charge_id) : null,
      max_members: formData.max_members ? parseInt(formData.max_members) : null
    };

    try {
      if (modalType === 'create') {
        await api.post('/clubs', payload);
      } else if (selectedClub) {
        await api.put(`/clubs/${selectedClub.id}`, payload);
      }
      setShowModal(false);
      fetchClubs();
    } catch (err) {
      alert(`Failed to save extracurricular activity: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this extracurricular activity?')) return;
    try {
      await api.delete(`/clubs/${id}`);
      fetchClubs();
    } catch (err) {
      alert('Failed to delete activity');
    }
  };

  const filteredClubs = clubs.filter(c => 
    c.name.toLowerCase().includes(search.toLowerCase()) || 
    c.type.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="p-6 md:p-8 space-y-8 animate-in fade-in duration-500 pb-12">
      {/* Page Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-black text-text flex items-center gap-2 uppercase tracking-tight">
            <Trophy className="text-primary" size={32} />
            Extracurricular Management
          </h1>
          <p className="text-text-muted text-sm mt-1">Oversee and coordinate school-wide sports teams, clubs, and teacher assignments</p>
        </div>
        {activeTab === 'registry' && (
          <button
            onClick={handleOpenCreate}
            className="flex items-center justify-center gap-2 px-6 py-3 bg-primary text-white rounded-xl hover:bg-primary/95 transition-all shadow-md active:scale-95 font-bold text-sm uppercase tracking-wider"
          >
            <Plus size={18} />
            Create Activity
          </button>
        )}
      </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: 'registry', label: 'Activity Registry', icon: List },
            { id: 'attendance', label: 'Take Attendance', icon: ClipboardCheck },
            { id: 'history', label: 'Attendance History', icon: History },
            { id: 'inventory', label: 'Borrow Equipment', icon: Package },
          ].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>

        {activeTab === 'registry' && (
          <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 by activity name or category..."
              value={search}
              onChange={e => setSearch(e.target.value)}
            />
          </div>
        )}
      </div>

      {/* Main Content */}
      <div className="min-h-[400px]">
        {activeTab === 'registry' ? (
          <div className="bg-card border border-border rounded-[2rem] shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-muted/30 border-b border-border text-[0.65rem] font-black text-primary uppercase tracking-widest">
                    <th className="px-6 py-4">Activity Info</th>
                    <th className="px-6 py-4">Teacher in Charge (Club Head)</th>
                    <th className="px-6 py-4">Schedule</th>
                    <th className="px-6 py-4">Capacity</th>
                    <th className="px-6 py-4">Status</th>
                    <th className="px-6 py-4 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border/50 text-sm font-medium text-text">
                  {loading ? (
                    <tr><td colSpan={6} className="px-6 py-12 text-center text-text-muted italic">Loading records...</td></tr>
                  ) : filteredClubs.length === 0 ? (
                    <tr><td colSpan={6} className="px-6 py-12 text-center text-text-muted italic">No extracurricular activities found</td></tr>
                  ) : (
                    filteredClubs.map((club) => (
                      <tr key={club.id} className="hover:bg-muted/10 transition-colors">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className={`w-10 h-10 rounded-xl flex items-center justify-center text-white ${club.type === 'sport' ? 'bg-orange-500 shadow-orange-500/20' : 'bg-blue-600 shadow-blue-600/20'}`}>
                              {club.type === 'sport' ? <Trophy size={18} /> : <User size={18} />}
                            </div>
                            <div>
                              <p className="font-bold text-text text-base">{club.name}</p>
                              <span className={`inline-flex mt-1 items-center px-2 py-0.5 rounded text-[0.55rem] font-black uppercase tracking-wider border ${
                                club.type === 'sport' 
                                  ? 'bg-orange-50 text-orange-600 border-orange-100 dark:bg-orange-950/30 dark:text-orange-400 dark:border-orange-900/50' 
                                  : 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-900/50'
                              }`}>
                                {club.type}
                              </span>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2 text-text-secondary font-medium">
                            <User size={14} className="text-text-muted" />
                            {club.teacher_name || 'Unassigned'}
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <p className="text-xs text-text-muted font-bold uppercase tracking-widest">{club.schedule || 'TBA'}</p>
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            <div className="flex flex-col items-center bg-muted/40 px-3 py-1 rounded-lg border border-border">
                              <span className="text-[0.55rem] text-text-muted font-black uppercase tracking-wider">Enrolled</span>
                              <span className="text-sm font-black text-text">{club.current_members || 0}</span>
                            </div>
                            <span className="text-text-muted text-xs font-bold">/</span>
                            <div className="flex flex-col items-center bg-muted/40 px-3 py-1 rounded-lg border border-border">
                              <span className="text-[0.55rem] text-text-muted font-black uppercase tracking-wider">Max</span>
                              <span className="text-sm font-black text-text">{club.max_members || '∞'}</span>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4">
                          <span className={`px-2.5 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                            club.status === 'active' 
                              ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-950/30 dark:text-emerald-400 dark:border-emerald-900/50' 
                              : 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-950/30 dark:text-rose-400 dark:border-rose-900/50'
                          }`}>
                            {club.status}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-right">
                          <div className="flex items-center justify-end gap-2">
                            <button
                              onClick={() => handleOpenEdit(club)}
                              className="p-2 text-text-muted hover:text-primary hover:bg-primary/5 rounded-xl transition-all cursor-pointer"
                              title="Edit"
                            >
                              <Edit2 size={16} />
                            </button>
                            <button
                              onClick={() => handleDelete(club.id)}
                              className="p-2 text-text-muted hover:text-rose-600 hover:bg-rose-500/5 rounded-xl transition-all cursor-pointer"
                              title="Delete"
                            >
                              <Trash2 size={16} />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        ) : activeTab === 'attendance' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceTakeView initialContext="club" showTabs={false} />
          </div>
        ) : activeTab === 'history' ? (
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <AttendanceHistoryView studentOptions={students} tabs={['club']} />
          </div>
        ) : (
          <div className="space-y-6">
            {/* Sub-tabs & Search */}
            <div className="flex flex-col md:flex-row items-stretch md:items-center justify-between gap-4">
              <div className="flex p-1 bg-muted/50 rounded-2xl w-fit">
                <button
                  onClick={() => setInventorySubTab('catalog')}
                  className={`px-5 py-2.5 rounded-xl text-xs font-bold transition-all ${inventorySubTab === 'catalog' ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}`}
                >
                  Sports & Clubs Catalog
                </button>
                <button
                  onClick={() => setInventorySubTab('borrowed')}
                  className={`px-5 py-2.5 rounded-xl text-xs font-bold transition-all ${inventorySubTab === 'borrowed' ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}`}
                >
                  Borrowed Equipment
                </button>
              </div>

              <div className="relative group flex-1 max-w-md">
                <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 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={inventorySubTab === 'catalog' ? "Search equipment by name or code..." : "Search borrowed items..."}
                  value={searchInventory}
                  onChange={e => setSearchInventory(e.target.value)}
                />
              </div>
            </div>

            {/* Sub-tab Content */}
            {inventorySubTab === 'catalog' ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {inventoryLoading ? (
                  <div className="col-span-full py-12 text-center text-text-muted italic">Loading catalog items...</div>
                ) : (() => {
                  const sportsItems = items.filter(item => item.category_id === 6 || item.category_name?.toLowerCase().includes('sport'));
                  const filtered = sportsItems.filter(item => 
                    item.name.toLowerCase().includes(searchInventory.toLowerCase()) ||
                    item.code?.toLowerCase().includes(searchInventory.toLowerCase())
                  );

                  if (filtered.length === 0) {
                    return <div className="col-span-full py-12 text-center text-text-muted italic">No matching equipment found in catalog</div>;
                  }

                  return filtered.map(item => {
                    const isOutOfStock = !item.total_stock || item.total_stock <= 0;
                    return (
                      <div key={item.id} className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-xl transition-all group relative overflow-hidden flex flex-col justify-between">
                        <div>
                          <div className="flex items-start gap-4 mb-4">
                            <div className="w-12 h-12 bg-primary/5 rounded-2xl flex items-center justify-center text-primary group-hover:scale-110 transition-transform duration-500">
                              <Package size={24} />
                            </div>
                            <div>
                              <h4 className="font-black text-lg text-text tracking-tight group-hover:text-primary transition-colors">{item.name}</h4>
                              <p className="text-xs text-text-muted mt-0.5">{item.code || 'NO CODE'} • {item.category_name || 'Sports & Grounds'}</p>
                            </div>
                          </div>
                          <p className="text-xs text-text-muted line-clamp-2 mb-4">{item.description || 'No description available.'}</p>
                        </div>

                        <div className="space-y-4">
                          <div className="p-3 bg-muted/40 rounded-xl border border-border flex justify-between items-center">
                            <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-wider">Available Stock</span>
                            <span className={`text-base font-black ${isOutOfStock ? 'text-rose-500' : 'text-emerald-500'}`}>
                              {item.total_stock || 0} {item.unit}
                            </span>
                          </div>

                          <button
                            onClick={() => handleOpenBorrow(item)}
                            disabled={isOutOfStock}
                            className={`w-full py-2.5 rounded-xl font-bold text-xs uppercase tracking-widest transition-all flex items-center justify-center gap-2 ${
                              isOutOfStock 
                                ? 'bg-muted text-text-muted cursor-not-allowed border border-border' 
                                : 'bg-primary text-white hover:bg-primary/90 shadow-md active:scale-95'
                            }`}
                          >
                            <Package size={14} />
                            {isOutOfStock ? 'Out of Stock' : 'Borrow Equipment'}
                          </button>
                        </div>
                      </div>
                    );
                  });
                })()}
              </div>
            ) : (
              <div className="bg-card border border-border rounded-[2rem] shadow-sm overflow-hidden">
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse">
                    <thead>
                      <tr className="bg-muted/30 border-b border-border text-[0.65rem] font-black text-primary uppercase tracking-widest">
                        <th className="px-6 py-4">Borrowed Item</th>
                        <th className="px-6 py-4">Issued To</th>
                        <th className="px-6 py-4">Quantity</th>
                        <th className="px-6 py-4">Purpose</th>
                        <th className="px-6 py-4">Borrow Date</th>
                        <th className="px-6 py-4">Return Due Date</th>
                        <th className="px-6 py-4">Issuer</th>
                        <th className="px-6 py-4 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border/50 text-sm font-medium text-text">
                      {inventoryLoading ? (
                        <tr><td colSpan={8} className="px-6 py-12 text-center text-text-muted italic">Loading borrowed records...</td></tr>
                      ) : (() => {
                        const extracurricularIssues = issues.filter(iss => 
                          (iss.issued_to_type === 'sport' || iss.issued_to_type === 'club') &&
                          iss.status !== 'returned'
                        );
                        const filtered = extracurricularIssues.filter(iss =>
                          iss.item_name?.toLowerCase().includes(searchInventory.toLowerCase()) ||
                          iss.purpose?.toLowerCase().includes(searchInventory.toLowerCase())
                        );

                        if (filtered.length === 0) {
                          return <tr><td colSpan={8} className="px-6 py-12 text-center text-text-muted italic">No active borrowed equipment found</td></tr>;
                        }

                        return filtered.map(iss => {
                          const targetName = clubs.find(c => c.id === iss.issued_to_id)?.name || `${iss.issued_to_type.toUpperCase()} (ID: ${iss.issued_to_id})`;
                          const isOverdue = new Date(iss.return_due_date) < new Date() && iss.status !== 'returned';

                          return (
                            <tr key={iss.id} className="hover:bg-muted/10 transition-colors">
                              <td className="px-6 py-4">
                                <span className="font-bold text-text">{iss.item_name}</span>
                              </td>
                              <td className="px-6 py-4">
                                <span className="px-2.5 py-1 rounded bg-primary/5 text-primary border border-primary/10 dark:bg-primary/10 dark:text-primary-light text-xs font-bold uppercase">{targetName}</span>
                              </td>
                              <td className="px-6 py-4 font-bold text-text-muted">
                                {iss.quantity - (iss.returned_quantity || 0)} / {iss.quantity}
                              </td>
                              <td className="px-6 py-4">
                                <p className="text-text-secondary text-xs truncate max-w-xs">{iss.purpose || 'N/A'}</p>
                              </td>
                              <td className="px-6 py-4 text-xs font-bold text-text-muted uppercase">
                                {iss.issue_date ? new Date(iss.issue_date).toLocaleDateString() : 'N/A'}
                              </td>
                              <td className="px-6 py-4 text-xs">
                                <span className={`font-bold uppercase ${isOverdue ? 'text-rose-500' : 'text-text-muted'}`}>
                                  {iss.return_due_date ? new Date(iss.return_due_date).toLocaleDateString() : 'N/A'}
                                </span>
                                {isOverdue && <span className="ml-1 text-[0.6rem] font-black uppercase text-rose-500 bg-rose-50 border border-rose-100 dark:bg-rose-950/30 dark:text-rose-400 dark:border-rose-900/50 px-1 py-0.5 rounded">Overdue</span>}
                              </td>
                              <td className="px-6 py-4 text-text-secondary text-xs">
                                {iss.issuer_name || 'System Admin'}
                              </td>
                              <td className="px-6 py-4 text-right">
                                <button
                                  onClick={() => handleOpenReturn(iss)}
                                  className="px-3 py-1.5 bg-emerald-500/10 hover:bg-emerald-500 hover:text-white text-emerald-600 rounded-lg text-xs font-black uppercase tracking-widest transition-all"
                                >
                                  Return
                                </button>
                              </td>
                            </tr>
                          );
                        });
                      })()}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={() => setShowModal(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-lg border border-border overflow-hidden shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
            <div className="px-8 py-6 bg-muted/20 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text uppercase tracking-tight">
                {modalType === 'create' ? 'Create Extracurricular' : 'Edit Extracurricular'}
              </h2>
              <button 
                className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer" 
                onClick={() => setShowModal(false)}
              >
                <X size={20} />
              </button>
            </div>

            
            <form onSubmit={handleSubmit} className="p-8 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Activity Name</label>
                <input 
                  className="form-input text-text" 
                  value={formData.name} 
                  onChange={e => setFormData({...formData, name: e.target.value})} 
                  required 
                  placeholder="e.g. Science Club or Football Team" 
                />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Type</label>
                  <select 
                    className="form-input text-text" 
                    value={formData.type} 
                    onChange={e => setFormData({...formData, type: e.target.value as 'club' | 'sport'})}
                  >
                    <option value="club">Club & Society</option>
                    <option value="sport">Sport Team</option>
                  </select>
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Status</label>
                  <select 
                    className="form-input text-text" 
                    value={formData.status} 
                    onChange={e => setFormData({...formData, status: e.target.value as 'active' | 'inactive'})}
                  >
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                  </select>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Teacher in Charge (Club Head)</label>
                <select
                  className="form-input text-text"
                  value={formData.teacher_in_charge_id}
                  onChange={e => setFormData({...formData, teacher_in_charge_id: e.target.value})}
                  required
                >
                  <option value="">Select a teacher...</option>
                  {teachers.map(t => (
                    <option key={t.id} value={t.id}>
                      {t.first_name} {t.last_name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Schedule</label>
                  <input 
                    className="form-input text-text" 
                    value={formData.schedule} 
                    onChange={e => setFormData({...formData, schedule: e.target.value})} 
                    placeholder="e.g. Fridays 14:00 - 15:30" 
                  />
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Max Members (0 for unlimited)</label>
                  <input 
                    type="number"
                    className="form-input text-text" 
                    value={formData.max_members} 
                    onChange={e => setFormData({...formData, max_members: e.target.value})} 
                    placeholder="e.g. 30" 
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Description</label>
                <textarea 
                  className="form-input text-text" 
                  value={formData.description} 
                  onChange={e => setFormData({...formData, description: e.target.value})} 
                  rows={3} 
                  placeholder="Define activity objectives and details..." 
                />
              </div>

              <div className="flex gap-4 pt-4 border-t border-border">
                <button 
                  type="button" 
                  onClick={() => setShowModal(false)} 
                  className="flex-1 py-3 bg-muted rounded-xl text-xs font-black uppercase tracking-wider text-text-muted hover:bg-muted/80 transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  disabled={submitting} 
                  className="flex-1 py-3 bg-primary text-white rounded-xl text-xs font-black uppercase tracking-wider hover:bg-primary/95 transition-all shadow-md active:scale-95 disabled:opacity-50"
                >
                  {submitting ? 'Saving...' : 'Save Activity'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Borrow Modal */}
      {borrowModalOpen && selectedInventoryItem && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={() => setBorrowModalOpen(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-lg border border-border overflow-hidden shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
            <div className="px-8 py-6 bg-muted/20 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text uppercase tracking-tight flex items-center gap-2">
                <Package className="text-primary" size={24} />
                Borrow {selectedInventoryItem.name}
              </h2>
              <button 
                className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer" 
                onClick={() => setBorrowModalOpen(false)}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleBorrowSubmit} className="p-8 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Borrowing Club or Sport</label>
                <select
                  value={borrowForm.issued_to_id}
                  onChange={e => {
                    const selectedClub = clubs.find(c => c.id === parseInt(e.target.value));
                    setBorrowForm({
                      ...borrowForm,
                      issued_to_id: e.target.value,
                      issued_to_type: selectedClub?.type || 'club'
                    });
                  }}
                  className="form-input text-text"
                  required
                >
                  <option value="">Select Club/Sport...</option>
                  {clubs.map(c => (
                    <option key={c.id} value={c.id}>{c.name} ({c.type.toUpperCase()})</option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Store Location</label>
                  <select
                    value={borrowForm.store_id}
                    onChange={e => setBorrowForm({ ...borrowForm, store_id: e.target.value })}
                    className="form-input text-text"
                    required
                  >
                    <option value="">Select Location...</option>
                    {locations.map(loc => (
                      <option key={loc.id} value={loc.id}>{loc.name} ({loc.code})</option>
                    ))}
                  </select>
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Quantity (Max: {selectedInventoryItem.total_stock || 0})</label>
                  <input 
                    type="number"
                    className="form-input text-text" 
                    value={borrowForm.quantity} 
                    onChange={e => setBorrowForm({...borrowForm, quantity: Math.min(selectedInventoryItem.total_stock || 1, Math.max(1, parseInt(e.target.value) || 1))})} 
                    min={1}
                    max={selectedInventoryItem.total_stock || 1}
                    required 
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Purpose</label>
                  <input 
                    className="form-input text-text" 
                    value={borrowForm.purpose} 
                    onChange={e => setBorrowForm({...borrowForm, purpose: e.target.value})} 
                    placeholder="e.g. Football match practice" 
                    required
                  />
                </div>
                
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Return Due Date</label>
                  <input 
                    type="date"
                    className="form-input text-text" 
                    value={borrowForm.return_due_date} 
                    onChange={e => setBorrowForm({...borrowForm, return_due_date: e.target.value})} 
                    required 
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Notes / Remarks</label>
                <textarea 
                  className="form-input text-text" 
                  value={borrowForm.notes} 
                  onChange={e => setBorrowForm({...borrowForm, notes: e.target.value})} 
                  rows={2} 
                  placeholder="Optional remarks..." 
                />
              </div>

              <div className="flex gap-4 pt-4 border-t border-border">
                <button 
                  type="button" 
                  onClick={() => setBorrowModalOpen(false)} 
                  className="flex-1 py-3 bg-muted rounded-xl text-xs font-black uppercase tracking-wider text-text-muted hover:bg-muted/80 transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  disabled={borrowSubmitting} 
                  className="flex-1 py-3 bg-primary text-white rounded-xl text-xs font-black uppercase tracking-wider hover:bg-primary/95 transition-all shadow-md active:scale-95 disabled:opacity-50"
                >
                  {borrowSubmitting ? 'Processing...' : 'Borrow Equipment'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}

      {/* Return Modal */}
      {returnModalOpen && selectedIssueForReturn && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={() => setReturnModalOpen(false)}>
          <div className="bg-card rounded-[2.5rem] w-full max-w-lg border border-border overflow-hidden shadow-2xl animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
            <div className="px-8 py-6 bg-muted/20 border-b border-border flex justify-between items-center">
              <h2 className="text-xl font-black text-text uppercase tracking-tight flex items-center gap-2">
                <Package className="text-primary" size={24} />
                Return {selectedIssueForReturn.item_name}
              </h2>
              <button 
                className="p-1.5 text-text-muted hover:text-rose-500 rounded-lg hover:bg-muted/50 transition-colors cursor-pointer" 
                onClick={() => setReturnModalOpen(false)}
              >
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleReturnSubmit} className="p-8 space-y-6">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Return Quantity</label>
                  <input 
                    type="number"
                    className="form-input text-text" 
                    value={returnForm.quantity} 
                    onChange={e => setReturnForm({...returnForm, quantity: Math.min(selectedIssueForReturn.quantity - (selectedIssueForReturn.returned_quantity || 0), Math.max(1, parseInt(e.target.value) || 1))})} 
                    min={1}
                    max={selectedIssueForReturn.quantity - (selectedIssueForReturn.returned_quantity || 0)}
                    required 
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Return To Location</label>
                  <select
                    value={returnForm.store_id}
                    onChange={e => setReturnForm({ ...returnForm, store_id: e.target.value })}
                    className="form-input text-text"
                    required
                  >
                    <option value="">Select Location...</option>
                    {locations.map(loc => (
                      <option key={loc.id} value={loc.id}>{loc.name} ({loc.code})</option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">Return Condition</label>
                <select
                  value={returnForm.condition}
                  onChange={e => setReturnForm({ ...returnForm, condition: e.target.value })}
                  className="form-input text-text"
                  required
                >
                  <option value="Good">Good / Undamaged</option>
                  <option value="Damaged">Damaged / Needs Repair</option>
                  <option value="Lost">Lost / Unreturned</option>
                </select>
              </div>

              <div className="flex gap-4 pt-4 border-t border-border">
                <button 
                  type="button" 
                  onClick={() => setReturnModalOpen(false)} 
                  className="flex-1 py-3 bg-muted rounded-xl text-xs font-black uppercase tracking-wider text-text-muted hover:bg-muted/80 transition-colors"
                >
                  Cancel
                </button>
                <button 
                  type="submit" 
                  disabled={returnSubmitting} 
                  className="flex-1 py-3 bg-primary text-white rounded-xl text-xs font-black uppercase tracking-wider hover:bg-primary/95 transition-all shadow-md active:scale-95 disabled:opacity-50"
                >
                  {returnSubmitting ? 'Processing...' : 'Confirm Return'}
                </button>
              </div>
            </form>
          </div>
        </div>
      ,
        document.body
      )}
    </div>
  );
}
