'use client';

import { useState, useEffect } from 'react';

interface Student {
  name: string;
  phone?: string;
  university?: string;
  startDate?: string;
  endDate?: string;
  globalEndDate?: string;
  department?: string;
  deptLabel?: string;
  [key: string]: any;
}

// Department display names
const DEPT_NAMES: Record<string, string> = {
  'جراحة': 'الجراحة العامة',
  'نسائية': 'النسائية والتوليد',
  'الاطفال': 'طب الأطفال',
  'المغادرين': 'خريج',
  'الاستئناف': 'استئناف',
};

// Map dept to default ID card title
const DEPT_TITLES: Record<string, string> = {
  'جراحة': 'طبيب امتياز',
  'نسائية': 'طبيب امتياز',
  'الاطفال': 'طبيب امتياز',
  'التمريض': 'ممرض/ة',
  'تمريض تدريب': 'متدرب/ة تمريض',
  'تمريض امتياز': 'طالب/ة امتياز تمريض',
  'العلاج الطبيعي': 'معالج/ة طبيعي/ة',
  'العلاج الوظيفي': 'معالج/ة وظيفي/ة',
  'المطبخ': 'موظف مطبخ',
  'إدارة': 'موظف إداري',
  'المحاسبة': 'محاسب',
  'طب تطوع': 'طبيب متطوع',
  'تمريض تطوع': 'ممرض/ة متطوع/ة',
  'تغذية': 'أخصائي/ة تغذية',
  'أشعة': 'تقني/ة أشعة',
  'خدمة اجتماعية': 'أخصائي/ة اجتماعي/ة',
  'ضباط الإسعاف': 'ضابط إسعاف',
  'العمل المجتمعي': 'متطوع/ة مجتمعي/ة',
};

