"use client";

import { useState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  Student,
  DayOfWeek,
  DayGroup,
  GeneratedSchedule,
  Department,
  SectionCapacity,
  ShiftType,
  SHIFT_TYPES,
  DAY_GROUP_OPTIONS,
  getDepartmentSections,
  getDepartmentSectionNames,
  getDepartmentSectionColors,
  getDepartmentFemaleRestricted,
  getDepartmentBaseSections,
  getDepartmentBaseSectionNames
} from "@/lib/types";
import { generateSchedule } from "@/lib/scheduleGenerator";
import { getSchedule, saveSchedule, getScheduleInfo, deleteSchedule } from "@/lib/scheduleStorage";

// Department name mapping: dashboard Arabic keys -> schedule Department type
const DEPT_MAP: { [key in Department]: string } = {
  'pediatrics': 'الاطفال',
  'surgery': 'جراحة',
  'gynecology': 'نسائية',
};

// Gender detection from Arabic first names
function detectGender(name: string): 'M' | 'F' {
  const firstName = name.trim().split(' ')[0];
  // Common female Arabic name endings and patterns
  const femalePatterns = [
    /ة$/,   // ta marbuta
    /اء$/,  // alef hamza (e.g. رؤى، اسراء)
    /ى$/,   // alef maqsura (e.g. رؤى, هدى)
    /يره$/,
  ];
  const femaleNames = [
    'سجود', 'رشا', 'نسمه', 'تيماء', 'رناد', 'بيان', 'إسراء', 'اسراء',
    'ولاء', 'انسام', 'مي', 'نور', 'ديانا', 'رؤى', 'مرام', 'عروب',
    'سحر', 'لارا', 'رغد', 'خلود', 'إيمان', 'ايمان', 'جنا', 'هبة', 'هبه',
    'مرح', 'رجاء', 'دانا', 'جهينة', 'اسرار', 'براءه', 'رهف', 'روضة',
    'كوثر', 'شذى', 'منار', 'روند', 'ساجده', 'دنيا', 'لينا', 'عايده',
    'فاطمة', 'تالا', 'أريج', 'ضحى', 'دانيا', 'هديل', 'شيماء', 'ميار',
    'روز', 'رند', 'عندليب', 'وئام'
  ];
  
  if (femaleNames.includes(firstName)) return 'F';
  for (const pattern of femalePatterns) {
    if (pattern.test(firstName)) return 'F';
  }
  return 'M';
}

const durationOptions = [
  { value: 2, label: 'شهرين (8 أسابيع)', description: '~60 يوم' },
  { value: 3, label: 'ثلاثة أشهر (12 أسبوع)', description: '~90 يوم' },
  { value: 1, label: 'شهر واحد (4 أسابيع)', description: '~30 يوم' },
];

interface DepartmentConfig {
  id: Department;
  name: string;
  icon: string;
  color: string;
}

const departmentConfigs: { [key in Department]: DepartmentConfig } = {
  'pediatrics': { id: 'pediatrics', name: 'قسم الأطفال', icon: '👶', color: '#3498db' },
  'surgery': { id: 'surgery', name: 'قسم الجراحة', icon: '🏥', color: '#e74c3c' },
  'gynecology': { id: 'gynecology', name: 'قسم النسائية', icon: '👩‍⚕️', color: '#9b59b6' },
};

interface ScheduleGeneratorProps {
  department: Department;
}

