"use client";

import { useState, useEffect, useMemo, useCallback, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import * as XLSX from 'xlsx';
import {
  Student,
  Section,
  DayOfWeek,
  GeneratedSchedule,
  DAY_NAMES_AR,
  Department,
  getDepartmentSections,
  getDepartmentSectionNames,
  getDepartmentSectionColors,
  getDepartmentFemaleRestricted
} from "@/lib/types";
import { updateScheduleAssignment } from "@/lib/scheduleGenerator";
import { getSchedule, saveSchedule } from "@/lib/scheduleStorage";

// Friday comes FIRST - students who work Friday get the next week off
const dayOrder: DayOfWeek[] = ['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'];

const departmentConfigs: { [key in Department]: { name: string; icon: string; color: string } } = {
  'pediatrics': { name: 'قسم الأطفال', icon: '👶', color: '#3498db' },
  'surgery': { name: 'قسم الجراحة', icon: '🏥', color: '#e74c3c' },
  'gynecology': { name: 'قسم النسائية', icon: '👩‍⚕️', color: '#9b59b6' },
};

function ScheduleEditorContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const department = (searchParams.get('dept') || 'pediatrics') as Department;
  
  const config = (departmentConfigs as any)[department] || { name: `قسم ${department}`, icon: '📋', color: '#4F46E5' };
  
  const [schedule, setSchedule] = useState<GeneratedSchedule | null>(null);
  const [loading, setLoading] = useState(true);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [editingCell, setEditingCell] = useState<{ weekIndex: number; day: DayOfWeek; studentId: string } | null>(null);
  const [selectedWeeks, setSelectedWeeks] = useState<number[]>([0, 1, 2, 3]);
  const [lastSaved, setLastSaved] = useState<string>("");

  const allSections = useMemo(() => getDepartmentSections(department), [department]);
  const SECTION_NAMES = useMemo(() => getDepartmentSectionNames(department), [department]);
  const SECTION_COLORS = useMemo(() => getDepartmentSectionColors(department), [department]);
  const femaleRestrictedSections = useMemo(() => getDepartmentFemaleRestricted(department), [department]);

  useEffect(() => {
    const savedSchedule = getSchedule(department);
    if (savedSchedule) {
      setSchedule(savedSchedule);
      const weeksToShow = Math.min(4, savedSchedule.weeks.length);
      setSelectedWeeks(Array.from({ length: weeksToShow }, (_, i) => i));
    }
    setLoading(false);
  }, [department]);

  const autoSave = useCallback((updatedSchedule: GeneratedSchedule) => {
    saveSchedule(department, updatedSchedule);
    setLastSaved(new Date().toLocaleTimeString('ar-EG'));
  }, [department]);

  const showNotification = (message: string) => {
    setToastMessage(message);
    setShowToast(true);
    setTimeout(() => setShowToast(false), 2000);
  };

  // Helper to calculate actual date for each day in a week
  const getDayDate = (weekStartDate: string, day: DayOfWeek): string => {
    // Parse DD/MM/YYYY format
    const [d, m, y] = weekStartDate.split('/').map(Number);
    const weekStart = new Date(y, m - 1, d);
    
    // Day offsets from Saturday (week start)
    const dayOffsets: { [key in DayOfWeek]: number } = {
      'Friday': 6,
      'Saturday': 0,
      'Sunday': 1,
      'Monday': 2,
      'Tuesday': 3,
      'Wednesday': 4,
      'Thursday': 5
    };
    
    const date = new Date(weekStart);
    date.setDate(date.getDate() + dayOffsets[day]);
    
    return `${date.getDate()}/${date.getMonth() + 1}`;
  };

  const handleSectionEdit = (weekIndex: number, day: DayOfWeek, studentId: string, newSection: Section) => {
    if (!schedule) return;
    
    const student = schedule.config.students.find(s => s.id === studentId);
    const studentName = student?.name || '';
    
    const updatedSchedule = updateScheduleAssignment(schedule, weekIndex, day, studentId, newSection, studentName);
    setSchedule(updatedSchedule);
    autoSave(updatedSchedule);
    setEditingCell(null);
    showNotification("✓ تم الحفظ تلقائياً");
  };

  const exportToExcel = () => {
    if (!schedule) return;
    
    const data: any[][] = [];
    data.push([`برنامج الامتياز - ${config.name}`, '', '', '', '', '', '', '']);
    data.push(['']);
    
    schedule.weeks.forEach(week => {
      data.push([`الأسبوع ${week.weekNumber}: ${week.startDate} - ${week.endDate}`]);
      const dayHeaders = ['الطبيب', ...dayOrder.map(d => DAY_NAMES_AR[d])];
      data.push(dayHeaders);
      
      schedule.config.students.forEach(student => {
        const row = [student.name];
        dayOrder.forEach(day => {
          const assignment = (week.days[day] || []).find(a => a.studentId === student.id);
          row.push(assignment ? assignment.section : 'OUT');
        });
        data.push(row);
      });
      
      data.push(['']);
    });
    
    const ws = XLSX.utils.aoa_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Schedule");
    XLSX.writeFile(wb, `schedule_${department}_${new Date().toISOString().split('T')[0]}.xlsx`);
    showNotification("تم تصدير الجدول! 📊");
  };

  const toggleWeekSelection = (weekIndex: number) => {
    if (selectedWeeks.includes(weekIndex)) {
      if (selectedWeeks.length > 1) {
        setSelectedWeeks(selectedWeeks.filter(w => w !== weekIndex));
      }
    } else {
      setSelectedWeeks([...selectedWeeks, weekIndex].sort((a, b) => a - b));
    }
  };

  const selectAllWeeks = () => {
    if (!schedule) return;
    setSelectedWeeks(Array.from({ length: schedule.weeks.length }, (_, i) => i));
  };

  if (loading) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#f8f9fa'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            width: '60px',
            height: '60px',
            border: `4px solid ${config.color}30`,
            borderTop: `4px solid ${config.color}`,
            borderRadius: '50%',
            animation: 'spin 1s linear infinite',
            margin: '0 auto 20px'
          }} />
          <p style={{ color: '#666' }}>جاري التحميل...</p>
        </div>
      </div>
    );
  }

  if (!schedule) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#f8f9fa',
        padding: '20px'
      }}>
        <div style={{
          background: 'white',
          borderRadius: '24px',
          padding: '60px',
          textAlign: 'center',
          boxShadow: '0 20px 60px rgba(0,0,0,0.1)',
          maxWidth: '500px'
        }}>
          <div style={{ fontSize: '5rem', marginBottom: '20px' }}>📋</div>
          <h2 style={{ color: '#333', marginBottom: '15px' }}>لا يوجد جدول محفوظ</h2>
          <p style={{ color: '#666', marginBottom: '30px' }}>
            يرجى إنشاء جدول جديد من صفحة القسم
          </p>
          <Link
            href={`/schedule/${department}`}
            style={{
              display: 'inline-block',
              background: `linear-gradient(135deg, ${config.color}, ${config.color}cc)`,
              color: 'white',
              padding: '15px 40px',
              borderRadius: '12px',
              textDecoration: 'none',
              fontWeight: '700',
              fontSize: '1.1rem'
            }}
          >
            إنشاء جدول جديد →
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: '#f8f9fa', padding: '15px' }}>
      {/* Header */}
      <div style={{
        background: 'white',
        borderRadius: '16px',
        padding: '15px 25px',
        marginBottom: '15px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.06)',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexWrap: 'wrap',
        gap: '15px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
          <Link
            href={`/schedule/${department}`}
            style={{
              background: '#f1f3f4',
              padding: '10px 15px',
              borderRadius: '10px',
              color: '#666',
              textDecoration: 'none',
              fontWeight: '600',
              fontSize: '0.9rem'
            }}
          >
            ← رجوع
          </Link>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <span style={{ fontSize: '2rem' }}>{config.icon}</span>
            <div>
              <h1 style={{ fontSize: '1.3rem', fontWeight: '700', color: config.color, margin: 0 }}>
                محرر جدول {config.name}
              </h1>
              <div style={{ fontSize: '0.8rem', color: '#888' }}>
                {schedule.weeks.length} أسبوع • {schedule.config.students.length} طبيب
                {lastSaved && <span style={{ marginRight: '10px' }}>• آخر حفظ: {lastSaved}</span>}
              </div>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          <button onClick={selectAllWeeks} style={{ background: '#6c757d', color: 'white', border: 'none', padding: '10px 20px', borderRadius: '10px', cursor: 'pointer', fontWeight: '600', fontSize: '0.9rem' }}>
            عرض الكل 📋
          </button>
          <button onClick={exportToExcel} style={{ background: '#27ae60', color: 'white', border: 'none', padding: '10px 20px', borderRadius: '10px', cursor: 'pointer', fontWeight: '600', fontSize: '0.9rem' }}>
            Excel 📊
          </button>
          <button onClick={() => window.print()} style={{ background: config.color, color: 'white', border: 'none', padding: '10px 20px', borderRadius: '10px', cursor: 'pointer', fontWeight: '600', fontSize: '0.9rem' }}>
            طباعة 🖨️
          </button>
        </div>
      </div>

      {/* Week Selector */}
      <div style={{ background: 'white', borderRadius: '16px', padding: '15px 20px', marginBottom: '15px', boxShadow: '0 4px 20px rgba(0,0,0,0.06)', overflowX: 'auto' }}>
        <div style={{ display: 'flex', gap: '8px', alignItems: 'center', minWidth: 'max-content' }}>
          <span style={{ fontWeight: '600', color: '#666', marginLeft: '10px' }}>الأسابيع:</span>
          {schedule.weeks.map((week, index) => (
            <button
              key={index}
              onClick={() => toggleWeekSelection(index)}
              style={{
                background: selectedWeeks.includes(index) ? `linear-gradient(135deg, ${config.color}, ${config.color}cc)` : '#f1f3f4',
                color: selectedWeeks.includes(index) ? 'white' : '#666',
                border: 'none',
                padding: '8px 16px',
                borderRadius: '20px',
                cursor: 'pointer',
                fontWeight: '600',
                fontSize: '0.85rem'
              }}
            >
              أسبوع {week.weekNumber}
            </button>
          ))}
        </div>
      </div>

      {/* Schedule Tables */}
      <div style={{ display: 'grid', gap: '20px', gridTemplateColumns: selectedWeeks.length === 1 ? '1fr' : 'repeat(auto-fit, minmax(800px, 1fr))' }}>
        {selectedWeeks.map(weekIndex => {
          const week = schedule.weeks[weekIndex];
          if (!week) return null;
          
          return (
            <div key={weekIndex} style={{ background: 'white', borderRadius: '16px', padding: '20px', boxShadow: '0 4px 20px rgba(0,0,0,0.06)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '15px', paddingBottom: '10px', borderBottom: `2px solid ${config.color}20` }}>
                <h3 style={{ margin: 0, color: config.color, fontWeight: '700', fontSize: '1.1rem' }}>الأسبوع {week.weekNumber}</h3>
                <span style={{ color: '#888', fontSize: '0.9rem' }}>{week.startDate} → {week.endDate}</span>
              </div>

              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: '3px', fontSize: '0.85rem' }}>
                  <thead>
                    <tr>
                      <th style={{ padding: '10px 12px', background: `linear-gradient(135deg, ${config.color}, ${config.color}cc)`, color: 'white', borderRadius: '8px', fontWeight: '700', textAlign: 'right', minWidth: '140px' }}>الطبيب</th>
                      {dayOrder.map(day => (
                        <th key={day} style={{ padding: '8px 6px', background: day === 'Friday' ? 'linear-gradient(135deg, #f39c12, #e67e22)' : `linear-gradient(135deg, ${config.color}, ${config.color}cc)`, color: 'white', borderRadius: '8px', fontWeight: '700', minWidth: '80px', textAlign: 'center' }}>
                          <div>{DAY_NAMES_AR[day]}</div>
                          <div style={{ fontSize: '0.7rem', opacity: 0.9, marginTop: '2px' }}>{getDayDate(week.startDate, day)}</div>
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {schedule.config.students.map(student => (
                      <tr key={student.id}>
                        <td style={{ padding: '8px 12px', background: '#f8f9fa', borderRadius: '8px', fontWeight: '600', fontSize: '0.8rem' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                            <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: student.gender === 'M' ? '#3498db' : '#e91e63', flexShrink: 0 }} />
                            <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '130px' }}>{student.name}</span>
                          </div>
                        </td>
                        {dayOrder.map(day => {
                          const assignment = (week.days[day] || []).find(a => a.studentId === student.id);
                          const section = assignment?.section || 'OUT';
                          const isEditing = editingCell?.weekIndex === weekIndex && editingCell?.day === day && editingCell?.studentId === student.id;
                          
                          return (
                            <td key={day} onClick={() => setEditingCell({ weekIndex, day, studentId: student.id })} style={{ padding: '8px', background: SECTION_COLORS[section]?.bg || '#ecf0f1', color: SECTION_COLORS[section]?.text || '#7f8c8d', borderRadius: '8px', textAlign: 'center', fontWeight: '600', cursor: 'pointer', fontSize: '0.75rem', border: day === 'Friday' && assignment ? '2px dashed gold' : 'none' }}>
                              {isEditing ? (
                                <select autoFocus value={section} onChange={(e) => handleSectionEdit(weekIndex, day, student.id, e.target.value)} onBlur={() => setEditingCell(null)} onClick={(e) => e.stopPropagation()} style={{ padding: '6px', borderRadius: '6px', border: `2px solid ${config.color}`, fontWeight: '700', cursor: 'pointer', width: '100%', background: 'white', color: '#333', fontSize: '0.75rem', outline: 'none' }}>
                                  {allSections.filter(s => !(student.gender === 'F' && femaleRestrictedSections.includes(s))).map(s => (<option key={s} value={s}>{SECTION_NAMES[s] || s}</option>))}
                                </select>
                              ) : (<div title={SECTION_NAMES[section] || section}>{SECTION_NAMES[section] || section}</div>)}
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          );
        })}
      </div>

      {/* Legend */}
      <div style={{ background: 'white', borderRadius: '16px', padding: '15px 20px', marginTop: '15px', boxShadow: '0 4px 20px rgba(0,0,0,0.06)' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', alignItems: 'center' }}>
          <span style={{ fontWeight: '600', color: '#666' }}>الألوان:</span>
          {['CLINIC_A', 'PICU_A', 'NICU_A', 'OR_A', 'ER_A', 'WARD_A', 'DEL_A', 'OUT'].map(section => {
            const color = SECTION_COLORS[section];
            const name = section.replace('_A', '').replace('DEL', 'Delivery');
            if (!color) return null;
            return (<div key={section} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}><div style={{ width: '20px', height: '20px', background: color.bg, borderRadius: '5px' }} /><span style={{ fontSize: '0.8rem', color: '#666' }}>{name}</span></div>);
          })}
        </div>
      </div>

      {/* Toast */}
      <div style={{ position: 'fixed', bottom: '20px', left: '50%', transform: `translateX(-50%) translateY(${showToast ? '0' : '100px'})`, background: '#27ae60', color: 'white', padding: '12px 25px', borderRadius: '10px', fontWeight: '600', boxShadow: '0 8px 30px rgba(39, 174, 96, 0.4)', opacity: showToast ? 1 : 0, transition: 'all 0.3s', zIndex: 1000, fontSize: '0.9rem' }}>{toastMessage}</div>

      <style jsx global>{`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

// Loading fallback
function EditorLoading() {
  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8f9fa' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ width: '60px', height: '60px', border: '4px solid #3498db30', borderTop: '4px solid #3498db', borderRadius: '50%', animation: 'spin 1s linear infinite', margin: '0 auto 20px' }} />
        <p style={{ color: '#666' }}>جاري التحميل...</p>
        <style jsx>{`@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }`}</style>
      </div>
    </div>
  );
}

export default function ScheduleEditorPage() {
  return (
    <Suspense fallback={<EditorLoading />}>
      <ScheduleEditorContent />
    </Suspense>
  );
}