export default function CardPage() {
  const [allStudents, setAllStudents] = useState<{ name: string; dept: string; student: Student }[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      let data: any = null;
      try {
        const res = await fetch('/api/students');
        if (res.ok) data = await res.json();
      } catch {}
      if (!data) {
        try { data = JSON.parse(localStorage.getItem('studentsData') || '{}'); } catch {}
      }
      if (data) {
        const list: { name: string; dept: string; student: Student }[] = [];
        const seen = new Set<string>();
        for (const dept of Object.keys(data)) {
          for (const s of (data[dept] || [])) {
            if (!seen.has(s.name)) {
              seen.add(s.name);
              list.push({ name: s.name, dept, student: { ...s, department: dept } });
            }
          }
        }
        setAllStudents(list);
      }
      setIsLoading(false);
    };
    load();
  }, []);

  const printCard = (entry: { name: string; dept: string; student: Student }) => {
    const s = entry.student;
    const dept = DEPT_NAMES[entry.dept] || entry.dept;
    const endDate = s.endDate || s.globalEndDate || '';
    const title = s.internshipYear || DEPT_TITLES[entry.dept] || entry.dept || 'متدرب/ة';
    const autoTrainer = (
      s.assignedTrainer ||
      s.assigned_trainer ||
      s.supervisorName ||
      (entry.dept.includes('أشعة') ? 'ضياء الدين هيموني' :
       entry.dept.includes('مختبر') ? 'مشرف قسم المختبرات الطبية' :
       entry.dept.includes('علاج طبيعي') ? 'مشرف قسم العلاج الطبيعي' :
       entry.dept.includes('تغذية') ? 'مشرف قسم التغذية السريرية' :
       entry.dept.includes('صيدل') ? 'مشرف قسم الصيدلة السريرية' :
       entry.dept.includes('تمريض') ? 'مشرف قسم التمريض السريري' : '')
    );

    const cardHtml = `
      <div style="
        width: 85mm; height: 54mm;
        border: 1px solid #ccc;
        border-radius: 6px;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        font-family: 'Tajawal', sans-serif;
        position: relative;
        background: white;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      ">
        <!-- HEADER -->
        <div style="display:flex; align-items:center; justify-content:space-between; padding:5px 8px; border-bottom:2px solid #CE1126;">
          <!-- Arabic text -->
          <div style="text-align:right; flex:1; direction:rtl;">
            <div style="font-size:8px; font-weight:800; color:#CE1126; line-height:1.5;">جمعية الهلال الأحمر الفلسطيني - الخليل</div>
            <div style="font-size:7.5px; font-weight:700; color:#333; line-height:1.4;">مستشفى الهلال الأحمر التخصصي - الخليل</div>
          </div>
          <!-- Logo -->
          <div style="margin:0 6px; flex-shrink:0;">
            <div style="
              width:36px; height:36px; border-radius:50%;
              border:2px solid #CE1126;
              display:flex; align-items:center; justify-content:center;
              overflow:hidden;
            ">
              <img src="/prcs-logo.png" style="width:32px;height:32px;object-fit:contain;" alt="" />
            </div>
          </div>
          <!-- English text -->
          <div style="text-align:left; flex:1;">
            <div style="font-size:6.5px; font-weight:700; color:#CE1126; line-height:1.5;">Palestine Red Crescent Society- Hebron</div>
            <div style="font-size:6px; font-weight:600; color:#555; line-height:1.4;">Red Crescent Specilized Hospital - Hebron</div>
          </div>
        </div>

        <!-- BODY -->
        <div style="flex:1; padding:5px 10px; direction:rtl; display:flex; flex-direction:column; justify-content:center; gap:6px;">
          <div style="display:flex; align-items:center; border-bottom:1px dotted #aaa; padding-bottom:3px;">
            <span style="font-size:8.5px; font-weight:800; white-space:nowrap; min-width:60px; color:#222;">الاسم :</span>
            <span style="flex:1; font-size:9px; font-weight:700; color:#CE1126;" contenteditable="true">${s.name || ''}</span>
          </div>
          <div style="display:flex; align-items:center; border-bottom:1px dotted #aaa; padding-bottom:3px;">
            <span style="font-size:8.5px; font-weight:800; white-space:nowrap; min-width:60px; color:#222;">المسمى:</span>
            <span style="flex:1; font-size:9px; color:#333;" contenteditable="true">${title}</span>
          </div>
          <div style="display:flex; align-items:center; border-bottom:1px dotted #aaa; padding-bottom:3px;">
            <span style="font-size:8.5px; font-weight:800; white-space:nowrap; min-width:72px; color:#222;">القسم :</span>
            <span style="flex:1; font-size:9px; color:#333; background:#eff6ff; padding:1px 4px; border-radius:3px;" contenteditable="true" title="القسم - انقر للتعديل">${dept}</span>
          </div>
          ${autoTrainer ? `
          <div style="display:flex; align-items:center; border-bottom:1px dotted #aaa; padding-bottom:3px;">
            <span style="font-size:8.5px; font-weight:800; white-space:nowrap; min-width:72px; color:#222;">المدرب المشرف:</span>
            <span style="flex:1; font-size:9.5px; font-weight:800; color:#0284c7;" contenteditable="true">${autoTrainer}</span>
          </div>` : ''}
          <div style="display:flex; align-items:center;">
            <div style="flex:1; display:flex; align-items:center;">
              <span style="font-size:8.5px; font-weight:800; white-space:nowrap; min-width:72px; color:#222;">تاريخ الإنتهاء :</span>
              <span style="font-size:9px; color:#333;" contenteditable="true">${endDate}</span>
            </div>
          </div>
          <div style="padding:2px 12px 9px;display:flex;justify-content:flex-start;align-items:center;direction:ltr;">
            <div style="text-align:center;line-height:1.25;direction:rtl;">
              <div style="font-size:7px;font-weight:800;color:#0f172a;">مديرة وحدة التطوير والتدريب</div>
              <div style="font-size:6.5px;font-weight:800;color:#CE1126;">أ. نسرين عابدين</div>
            </div>
          </div>
        </div>

        <!-- FOOTER decoration -->
        <div style="
          height:10px;
          background: linear-gradient(to bottom, #CE1126, #8B0000);
          border-radius: 0 0 0 0;
          position:relative;
          overflow:hidden;
        ">
          <div style="
            position:absolute; bottom:-4px; left:50%; transform:translateX(-50%);
            width:70%; height:14px;
            background:white;
            border-radius:50%;
          "></div>
        </div>
      </div>
    `;

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`
      <html dir="rtl">
      <head>
        <title>بطاقة - ${s.name}</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700;800&display=swap');
          * { margin:0; padding:0; box-sizing:border-box; }
          @page { size: 85mm 54mm; margin:0; }
          body {
            width: 85mm; height: 54mm;
            display: flex; align-items:center; justify-content:center;
            background: white;
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
          }
        </style>
      </head>
      <body>
        ${cardHtml}
      </body>
      </html>
    `);
    printWindow.document.close();
    setTimeout(() => { printWindow.focus(); printWindow.print(); printWindow.close(); }, 800);
  };

  // Print all cards on A4 (6 per page, 2 columns x 3 rows)
  const printAllCards = () => {
    const cards = allStudents.map(entry => {
      const s = entry.student;
      const dept = DEPT_NAMES[entry.dept] || entry.dept;
      const endDate = s.globalEndDate || s.endDate || '';
      return `
        <div class="card">
          <div class="card-header">
            <div class="ar-text">
              <div class="ar-main">جمعية الهلال الأحمر الفلسطيني - الخليل</div>
              <div class="ar-sub">مستشفى الهلال الأحمر التخصصي - الخليل</div>
            </div>
            <div class="logo-wrap">
              <img src="${window.location.origin}/prcs-logo.png" class="logo" alt="" />
            </div>
            <div class="en-text">
              <div class="en-main">Palestine Red Crescent Society- Hebron</div>
              <div class="en-sub">Red Crescent Specilized Hospital - Hebron</div>
            </div>
          </div>
          <div class="card-body">
            <div class="field"><span class="label">الاسم :</span><span class="value red">${s.name}</span></div>
            <div class="field"><span class="label">المسمى:</span><span class="value">طبيب امتياز</span></div>
            <div class="field"><span class="label">القسم :</span><span class="value">${dept}</span></div>
            <div class="field-row">
              <div style="flex:1;display:flex;align-items:center"><span class="label">تاريخ الإنتهاء :</span><span class="value">${endDate}</span></div>
              <span style="font-size:8px;color:#666;font-weight:700;margin-right:6px;">التوقيع</span>
            </div>
          </div>
          <div class="card-footer">
            <div class="footer-curve"></div>
          </div>
        </div>
      `;
    }).join('');

    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    printWindow.document.write(`
      <html dir="rtl">
      <head>
        <title>بطاقات المتدربين</title>
        <style>
          @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700;800&display=swap');
          * { margin:0; padding:0; box-sizing:border-box; }
          @page { size: A4; margin: 8mm; }
          body { font-family:'Tajawal',sans-serif; print-color-adjust:exact; -webkit-print-color-adjust:exact; }
          .grid { display:grid; grid-template-columns:1fr 1fr; gap:6mm; }
          .card { width:85mm; height:54mm; border:1px solid #ccc; border-radius:6px; overflow:hidden; display:flex; flex-direction:column; background:white; }
          .card-header { display:flex; align-items:center; justify-content:space-between; padding:5px 8px; border-bottom:2px solid #CE1126; }
          .ar-text { text-align:right; flex:1; direction:rtl; }
          .ar-main { font-size:7.5px; font-weight:800; color:#CE1126; line-height:1.5; }
          .ar-sub  { font-size:7px;   font-weight:700; color:#333;    line-height:1.4; }
          .logo-wrap { margin:0 5px; flex-shrink:0; width:34px; height:34px; border-radius:50%; border:2px solid #CE1126; overflow:hidden; display:flex; align-items:center; justify-content:center; }
          .logo { width:30px; height:30px; object-fit:contain; }
          .en-text { text-align:left; flex:1; }
          .en-main { font-size:6px; font-weight:700; color:#CE1126; line-height:1.5; }
          .en-sub  { font-size:5.5px; font-weight:600; color:#555;    line-height:1.4; }
          .card-body { flex:1; padding:5px 10px; direction:rtl; display:flex; flex-direction:column; justify-content:center; gap:5px; }
          .field { display:flex; align-items:center; border-bottom:1px dotted #aaa; padding-bottom:3px; }
          .field-row { display:flex; align-items:center; }
          .label { font-size:8px; font-weight:800; white-space:nowrap; min-width:65px; color:#222; }
          .value { font-size:8.5px; color:#333; flex:1; }
          .value.red { color:#CE1126; font-weight:700; font-size:9px; }
          .card-footer { height:10px; background:linear-gradient(to bottom,#CE1126,#8B0000); position:relative; overflow:hidden; }
          .footer-curve { position:absolute; bottom:-4px; left:50%; transform:translateX(-50%); width:70%; height:14px; background:white; border-radius:50%; }
        </style>
      </head>
      <body>
        <div class="grid">${cards}</div>
      </body>
      </html>
    `);
    printWindow.document.close();
    setTimeout(() => { printWindow.focus(); printWindow.print(); printWindow.close(); }, 1000);
  };

  if (isLoading) {
    return (
      <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', padding: '40px', textAlign: 'center' }}>
        <p>جاري تحميل البيانات...</p>
      </div>
    );
  }

  return (
    <div dir="rtl" style={{ fontFamily: 'Tajawal, sans-serif', background: '#f8f9fa', minHeight: '100vh', padding: '20px' }}>
      {/* Back */}
      <div style={{ maxWidth: '1000px', margin: '0 auto 20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '10px', marginBottom: '15px' }}>
        <a href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', color: '#8B1A2B', fontWeight: 700, textDecoration: 'none' }}>
          <i className="fas fa-arrow-right"></i> رجوع للوحة التحكم
        </a>
        <a href="/idcard" style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', background: '#059669', color: 'white', padding: '8px 16px', borderRadius: '10px', fontWeight: 700, textDecoration: 'none', fontSize: '0.9rem' }}>
          <i className="fas fa-id-badge"></i> الانتقال إلى محرر البطاقات المتقدم
        </a>
      </div>
      

      <div style={{ maxWidth: '1000px', margin: '0 auto' }}>
        {/* Header */}
        <div style={{ background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)', borderRadius: '16px', padding: '30px', color: 'white', marginBottom: '24px', textAlign: 'center' }}>
          <i className="fas fa-id-card" style={{ fontSize: '2.5rem', marginBottom: '12px', display: 'block' }}></i>
          <h1 style={{ fontSize: '1.8rem', fontWeight: 800, marginBottom: '8px' }}>بطاقات المتدربين</h1>
          <p style={{ opacity: 0.8 }}>طباعة بطاقات الهوية للمتدربين في مستشفى الهلال الأحمر التخصصي</p>
          <button
            onClick={printAllCards}
            style={{
              marginTop: '16px', padding: '12px 30px', borderRadius: '12px', border: '2px solid white',
              background: 'rgba(255,255,255,0.15)', color: 'white', fontFamily: 'Tajawal', fontWeight: 700,
              fontSize: '1rem', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: '8px'
            }}
          >
            <i className="fas fa-print"></i> طباعة جميع البطاقات (A4)
          </button>
        </div>

        {/* Grid Preview */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '20px' }}>
          {allStudents.map((entry, i) => {
            const dept = DEPT_NAMES[entry.dept] || entry.dept;
            const endDate = entry.student.globalEndDate || entry.student.endDate || '—';
            return (
              <div key={i} style={{
                background: 'white', borderRadius: '10px', overflow: 'hidden',
                boxShadow: '0 4px 16px rgba(0,0,0,0.08)', border: '1px solid #e5e7eb'
              }}>
                {/* Card Header Preview */}
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', borderBottom: '2px solid #CE1126' }}>
                  <div style={{ textAlign: 'right', flex: 1 }}>
                    <div style={{ fontSize: '8px', fontWeight: 800, color: '#CE1126', lineHeight: 1.5 }}>جمعية الهلال الأحمر الفلسطيني - الخليل</div>
                    <div style={{ fontSize: '7px', fontWeight: 700, color: '#333', lineHeight: 1.4 }}>مستشفى الهلال الأحمر التخصصي - الخليل</div>
                  </div>
                  <div style={{ margin: '0 8px', width: 38, height: 38, borderRadius: '50%', border: '2px solid #CE1126', overflow: 'hidden', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <img src="/prcs-logo.png" style={{ width: 32, height: 32, objectFit: 'contain' }} alt="" />
                  </div>
                  <div style={{ textAlign: 'left', flex: 1 }}>
                    <div style={{ fontSize: '6.5px', fontWeight: 700, color: '#CE1126', lineHeight: 1.5 }}>Palestine Red Crescent Society- Hebron</div>
                    <div style={{ fontSize: '6px', color: '#555', lineHeight: 1.4 }}>Red Crescent Specilized Hospital - Hebron</div>
                  </div>
                </div>

                {/* Card Body Preview */}
                <div style={{ padding: '10px 14px', direction: 'rtl', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                  {[
                    { label: 'الاسم :', value: entry.name, red: true },
                    { label: 'المسمى:', value: entry.student.internshipYear || 'طبيب امتياز', red: false },
                    { label: 'القسم :', value: dept, red: false },
                    { label: 'تاريخ الإنتهاء :', value: endDate, red: false },
                  ].map((field, fi) => (
                    <div key={fi} style={{ display: 'flex', alignItems: 'center', borderBottom: fi < 3 ? '1px dotted #ddd' : 'none', paddingBottom: fi < 3 ? '4px' : 0 }}>
                      <span style={{ fontSize: '9px', fontWeight: 800, color: '#222', whiteSpace: 'nowrap', minWidth: '80px' }}>{field.label}</span>
                      <span style={{ fontSize: '9.5px', fontWeight: field.red ? 700 : 400, color: field.red ? '#CE1126' : '#333', flex: 1 }}>{field.value}</span>
                    </div>
                  ))}
                </div>

                {/* Footer bar */}
                <div style={{ height: 12, background: 'linear-gradient(to bottom, #CE1126, #8B0000)', position: 'relative', overflow: 'hidden' }}>
                  <div style={{ position: 'absolute', bottom: -5, left: '50%', transform: 'translateX(-50%)', width: '60%', height: 16, background: 'white', borderRadius: '50%' }}></div>
                </div>

                {/* Print Button */}
                <div style={{ padding: '10px 14px', borderTop: '1px solid #f0f0f0' }}>
                  <button
                    onClick={() => printCard(entry)}
                    style={{
                      width: '100%', padding: '8px', borderRadius: '8px', border: 'none',
                      background: 'linear-gradient(135deg, #8B1A2B, #6B0F1D)',
                      color: 'white', fontFamily: 'Tajawal', fontWeight: 700, fontSize: '0.85rem',
                      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px'
                    }}
                  >
                    <i className="fas fa-print"></i> طباعة بطاقة {entry.name}
                  </button>
                </div>
              </div>
            );
          })}
        </div>

        {allStudents.length === 0 && (
          <div style={{ textAlign: 'center', padding: '60px', color: '#999' }}>
            <i className="fas fa-id-card" style={{ fontSize: '3rem', marginBottom: '16px', display: 'block' }}></i>
            <p>لا يوجد متدربون حالياً</p>
          </div>
        )}
      </div>
    </div>
  );
}