export default function ScheduleGenerator({ department }: ScheduleGeneratorProps) {
  const router = useRouter();
  const config = departmentConfigs[department];
  
  const [students, setStudents] = useState<Student[]>([]);
  const [selectedStudents, setSelectedStudents] = useState<Set<string>>(new Set());
  const [loadingStudents, setLoadingStudents] = useState(true);
  
  // All students from all departments (for adding from global list)
  const [allGlobalStudents, setAllGlobalStudents] = useState<{ name: string; dept: string; student: any }[]>([]);
  const [addSearchTerm, setAddSearchTerm] = useState('');
  const [addedExtraIds, setAddedExtraIds] = useState<Set<string>>(new Set());
  
  // Default dates: today -> today + 2 months
  const today = new Date();
  const defaultStart = today.toISOString().split('T')[0];
  const defaultEnd = new Date(today.getFullYear(), today.getMonth() + 2, today.getDate()).toISOString().split('T')[0];
  const [startDate, setStartDate] = useState(defaultStart);
  const [endDate, setEndDate] = useState(defaultEnd);
  
  // Fetch real students from API
  useEffect(() => {
    const fetchStudents = async () => {
      setLoadingStudents(true);
      try {
        const res = await fetch('/api/students');
        if (res.ok) {
          const data = await res.json();
          const deptKey = DEPT_MAP[department];
          const deptStudents = data[deptKey] || [];
          
          const mapped: Student[] = deptStudents.map((s: any, i: number) => ({
            id: `${department}_${i + 1}`,
            name: s.name,
            gender: detectGender(s.name),
            startDate: s.startDate || defaultStart.split('-').reverse().join('/'),
            endDate: s.endDate || defaultEnd.split('-').reverse().join('/'),
            phone: s.phone || '',
            university: s.university || ''
          }));
          
          setStudents(mapped);
          setSelectedStudents(new Set(mapped.map((s: Student) => s.id)));
          
          // Build global students list (all departments)
          const globalList: { name: string; dept: string; student: any }[] = [];
          const seenNames = new Set<string>();
          for (const deptName of Object.keys(data)) {
            for (const s of (data[deptName] || [])) {
              if (!seenNames.has(s.name)) {
                seenNames.add(s.name);
                globalList.push({ name: s.name, dept: deptName, student: s });
              }
            }
          }
          setAllGlobalStudents(globalList);
        }
      } catch (err) {
        console.error('Failed to fetch students:', err);
        // Fallback to localStorage
        try {
          const local = localStorage.getItem('studentsData');
          if (local) {
            const data = JSON.parse(local);
            const deptKey = DEPT_MAP[department];
            const deptStudents = data[deptKey] || [];
            const mapped: Student[] = deptStudents.map((s: any, i: number) => ({
              id: `${department}_${i + 1}`,
              name: s.name,
              gender: detectGender(s.name),
              startDate: s.startDate || defaultStart.split('-').reverse().join('/'),
              endDate: s.endDate || defaultEnd.split('-').reverse().join('/'),
              phone: s.phone || '',
              university: s.university || ''
            }));
            setStudents(mapped);
            setSelectedStudents(new Set(mapped.map((s: Student) => s.id)));
            
            // Build global list from localStorage too
            const globalList: { name: string; dept: string; student: any }[] = [];
            const seenNames = new Set<string>();
            for (const deptName of Object.keys(data)) {
              for (const s of (data[deptName] || [])) {
                if (!seenNames.has(s.name)) {
                  seenNames.add(s.name);
                  globalList.push({ name: s.name, dept: deptName, student: s });
                }
              }
            }
            setAllGlobalStudents(globalList);
          }
        } catch {}
      } finally {
        setLoadingStudents(false);
      }
    };
    fetchStudents();
  }, [department]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  
  const [scheduleDuration, setScheduleDuration] = useState(2);
  const [daysPerWeek, setDaysPerWeek] = useState(2);
  const [shiftsPerWeek, setShiftsPerWeek] = useState(0); // 0 = no limit
  
  // Check for existing schedule
  const [existingSchedule, setExistingSchedule] = useState<{ exists: boolean; weeksCount?: number; studentsCount?: number } | null>(null);
  
  useEffect(() => {
    const info = getScheduleInfo(department);
    setExistingSchedule(info);
  }, [department]);

  const femaleRestrictedSections = useMemo(() => getDepartmentFemaleRestricted(department), [department]);
  const baseSections = useMemo(() => getDepartmentBaseSections(department), [department]);
  const baseSectionNames = useMemo(() => getDepartmentBaseSectionNames(department), [department]);

  // Section capacity state
  const [sectionCapacities, setSectionCapacities] = useState<SectionCapacity[]>([]);

  // Initialize section capacities when department changes
  useEffect(() => {
    const sections = getDepartmentBaseSections(department);
    setSectionCapacities(sections.map(s => ({ sectionBase: s, count: 2, shiftType: 'A' as ShiftType, dayGroup: 'sat_mon_wed' as DayGroup })));
  }, [department]);

  const totalCapacity = sectionCapacities.reduce((sum, c) => sum + c.count, 0);

  const updateCapacity = (sectionBase: string, count: number) => {
    setSectionCapacities(prev =>
      prev.map(c => c.sectionBase === sectionBase ? { ...c, count: Math.max(0, Math.min(100, count)) } : c)
    );
  };

  const updateShiftType = (sectionBase: string, shiftType: ShiftType) => {
    setSectionCapacities(prev =>
      prev.map(c => c.sectionBase === sectionBase ? { ...c, shiftType } : c)
    );
  };

  const updateDayGroup = (sectionBase: string, dayGroup: DayGroup) => {
    setSectionCapacities(prev =>
      prev.map(c => c.sectionBase === sectionBase ? { ...c, dayGroup } : c)
    );
  };

  // Max capacity per section (4 doctors per shift per section)
  const MAX_PER_SECTION = 4;
  const maxTotalCapacity = baseSections.length * MAX_PER_SECTION;

  // Set all sections to max capacity (4 per section)
  const setMaxCapacity = () => {
    setSectionCapacities(prev =>
      prev.map(c => ({ ...c, count: MAX_PER_SECTION }))
    );
  };

  // Smart auto-distribute: distribute available doctors evenly across sections
  const autoDistribute = () => {
    const totalDoctors = selectedStudents.size;
    const numSections = baseSections.length;
    if (numSections === 0) return;
    
    // Each section gets an equal share, capped at MAX_PER_SECTION
    const perSection = Math.min(MAX_PER_SECTION, Math.floor(totalDoctors / numSections));
    let remaining = totalDoctors - (perSection * numSections);
    
    setSectionCapacities(prev =>
      prev.map((c, i) => {
        // Distribute remaining doctors to first sections
        const extra = remaining > 0 && (perSection + 1) <= MAX_PER_SECTION ? 1 : 0;
        if (extra) remaining--;
        return { ...c, count: perSection + extra };
      })
    );
  };

  const calculateEndDate = (start: string, months: number) => {
    const startD = new Date(start);
    startD.setMonth(startD.getMonth() + months);
    return startD.toISOString().split('T')[0];
  };

  const handleDurationChange = (months: number) => {
    setScheduleDuration(months);
    setEndDate(calculateEndDate(startDate, months));
  };

  const handleStartDateChange = (date: string) => {
    setStartDate(date);
    setEndDate(calculateEndDate(date, scheduleDuration));
  };

  const showNotification = (message: string) => {
    setToastMessage(message);
    setShowToast(true);
    setTimeout(() => setShowToast(false), 3000);
  };

  const handleGenerate = async () => {
    setIsGenerating(true);
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    const selectedStudentsList = students.filter(s => selectedStudents.has(s.id));
    
    const generatedSchedule = generateSchedule({
      startDate: startDate.split('-').reverse().join('/'),
      endDate: endDate.split('-').reverse().join('/'),
      students: selectedStudentsList,
      daysPerWeek: daysPerWeek,
      shiftsPerWeek: shiftsPerWeek > 0 ? shiftsPerWeek : undefined,
      femaleRestrictedSections: femaleRestrictedSections,
      department: department,
      sectionCapacities: sectionCapacities
    });
    
    // Save to localStorage
    saveSchedule(department, generatedSchedule);
    
    setIsGenerating(false);
    showNotification("تم إنشاء الجدول! جاري الانتقال للمحرر...");
    
    // Redirect to editor
    setTimeout(() => {
      router.push(`/schedule/editor?dept=${department}`);
    }, 500);
  };

  const goToEditor = () => {
    router.push(`/schedule/editor?dept=${department}`);
  };

  const handleDeleteSchedule = () => {
    if (confirm('هل أنت متأكد من حذف الجدول المحفوظ؟ لا يمكن التراجع عن هذا الإجراء.')) {
      deleteSchedule(department);
      setExistingSchedule({ exists: false });
      showNotification("تم حذف الجدول! 🗑️");
    }
  };

  const toggleStudent = (studentId: string) => {
    const newSelected = new Set(selectedStudents);
    if (newSelected.has(studentId)) {
      newSelected.delete(studentId);
    } else {
      newSelected.add(studentId);
    }
    setSelectedStudents(newSelected);
  };

  const toggleAllStudents = () => {
    if (selectedStudents.size === students.length) {
      setSelectedStudents(new Set());
    } else {
      setSelectedStudents(new Set(students.map(s => s.id)));
    }
  };

  // Add a student from the global list
  const addGlobalStudent = (entry: { name: string; dept: string; student: any }) => {
    // Check if already in the list
    if (students.some(s => s.name === entry.name)) {
      showNotification(`${entry.name} موجود بالفعل في القائمة`);
      return;
    }
    const newId = `extra_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
    const newStudent: Student = {
      id: newId,
      name: entry.name,
      gender: detectGender(entry.name),
      startDate: startDate.split('-').reverse().join('/'),
      endDate: endDate.split('-').reverse().join('/'),
      phone: entry.student.phone || '',
      university: entry.student.university || ''
    };
    setStudents(prev => [...prev, newStudent]);
    setSelectedStudents(prev => new Set([...prev, newId]));
    setAddedExtraIds(prev => new Set([...prev, newId]));
    setAddSearchTerm('');
    showNotification(`✅ تمت إضافة ${entry.name}`);
  };

  const removeExtraStudent = (studentId: string) => {
    setStudents(prev => prev.filter(s => s.id !== studentId));
    setSelectedStudents(prev => { const n = new Set(prev); n.delete(studentId); return n; });
    setAddedExtraIds(prev => { const n = new Set(prev); n.delete(studentId); return n; });
  };

  return (
    <div className="dashboard-container" style={{ maxWidth: '1200px' }}>
      {/* Header */}
      <div style={{
        background: `linear-gradient(135deg, ${config.color} 0%, ${config.color}cc 100%)`,
        borderRadius: '24px',
        padding: '40px',
        marginBottom: '30px',
        color: 'white',
        position: 'relative',
        overflow: 'hidden',
        boxShadow: `0 20px 60px ${config.color}66`
      }}>
        <div style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'radial-gradient(circle at 20% 80%, rgba(255,255,255,0.1) 0%, transparent 50%)',
          pointerEvents: 'none'
        }} />
        
        <Link href="/schedule" style={{
          position: 'absolute',
          top: '20px',
          right: '20px',
          background: 'rgba(255,255,255,0.2)',
          padding: '10px 20px',
          borderRadius: '12px',
          color: 'white',
          textDecoration: 'none',
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          backdropFilter: 'blur(10px)',
          transition: 'all 0.3s'
        }}>
          ← الأقسام
        </Link>
        
        <div style={{ textAlign: 'center', position: 'relative', zIndex: 1 }}>
          <div style={{ fontSize: '4rem', marginBottom: '10px' }}>{config.icon}</div>
          <h1 style={{ fontSize: '2.5rem', fontWeight: '800', marginBottom: '10px' }}>
            {config.name}
          </h1>
          <p style={{ fontSize: '1.2rem', opacity: 0.9 }}>
            إنشاء جدول المناوبات
          </p>
        </div>
      </div>

      {/* Existing Schedule Card */}
      {existingSchedule?.exists && (
        <div style={{
          background: 'linear-gradient(135deg, #27ae60 0%, #1e8449 100%)',
          borderRadius: '20px',
          padding: '25px 30px',
          marginBottom: '25px',
          color: 'white',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '20px',
          boxShadow: '0 10px 40px rgba(39, 174, 96, 0.3)'
        }}>
          <div>
            <h3 style={{ margin: 0, marginBottom: '5px', display: 'flex', alignItems: 'center', gap: '10px' }}>
              <span style={{ fontSize: '1.5rem' }}>✅</span>
              يوجد جدول محفوظ
            </h3>
            <p style={{ margin: 0, opacity: 0.9 }}>
              {existingSchedule.weeksCount} أسبوع • {existingSchedule.studentsCount} طبيب
            </p>
          </div>
          <div style={{ display: 'flex', gap: '10px' }}>
            <button
              onClick={goToEditor}
              style={{
                background: 'white',
                color: '#27ae60',
                border: 'none',
                padding: '14px 30px',
                borderRadius: '12px',
                cursor: 'pointer',
                fontWeight: '700',
                fontSize: '1rem',
                display: 'flex',
                alignItems: 'center',
                gap: '8px'
              }}
            >
              فتح المحرر ✏️
            </button>
            <button
              onClick={handleDeleteSchedule}
              style={{
                background: 'rgba(255,255,255,0.2)',
                color: 'white',
                border: '2px solid rgba(255,255,255,0.5)',
                padding: '14px 20px',
                borderRadius: '12px',
                cursor: 'pointer',
                fontWeight: '700',
                fontSize: '1rem',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                transition: 'all 0.2s'
              }}
            >
              حذف 🗑️
            </button>
          </div>
        </div>
      )}

      {/* Configuration */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
        gap: '25px',
        marginBottom: '25px'
      }}>
        {/* Duration Selection */}
        <div style={{
          background: 'white',
          borderRadius: '20px',
          padding: '30px',
          boxShadow: '0 10px 40px rgba(0,0,0,0.08)'
        }}>
          <h3 style={{ marginBottom: '20px', display: 'flex', alignItems: 'center', gap: '10px', color: 'var(--text)' }}>
            <span style={{ fontSize: '1.5rem' }}>⏱️</span>
            مدة الجدول
          </h3>
          
          <div style={{ display: 'grid', gap: '12px' }}>
            {durationOptions.map(option => (
              <label
                key={option.value}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '12px',
                  padding: '15px',
                  borderRadius: '12px',
                  background: scheduleDuration === option.value ? `${config.color}15` : 'var(--bg-light)',
                  border: scheduleDuration === option.value ? `2px solid ${config.color}` : '2px solid transparent',
                  cursor: 'pointer',
                  transition: 'all 0.2s'
                }}
              >
                <input
                  type="radio"
                  name="duration"
                  checked={scheduleDuration === option.value}
                  onChange={() => handleDurationChange(option.value)}
                  style={{ width: '20px', height: '20px', accentColor: config.color }}
                />
                <div>
                  <div style={{ fontWeight: '600', color: 'var(--text)' }}>{option.label}</div>
                  <div style={{ fontSize: '0.85rem', color: 'var(--text-light)' }}>{option.description}</div>
                </div>
              </label>
            ))}
          </div>
        </div>

        {/* Date Selection */}
        <div style={{
          background: 'white',
          borderRadius: '20px',
          padding: '30px',
          boxShadow: '0 10px 40px rgba(0,0,0,0.08)'
        }}>
          <h3 style={{ marginBottom: '20px', display: 'flex', alignItems: 'center', gap: '10px', color: 'var(--text)' }}>
            <span style={{ fontSize: '1.5rem' }}>📆</span>
            تاريخ البداية والنهاية
          </h3>
          
          <div style={{ display: 'grid', gap: '15px' }}>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontWeight: '600', color: 'var(--text-light)' }}>
                تاريخ البداية
              </label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => handleStartDateChange(e.target.value)}
                style={{
                  width: '100%',
                  padding: '14px',
                  borderRadius: '12px',
                  border: '2px solid var(--border)',
                  fontSize: '1rem'
                }}
              />
            </div>
            <div>
              <label style={{ display: 'block', marginBottom: '8px', fontWeight: '600', color: 'var(--text-light)' }}>
                تاريخ النهاية
              </label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                style={{
                  width: '100%',
                  padding: '14px',
                  borderRadius: '12px',
                  border: '2px solid var(--border)',
                  fontSize: '1rem',
                  background: '#f8f9fa'
                }}
              />
            </div>
          </div>
        </div>

        {/* Section Capacity Configuration - في نفس الشبكة */}
        <div style={{
          background: 'white',
          borderRadius: '20px',
          padding: '30px',
          boxShadow: '0 10px 40px rgba(0,0,0,0.08)'
        }}>
          <h3 style={{ marginBottom: '15px', display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap', color: 'var(--text)' }}>
            <span style={{ fontSize: '1.3rem' }}>📊</span>
            <span style={{ fontSize: '0.95rem' }}>توزيع الأطباء</span>
            <span style={{
              background: totalCapacity > selectedStudents.size
                ? 'linear-gradient(135deg, #e74c3c, #c0392b)'
                : `linear-gradient(135deg, ${config.color}, ${config.color}cc)`,
              color: 'white',
              padding: '3px 8px',
              borderRadius: '20px',
              fontSize: '0.75rem'
            }}>
              {totalCapacity}/{maxTotalCapacity}
            </span>
          </h3>

          {/* Shifts per week selector */}
          <div style={{
            marginBottom: '14px',
            padding: '12px 14px',
            borderRadius: '12px',
            background: `linear-gradient(135deg, ${config.color}08, ${config.color}15)`,
            border: `2px solid ${config.color}25`
          }}>
            <div style={{ 
              fontSize: '0.85rem', fontWeight: '700', color: config.color, 
              marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '6px' 
            }}>
              ⏱️ عدد الشفتات لكل طبيب / أسبوع
            </div>
            <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
              {[0, 1, 2, 3, 4, 5, 6, 7].map(n => (
                <button
                  key={n}
                  onClick={() => setShiftsPerWeek(n)}
                  style={{
                    padding: '6px 10px',
                    borderRadius: '8px',
                    border: shiftsPerWeek === n ? `2px solid ${config.color}` : '2px solid #e0e0e0',
                    background: shiftsPerWeek === n ? config.color : 'white',
                    color: shiftsPerWeek === n ? 'white' : '#666',
                    fontSize: '0.8rem',
                    fontWeight: '700',
                    cursor: 'pointer',
                    transition: 'all 0.2s',
                    minWidth: n === 0 ? '70px' : '36px'
                  }}
                >
                  {n === 0 ? 'بدون حد' : n}
                </button>
              ))}
            </div>
            {shiftsPerWeek > 0 && (
              <div style={{ marginTop: '6px', fontSize: '0.75rem', color: '#888' }}>
                كل طبيب يعمل {shiftsPerWeek} شفت/أسبوع كحد أقصى
              </div>
            )}
          </div>

          {/* Smart buttons */}
          <div style={{ display: 'flex', gap: '6px', marginBottom: '12px' }}>
            <button
              onClick={autoDistribute}
              style={{
                flex: 1,
                padding: '8px 10px',
                borderRadius: '10px',
                border: 'none',
                background: `linear-gradient(135deg, ${config.color}, ${config.color}dd)`,
                color: 'white',
                fontSize: '0.78rem',
                fontWeight: '700',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '5px',
                transition: 'all 0.2s',
                boxShadow: `0 4px 15px ${config.color}40`
              }}
            >
              🧠 توزيع ذكي
            </button>
            <button
              onClick={setMaxCapacity}
              style={{
                flex: 1,
                padding: '8px 10px',
                borderRadius: '10px',
                border: `2px solid ${config.color}40`,
                background: `${config.color}10`,
                color: config.color,
                fontSize: '0.78rem',
                fontWeight: '700',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '5px',
                transition: 'all 0.2s'
              }}
            >
              ⚡ أقصى ({MAX_PER_SECTION}×{baseSections.length})
            </button>
          </div>

          <div style={{ display: 'grid', gap: '10px' }}>
            {sectionCapacities.map(cap => (
              <div key={cap.sectionBase} style={{
                display: 'flex',
                alignItems: 'center',
                gap: '10px',
                padding: '10px 14px',
                borderRadius: '12px',
                background: 'var(--bg-light)',
                transition: 'all 0.2s'
              }}>
                {/* Section name */}
                <div style={{
                  flex: 1,
                  fontWeight: '700',
                  fontSize: '0.85rem',
                  color: config.color
                }}>
                  {baseSectionNames[cap.sectionBase] || cap.sectionBase}
                </div>

                {/* Decrement button */}
                <button
                  onClick={() => updateCapacity(cap.sectionBase, cap.count - 1)}
                  style={{
                    width: '32px',
                    height: '32px',
                    borderRadius: '8px',
                    border: 'none',
                    background: cap.count > 0 ? `${config.color}20` : '#f1f3f4',
                    color: cap.count > 0 ? config.color : '#ccc',
                    fontSize: '1.1rem',
                    fontWeight: '800',
                    cursor: cap.count > 0 ? 'pointer' : 'default',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transition: 'all 0.2s'
                  }}
                >
                  −
                </button>

                {/* Number input */}
                <input
                  type="number"
                  min="0"
                  max="100"
                  value={cap.count}
                  onChange={(e) => updateCapacity(cap.sectionBase, parseInt(e.target.value) || 0)}
                  style={{
                    width: '52px',
                    textAlign: 'center',
                    padding: '6px',
                    borderRadius: '8px',
                    border: `2px solid ${config.color}40`,
                    fontSize: '1rem',
                    fontWeight: '700',
                    color: config.color,
                    outline: 'none'
                  }}
                />

                {/* Increment button */}
                <button
                  onClick={() => updateCapacity(cap.sectionBase, cap.count + 1)}
                  style={{
                    width: '32px',
                    height: '32px',
                    borderRadius: '8px',
                    border: 'none',
                    background: `${config.color}20`,
                    color: config.color,
                    fontSize: '1.1rem',
                    fontWeight: '800',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transition: 'all 0.2s'
                  }}
                >
                  +
                </button>

                {/* Shift type selector */}
                <select
                  value={cap.shiftType}
                  onChange={(e) => updateShiftType(cap.sectionBase, e.target.value as ShiftType)}
                  style={{
                    padding: '6px 4px',
                    borderRadius: '8px',
                    border: `2px solid ${config.color}40`,
                    fontSize: '0.78rem',
                    fontWeight: '700',
                    color: config.color,
                    background: `${config.color}08`,
                    outline: 'none',
                    cursor: 'pointer',
                    minWidth: '48px'
                  }}
                >
                  {SHIFT_TYPES.map(st => (
                    <option key={st} value={st}>{st}</option>
                  ))}
                </select>

                {/* Day group selector */}
                <select
                  value={cap.dayGroup}
                  onChange={(e) => updateDayGroup(cap.sectionBase, e.target.value as DayGroup)}
                  style={{
                    padding: '6px 4px',
                    borderRadius: '8px',
                    border: '2px solid #e5e7eb',
                    fontSize: '0.7rem',
                    fontWeight: '600',
                    color: '#555',
                    background: '#f8f9fa',
                    outline: 'none',
                    cursor: 'pointer',
                    minWidth: '80px'
                  }}
                >
                  {DAY_GROUP_OPTIONS.map(opt => (
                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                  ))}
                </select>
              </div>
            ))}
          </div>

          {/* Summary */}
          <div style={{
            marginTop: '15px',
            padding: '10px 14px',
            borderRadius: '10px',
            background: totalCapacity > selectedStudents.size
              ? '#fef2f2'
              : `${config.color}08`,
            border: totalCapacity > selectedStudents.size
              ? '2px solid #fecaca'
              : `2px solid ${config.color}20`,
            textAlign: 'center'
          }}>
            <span style={{ fontSize: '1rem' }}>
              {totalCapacity > selectedStudents.size ? '⚠️' : '✅'}
            </span>
            <span style={{
              fontWeight: '700',
              fontSize: '0.85rem',
              color: totalCapacity > selectedStudents.size ? '#dc2626' : 'var(--text)',
              marginRight: '8px'
            }}>
              {totalCapacity > selectedStudents.size
                ? `المطلوب ${totalCapacity} > المتاحين ${selectedStudents.size}`
                : `${totalCapacity} طبيب • ${Math.max(0, selectedStudents.size - totalCapacity)} OFF`
              }
            </span>
          </div>
        </div>
      </div>

      {/* Students Selection */}
      <div style={{
        background: 'white',
        borderRadius: '20px',
        padding: '30px',
        boxShadow: '0 10px 40px rgba(0,0,0,0.08)',
        marginBottom: '25px'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <h3 style={{ display: 'flex', alignItems: 'center', gap: '10px', color: 'var(--text)' }}>
            <span style={{ fontSize: '1.5rem' }}>👨‍⚕️</span>
            الأطباء المشاركين
            <span style={{
              background: `linear-gradient(135deg, ${config.color}, ${config.color}cc)`,
              color: 'white',
              padding: '4px 12px',
              borderRadius: '20px',
              fontSize: '0.85rem'
            }}>
              {selectedStudents.size}/{students.length}
            </span>
          </h3>
          <button
            onClick={toggleAllStudents}
            style={{
              background: 'var(--bg-light)',
              border: 'none',
              padding: '8px 16px',
              borderRadius: '8px',
              cursor: 'pointer',
              fontSize: '0.9rem',
              fontWeight: '600'
            }}
          >
            {selectedStudents.size === students.length ? 'إلغاء الكل' : 'تحديد الكل'}
          </button>
        </div>
        
        <div style={{
          maxHeight: '200px',
          overflowY: 'auto',
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
          gap: '8px'
        }}>
          {students.map(student => {
            const isExtra = addedExtraIds.has(student.id);
            return (
              <label
                key={student.id}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '10px',
                  padding: '10px 15px',
                  borderRadius: '10px',
                  background: selectedStudents.has(student.id) ? `${config.color}10` : 'var(--bg-light)',
                  border: selectedStudents.has(student.id) ? `2px solid ${config.color}` : '2px solid transparent',
                  cursor: 'pointer',
                  transition: 'all 0.2s'
                }}
              >
                <input
                  type="checkbox"
                  checked={selectedStudents.has(student.id)}
                  onChange={() => toggleStudent(student.id)}
                  style={{ accentColor: config.color }}
                />
                <span style={{
                  width: '8px',
                  height: '8px',
                  borderRadius: '50%',
                  background: student.gender === 'M' ? '#3498db' : '#e91e63'
                }} />
                <span style={{ fontWeight: '500', fontSize: '0.9rem', flex: 1 }}>{student.name}</span>
                <select
                  value={student.shiftType || ''}
                  onClick={(e) => e.stopPropagation()}
                  onChange={(e) => {
                    e.stopPropagation();
                    const newVal = e.target.value as ShiftType | '';
                    setStudents(prev => prev.map(s => 
                      s.id === student.id ? { ...s, shiftType: newVal || undefined } : s
                    ));
                  }}
                  style={{
                    padding: '3px 4px',
                    borderRadius: '6px',
                    border: student.shiftType ? `2px solid ${config.color}` : '1px solid #ddd',
                    fontSize: '0.7rem',
                    fontWeight: '700',
                    color: student.shiftType ? config.color : '#aaa',
                    background: student.shiftType ? `${config.color}10` : '#f8f9fa',
                    outline: 'none',
                    cursor: 'pointer',
                    minWidth: '55px'
                  }}
                >
                  <option value="">شفت</option>
                  {SHIFT_TYPES.map(st => (
                    <option key={st} value={st}>{st}</option>
                  ))}
                </select>
                {isExtra && (
                  <>
                    <span style={{ background: '#fbbf24', color: '#78350f', fontSize: '0.65rem', padding: '1px 6px', borderRadius: '6px', fontWeight: 700 }}>إضافي</span>
                    <button onClick={(e) => { e.preventDefault(); removeExtraStudent(student.id); }} style={{
                      background: 'none', border: 'none', color: '#ef4444', cursor: 'pointer', fontSize: '1.1rem', padding: '0 4px', fontWeight: 800, lineHeight: 1
                    }}>×</button>
                  </>
                )}
              </label>
            );
          })}
        </div>

        {/* Add from global list */}
        <div style={{
          marginTop: '15px',
          paddingTop: '15px',
          borderTop: '2px dashed #e5e7eb'
        }}>
          <label style={{ fontSize: '0.9rem', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px', color: config.color }}>
            <span style={{ fontSize: '1.2rem' }}>➕</span>
            إضافة طبيب من قسم آخر
          </label>
          <div style={{ display: 'flex', gap: '8px' }}>
            <div style={{ flex: 1, position: 'relative' }}>
              <input
                list="global-students-list"
                value={addSearchTerm}
                onChange={e => {
                  setAddSearchTerm(e.target.value);
                  const entry = allGlobalStudents.find(s => s.name === e.target.value);
                  if (entry) {
                    addGlobalStudent(entry);
                  }
                }}
                placeholder="ابحث عن اسم من أي قسم..."
                style={{
                  width: '100%',
                  padding: '12px 15px',
                  borderRadius: '12px',
                  border: `2px solid ${config.color}40`,
                  fontSize: '0.95rem',
                  fontFamily: 'inherit',
                  outline: 'none'
                }}
              />
              <datalist id="global-students-list">
                {allGlobalStudents
                  .filter(g => !students.some(s => s.name === g.name))
                  .map((g, i) => (
                    <option key={i} value={g.name}>{g.dept}</option>
                  ))}
              </datalist>
            </div>
          </div>
          {addedExtraIds.size > 0 && (
            <p style={{ marginTop: '8px', fontSize: '0.8rem', color: '#888' }}>
              ℹ️ تم إضافة {addedExtraIds.size} طبيب إضافي من أقسام أخرى
            </p>
          )}
        </div>
      </div>

      {/* Generate Button */}
      <div style={{ textAlign: 'center', marginBottom: '40px' }}>
        <button
          onClick={handleGenerate}
          disabled={isGenerating || selectedStudents.size === 0}
          style={{
            background: isGenerating ? '#ccc' : `linear-gradient(135deg, ${config.color} 0%, ${config.color}cc 100%)`,
            color: 'white',
            border: 'none',
            padding: '20px 60px',
            fontSize: '1.3rem',
            fontWeight: '700',
            borderRadius: '16px',
            cursor: isGenerating ? 'not-allowed' : 'pointer',
            boxShadow: isGenerating ? 'none' : `0 15px 40px ${config.color}66`,
            transition: 'all 0.3s',
            display: 'inline-flex',
            alignItems: 'center',
            gap: '15px'
          }}
        >
          {isGenerating ? (
            <>
              <div style={{
                width: '24px',
                height: '24px',
                border: '3px solid rgba(255,255,255,0.3)',
                borderTop: '3px solid white',
                borderRadius: '50%',
                animation: 'spin 1s linear infinite'
              }} />
              جاري الإنشاء...
            </>
          ) : (
            <>
              <span style={{ fontSize: '1.5rem' }}>🪄</span>
              {existingSchedule?.exists ? 'إنشاء جدول جديد' : 'إنشاء الجدول تلقائياً'}
            </>
          )}
        </button>
        
        <p style={{ marginTop: '15px', color: 'var(--text-light)', fontSize: '0.95rem' }}>
          {selectedStudents.size === 0 ? 
            '⚠️ يرجى اختيار طبيب واحد على الأقل' :
            `سيتم إنشاء جدول لـ ${selectedStudents.size} طبيب`
          }
        </p>
        
        {existingSchedule?.exists && (
          <p style={{ marginTop: '10px', color: '#e74c3c', fontSize: '0.85rem' }}>
            ⚠️ إنشاء جدول جديد سيستبدل الجدول المحفوظ الحالي
          </p>
        )}
      </div>

      {/* Toast */}
      <div style={{
        position: 'fixed',
        bottom: '30px',
        left: '50%',
        transform: `translateX(-50%) translateY(${showToast ? '0' : '100px'})`,
        background: `linear-gradient(135deg, ${config.color}, ${config.color}cc)`,
        color: 'white',
        padding: '15px 30px',
        borderRadius: '12px',
        fontWeight: '600',
        boxShadow: `0 10px 40px ${config.color}66`,
        opacity: showToast ? 1 : 0,
        transition: 'all 0.3s',
        zIndex: 1000
      }}>
        {toastMessage}
      </div>

      <style jsx global>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}
