import { useState, useEffect } from 'react';
import { useAttendanceStore } from '../../store/attendance';
import AttendanceTakeView from '../../components/AttendanceTakeView';
import AttendanceHistoryView from '../../components/AttendanceHistoryView';
import api from '../../store/api';
import { ClipboardCheck, History, User } from 'lucide-react';

export default function StaffAttendance() {
  const [activeTab, setActiveTab] = useState('take'); // take, history
  const [staffOptions, setStaffOptions] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [roleFilter, setRoleFilter] = useState('all');

  const roles = [
    { id: 'all', label: 'All Staff' },
    { id: 'teacher', label: 'Teachers' },
    { id: 'driver', label: 'Drivers' },
    { id: 'groundsman', label: 'Groundsmen' },
    { id: 'matron', label: 'Matrons' },
    { id: 'boarding_master', label: 'Boarding Masters' },
    { id: 'security', label: 'Security' },
    { id: 'janitor', label: 'Janitors' },
    { id: 'school_admin', label: 'Admins' },
  ];

  const fetchStaff = async () => {
    try {
      setLoading(true);
      const res = await api.get('/users', { params: { limit: 1000 } });
      const data = Array.isArray(res.data) ? res.data : (res.data?.users || []);
      const staff = data.filter((u: any) => !['student', 'parent'].includes(u.role));
      setStaffOptions(staff.map((s: any) => ({
        id: s.id,
        full_name: `${s.first_name} ${s.last_name}`,
        role: s.role
      })));
    } catch (err) {
      console.error('Error fetching staff');
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Staff Attendance</h2>
          <p className="text-text-muted text-sm mt-1">Institutional support and faculty roll-call.</p>
        </div>

        <div className="flex flex-col md:flex-row gap-3">
          {activeTab === 'take' && (
            <div className="flex p-1 bg-muted/30 rounded-2xl border border-border focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary transition-all">
              <select 
                value={roleFilter}
                onChange={e => setRoleFilter(e.target.value)}
                className="bg-transparent text-[0.65rem] font-black uppercase tracking-widest px-4 py-2 outline-none cursor-pointer text-text-secondary hover:text-primary transition-colors dark:text-text-secondary"
              >
                {roles.map(r => (
                  <option 
                    key={r.id} 
                    value={r.id} 
                    className="bg-card text-text dark:bg-card-elevated dark:text-text"
                  >
                    {r.label}
                  </option>
                ))}
              </select>
            </div>
          )}

          <div className="flex p-1 bg-muted/50 rounded-2xl">
            {[
              { id: 'take', label: 'Take Attendance', icon: ClipboardCheck },
              { id: 'history', label: 'History', icon: History },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`
                  px-6 py-2 rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all flex items-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>
      </div>

      <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
        {activeTab === 'take' ? (
          <AttendanceTakeView 
            initialContext="staff" 
            showTabs={false} 
            roleFilter={roleFilter !== 'all' ? roleFilter : undefined} 
          />
        ) : (
          <AttendanceHistoryView 
            studentOptions={staffOptions} 
            tabs={['staff']} 
            defaultTab="staff"
            hideStudentPicker={false}
          />
        )}
      </div>
    </div>
  );
}
