/* global React, Icons, AppContext */
const { useState, useContext, useMemo, createElement: h, Fragment } = React;

// ==================== Add Patient Modal ====================
function AddPatientModal({ onClose, onSaved }) {
  const { clinicId, toast } = useContext(AppContext);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({ name: '', age: '', gender: 'ذكر', phone: '', email: '', notes: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name.trim()) { toast('الاسم مطلوب'); return; }
    setSaving(true);
    try {
      const newPatient = await DB.addPatient(clinicId, {
        name: form.name.trim(),
        age: parseInt(form.age) || null,
        gender: form.gender,
        phone: form.phone,
        email: form.email,
        notes: form.notes,
        status: 'active',
      });
      toast('تم إضافة المريض بنجاح ✅');
      onSaved(newPatient);
      onClose();
    } catch(e) {
      console.error(e);
      toast('حدث خطأ أثناء الحفظ');
    } finally { setSaving(false); }
  };

  return h(Fragment, null,
    h('div', { onClick: onClose, style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 } }),
    h('div', {
      style: {
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        background: 'var(--bg-elevated)', borderRadius: 'var(--radius-lg)', padding: 28,
        width: 480, zIndex: 201, boxShadow: 'var(--shadow-lg)',
      },
    },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
        h('div', { style: { fontWeight: 800, fontSize: 18 } }, 'مريض جديد'),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 18 })),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'الاسم الكامل *'),
          h('input', { className: 'input', placeholder: 'محمد أحمد...', value: form.name, onChange: e => set('name', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'العمر'),
          h('input', { className: 'input', type: 'number', placeholder: '30', value: form.age, onChange: e => set('age', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الجنس'),
          h('select', { className: 'select', value: form.gender, onChange: e => set('gender', e.target.value) },
            h('option', { value: 'ذكر' }, 'ذكر'),
            h('option', { value: 'أنثى' }, 'أنثى'),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الهاتف'),
          h('input', { className: 'input', placeholder: '01xxxxxxxxx', value: form.phone, onChange: e => set('phone', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'البريد الإلكتروني'),
          h('input', { className: 'input', type: 'email', placeholder: 'email@...', value: form.email, onChange: e => set('email', e.target.value) }),
        ),
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'ملاحظات'),
          h('textarea', { className: 'textarea', rows: 2, placeholder: 'أي ملاحظات...', value: form.notes, onChange: e => set('notes', e.target.value) }),
        ),
      ),
      h('div', { style: { display: 'flex', gap: 8, marginTop: 20, justifyContent: 'flex-end' } },
        h('button', { className: 'btn outline', onClick: onClose }, 'إلغاء'),
        h('button', { className: 'btn primary', disabled: saving, onClick: handleSave },
          saving ? 'جاري الحفظ...' : 'حفظ المريض',
        ),
      ),
    ),
  );
}

// ==================== Edit Patient Modal ====================
function EditPatientModal({ patient, onClose, onSaved }) {
  const { toast } = useContext(AppContext);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    name: patient.name || '',
    age: patient.age || '',
    gender: patient.gender || 'ذكر',
    phone: patient.phone || '',
    email: patient.email || '',
    notes: patient.notes || '',
    status: patient.status || 'active',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSave = async () => {
    if (!form.name.trim()) { toast('الاسم مطلوب'); return; }
    setSaving(true);
    try {
      const updated = await DB.updatePatient(patient.id, {
        name: form.name.trim(),
        age: parseInt(form.age) || null,
        gender: form.gender,
        phone: form.phone,
        email: form.email,
        notes: form.notes,
        status: form.status,
        avatar: window.initials(form.name.trim()),
      });
      toast('تم تحديث بيانات المريض ✅');
      onSaved(updated);
      onClose();
    } catch(e) {
      console.error(e);
      toast('حدث خطأ أثناء التحديث');
    } finally { setSaving(false); }
  };

  return h(React.Fragment, null,
    h('div', { onClick: onClose, style: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 } }),
    h('div', {
      style: {
        position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
        background: 'var(--bg-elevated)', borderRadius: 'var(--radius-lg)', padding: 28,
        width: 480, zIndex: 201, boxShadow: 'var(--shadow-lg)',
      },
    },
      h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 } },
        h('div', { style: { fontWeight: 800, fontSize: 18 } }, 'تعديل بيانات المريض'),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 18 })),
      ),
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } },
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'الاسم الكامل *'),
          h('input', { className: 'input', value: form.name, onChange: e => set('name', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'العمر'),
          h('input', { className: 'input', type: 'number', value: form.age, onChange: e => set('age', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الجنس'),
          h('select', { className: 'select', value: form.gender, onChange: e => set('gender', e.target.value) },
            h('option', { value: 'ذكر' }, 'ذكر'),
            h('option', { value: 'أنثى' }, 'أنثى'),
          ),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الهاتف'),
          h('input', { className: 'input', value: form.phone, onChange: e => set('phone', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'البريد الإلكتروني'),
          h('input', { className: 'input', type: 'email', value: form.email, onChange: e => set('email', e.target.value) }),
        ),
        h('div', null,
          h('div', { className: 'label' }, 'الحالة'),
          h('select', { className: 'select', value: form.status, onChange: e => set('status', e.target.value) },
            h('option', { value: 'active' }, 'نشط'),
            h('option', { value: 'pending' }, 'معلق'),
            h('option', { value: 'inactive' }, 'غير نشط'),
          ),
        ),
        h('div', { style: { gridColumn: '1/-1' } },
          h('div', { className: 'label' }, 'ملاحظات'),
          h('textarea', { className: 'textarea', rows: 2, value: form.notes, onChange: e => set('notes', e.target.value) }),
        ),
      ),
      h('div', { style: { display: 'flex', gap: 8, marginTop: 20, justifyContent: 'space-between' } },
        h('button', {
          className: 'btn danger',
          disabled: saving,
          onClick: async () => {
            if (!confirm(`هل أنت متأكد من حذف المريض "${patient.name}"؟ لا يمكن التراجع عن هذا الإجراء.`)) return;
            setSaving(true);
            try {
              await DB.deletePatient(patient.id);
              toast('تم حذف المريض ✅');
              onSaved({ _deleted: true, id: patient.id });
              onClose();
            } catch(e) { console.error(e); toast('حدث خطأ أثناء الحذف'); }
            finally { setSaving(false); }
          },
        }, h(Icons.Trash, { size: 14 }), 'حذف المريض'),
        h('div', { className: 'flex gap-8' },
          h('button', { className: 'btn outline', onClick: onClose }, 'إلغاء'),
          h('button', { className: 'btn primary', disabled: saving, onClick: handleSave },
            saving ? 'جاري الحفظ...' : 'حفظ التغييرات',
          ),
        ),
      ),
    ),
  );
}

// ==================== Patients List ====================
function Patients() {
  const { setScreen, patients, setPatients } = useContext(AppContext);
  const [query, setQuery] = useState('');
  const [view, setView] = useState('table');
  const [filter, setFilter] = useState('all');
  const [showAdd, setShowAdd] = useState(false);
  const [editPatient, setEditPatient] = useState(null);
  
  const allPatients = patients && patients.length ? patients : window.PATIENTS;
  const filtered = allPatients.filter(p => {
    if (query && !p.name.includes(query) && !(p.phone||'').includes(query) && !(p.id||'').includes(query)) return false;
    if (filter === 'active' && p.status !== 'active') return false;
    if (filter === 'debt' && (!p.balance || p.balance === 0)) return false;
    return true;
  });

  const handlePatientUpdated = (updated) => {
    if (updated?._deleted) {
      setPatients(prev => prev.filter(p => p.id !== updated.id));
      setEditPatient(null);
    } else {
      setPatients(prev => prev.map(p => p.id === updated.id ? updated : p));
    }
  };

  return h('div', { className: 'fade-in' },
    showAdd ? h(AddPatientModal, {
      onClose: () => setShowAdd(false),
      onSaved: (newP) => setPatients(prev => [newP, ...prev]),
    }) : null,
    editPatient ? h(EditPatientModal, {
      patient: editPatient,
      onClose: () => setEditPatient(null),
      onSaved: handlePatientUpdated,
    }) : null,
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'المرضى'),
        h('div', { className: 'page-subtitle' }, `${allPatients.length} مريض · ${allPatients.filter(p=>p.status==='active').length} نشط`),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline' }, h(Icons.Download, { size: 16 }), 'تصدير'),
        h('button', { className: 'btn primary', onClick: () => setShowAdd(true) }, h(Icons.UserPlus, { size: 16 }), 'مريض جديد'),
      ),
    ),
    h('div', { className: 'page-content' },
      h('div', { className: 'card p-16 mb-16' },
        h('div', { className: 'flex gap-12 ai-c wrap' },
          h('div', { style: { flex: 1, position: 'relative', minWidth: 240 } },
            h('input', { className: 'input', placeholder: 'ابحث بالاسم، الهاتف، أو رقم المريض...', value: query, onChange: (e) => setQuery(e.target.value), style: { paddingInlineEnd: 40 } }),
            h('span', { style: { position: 'absolute', insetInlineEnd: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-tertiary)' } }, h(Icons.Search, { size: 16 })),
          ),
          h('div', { className: 'flex gap-4' },
            ['all', 'active', 'debt'].map((f, i) => h('button', {
              key: f,
              className: 'btn sm ' + (filter === f ? 'primary' : 'outline'),
              onClick: () => setFilter(f),
            }, ['الكل', 'نشطون', 'عليهم مستحقات'][i])),
          ),
          h('div', { style: { display: 'flex', gap: 2, background: 'var(--bg-subtle)', padding: 4, borderRadius: 'var(--radius-sm)' } },
            ['table', 'grid'].map((v, i) => h('button', {
              key: v,
              onClick: () => setView(v),
              style: {
                padding: '6px 10px', border: 'none', background: view === v ? 'var(--bg-elevated)' : 'transparent',
                borderRadius: 4, cursor: 'pointer', color: view === v ? 'var(--text-primary)' : 'var(--text-tertiary)',
              },
            }, h(i === 0 ? Icons.List : Icons.Grid, { size: 14 }))),
          ),
        ),
      ),

      view === 'table' ? h('div', { className: 'card', style: { overflow: 'hidden' } },
        h('table', { className: 'data-table' },
          h('thead', null, h('tr', null, ['#', 'الاسم', 'العمر', 'الهاتف', 'الطبيب', 'آخر زيارة', 'الرصيد', 'الحالة', ''].map((t, i) => h('th', { key: i }, t)))),
          h('tbody', null,
            filtered.map(p => h('tr', { key: p.id, style: { cursor: 'pointer' }, onClick: () => setScreen('patient-file', { patientId: p.id }) },
              h('td', { style: { fontFamily: 'monospace', fontSize: 12, color: 'var(--text-tertiary)' } }, p.id),
              h('td', null, h('div', { className: 'flex ai-c gap-10' },
                h('div', { className: 'avatar sm' }, p.avatar),
                h('div', null,
                  h('div', { style: { fontWeight: 700 } }, p.name),
                  h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, p.gender),
                ),
              )),
              h('td', null, p.age),
              h('td', { style: { direction: 'ltr', textAlign: 'right', fontSize: 13 } }, p.phone),
              h('td', { style: { fontSize: 13 } }, p.doctor),
              h('td', { style: { fontSize: 13, color: 'var(--text-secondary)' } }, p.lastVisit),
              h('td', { style: { fontWeight: 700, color: p.balance > 0 ? 'var(--danger)' : 'var(--text-muted)' } }, window.fmtEGP(p.balance)),
              h('td', null, h('span', { className: 'chip ' + (p.status === 'active' ? 'success' : p.status === 'pending' ? 'warning' : '') },
                p.status === 'active' ? 'نشط' : p.status === 'pending' ? 'معلق' : 'غير نشط')),
              h('td', null,
                h('div', { className: 'flex gap-4' },
                  h('button', { className: 'icon-btn', title: 'تعديل', onClick: (e) => { e.stopPropagation(); setEditPatient(p); } }, h(Icons.Edit2, { size: 14 })),
                  h('button', { className: 'icon-btn', title: 'اتصال', onClick: (e) => { e.stopPropagation(); if(p.phone) window.open('tel:' + p.phone); } }, h(Icons.Phone, { size: 14 })),
                ),
              ),
            )),
          ),
        ),
      ) : h('div', { className: 'grid cols-3' },
        filtered.map(p => h('div', {
          key: p.id,
          className: 'card p-20',
          style: { cursor: 'pointer' },
          onClick: () => setScreen('patient-file', { patientId: p.id }),
        },
          h('div', { className: 'flex ai-c gap-12 mb-12' },
            h('div', { className: 'avatar lg' }, p.avatar),
            h('div', { style: { flex: 1 } },
              h('div', { style: { fontWeight: 800, fontSize: 15 } }, p.name),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${p.id} · ${p.age} سنة`),
            ),
            h('span', { className: 'chip ' + (p.status === 'active' ? 'success' : '') }, p.status === 'active' ? 'نشط' : 'غير نشط'),
            h('button', {
              className: 'icon-btn', title: 'تعديل',
              onClick: (e) => { e.stopPropagation(); setEditPatient(p); },
            }, h(Icons.Edit2, { size: 14 })),
          ),
          h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12 } },
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الهاتف'),
              h('div', { style: { fontWeight: 600, marginTop: 2, direction: 'ltr', textAlign: 'right' } }, p.phone),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الطبيب'),
              h('div', { style: { fontWeight: 600, marginTop: 2 } }, p.doctor),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'آخر زيارة'),
              h('div', { style: { fontWeight: 600, marginTop: 2 } }, p.lastVisit),
            ),
            h('div', null,
              h('div', { style: { color: 'var(--text-tertiary)', fontSize: 11 } }, 'الرصيد'),
              h('div', { style: { fontWeight: 700, marginTop: 2, color: p.balance > 0 ? 'var(--danger)' : 'var(--text-muted)' } }, window.fmtEGP(p.balance)),
            ),
          ),
        )),
      ),
    ),
  );
}

// ==================== Login Screen ====================
function Login() {
  const [tab, setTab]             = useState('login');  // login | register
  const [email, setEmail]         = useState('');
  const [password, setPassword]   = useState('');
  const [clinicNameVal, setClinicNameVal] = useState('');
  const [loading, setLoading]     = useState(false);
  const [error, setError]         = useState('');

  const Spinner = () => h('div', {
    style: { width: 16, height: 16, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.8s linear infinite' },
  });

  const handleLogin = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    const { error: err } = await SB.auth.signInWithPassword({ email, password });
    setLoading(false);
    if (err) setError(err.message === 'Invalid login credentials' ? 'البريد الإلكتروني أو كلمة المرور غير صحيحة' : err.message);
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    setError('');
    if (!clinicNameVal.trim()) { setError('أدخل اسم العيادة'); return; }
    if (password.length < 6)   { setError('كلمة المرور يجب أن تكون 6 أحرف على الأقل'); return; }
    setLoading(true);

    // 1. إنشاء حساب المستخدم
    const { data: authData, error: signUpErr } = await SB.auth.signUp({ email, password });
    if (signUpErr) { setLoading(false); setError(signUpErr.message); return; }

    // 2. إنشاء سجل العيادة (المستخدم الآن مسجّل دخول)
    const userId = authData?.user?.id;
    if (userId) {
      const { error: clinicErr } = await SB.from('clinics').insert({
        owner_id: userId,
        name: clinicNameVal.trim(),
      });
      if (clinicErr) {
        setLoading(false);
        setError('تم إنشاء الحساب — خطأ في العيادة: ' + clinicErr.message);
        return;
      }
    }

    setLoading(false);
    // auth state change في index.html هيكمل الباقي تلقائياً
  };

  const Logo = () => h('div', { style: { textAlign: 'center', marginBottom: 24 } },
    h('div', {
      style: {
        width: 60, height: 60, borderRadius: 16,
        background: 'linear-gradient(135deg, var(--accent), var(--info))',
        color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 16px',
        boxShadow: 'var(--shadow)',
      },
    }, h(Icons.Smile, { size: 28 })),
    h('div', { style: { fontSize: 24, fontWeight: 800 } }, 'سِنان كلينيك'),
    h('div', { style: { fontSize: 13, color: 'var(--text-tertiary)', marginTop: 4 } }, 'نظام إدارة عيادات الأسنان المتكامل'),
  );

  const TabBar = () => h('div', {
    style: { display: 'flex', gap: 4, background: 'var(--bg-subtle)', padding: 4, borderRadius: 'var(--radius)', marginBottom: 20 },
  },
    [['login', 'تسجيل الدخول'], ['register', 'عيادة جديدة']].map(([id, label]) =>
      h('button', {
        key: id, onClick: () => { setTab(id); setError(''); },
        style: {
          flex: 1, padding: '10px 12px', border: 'none', cursor: 'pointer',
          background: tab === id ? 'var(--bg-elevated)' : 'transparent',
          borderRadius: 'var(--radius-sm)',
          color: tab === id ? 'var(--text-primary)' : 'var(--text-tertiary)',
          fontWeight: 700, fontSize: 13, boxShadow: tab === id ? 'var(--shadow-sm)' : 'none',
          transition: 'all 0.15s',
        },
      }, label),
    ),
  );

  return h('div', { className: 'login-root' },
    h('div', { className: 'login-bg' }),
    h('div', { className: 'login-card card scale-in' },
      h(Logo),
      h(TabBar),

      tab === 'login'
        ? h('form', { onSubmit: handleLogin },
            h('div', { className: 'label' }, 'البريد الإلكتروني'),
            h('input', {
              className: 'input mb-16', type: 'email', required: true, autoFocus: true,
              placeholder: 'clinic@example.com',
              value: email, onChange: e => setEmail(e.target.value),
            }),
            h('div', { className: 'flex jc-sb ai-c', style: { marginBottom: 4 } },
              h('div', { className: 'label', style: { margin: 0 } }, 'كلمة المرور'),
            ),
            h('input', {
              className: 'input', type: 'password', required: true,
              placeholder: '••••••••',
              value: password, onChange: e => setPassword(e.target.value),
            }),
            error && h('div', { style: { marginTop: 12, fontSize: 12, color: error.startsWith('✅') ? 'var(--success)' : 'var(--danger)', fontWeight: 600 } }, error),
            h('button', {
              type: 'submit',
              className: 'btn primary mt-20',
              style: { width: '100%', justifyContent: 'center', padding: '12px 20px', fontSize: 14 },
              disabled: loading,
            }, loading ? h(Fragment, null, h(Spinner), 'جاري تسجيل الدخول...') : h(Fragment, null, h(Icons.LogIn, { size: 16 }), 'تسجيل الدخول')),
          )

        : h('form', { onSubmit: handleRegister },
            h('div', { className: 'label' }, 'اسم العيادة'),
            h('input', {
              className: 'input mb-16', required: true, autoFocus: true,
              placeholder: 'عيادة د. أحمد للأسنان',
              value: clinicNameVal, onChange: e => setClinicNameVal(e.target.value),
            }),
            h('div', { className: 'label' }, 'البريد الإلكتروني'),
            h('input', {
              className: 'input mb-16', type: 'email', required: true,
              placeholder: 'clinic@example.com',
              value: email, onChange: e => setEmail(e.target.value),
            }),
            h('div', { className: 'label' }, 'كلمة المرور'),
            h('input', {
              className: 'input', type: 'password', required: true,
              placeholder: '6 أحرف على الأقل',
              value: password, onChange: e => setPassword(e.target.value),
            }),
            error && h('div', { style: { marginTop: 12, fontSize: 12, color: error.startsWith('✅') ? 'var(--success)' : 'var(--danger)', fontWeight: 600 } }, error),
            h('button', {
              type: 'submit',
              className: 'btn primary mt-20',
              style: { width: '100%', justifyContent: 'center', padding: '12px 20px', fontSize: 14 },
              disabled: loading,
            }, loading ? h(Fragment, null, h(Spinner), 'جاري الإنشاء...') : h(Fragment, null, h(Icons.UserPlus, { size: 16 }), 'إنشاء الحساب')),
          ),
    ),
    h('style', null, `
      .login-root {
        position: fixed; inset: 0; display: grid; place-items: center;
        background: var(--bg); overflow: hidden; z-index: 1000;
      }
      .login-bg {
        position: absolute; inset: -10%;
        background:
          radial-gradient(ellipse at 20% 30%, color-mix(in oklab, var(--accent) 22%, transparent), transparent 55%),
          radial-gradient(ellipse at 80% 70%, color-mix(in oklab, var(--info) 22%, transparent), transparent 55%),
          radial-gradient(ellipse at 60% 20%, color-mix(in oklab, var(--purple) 14%, transparent), transparent 50%);
        filter: blur(60px); animation: drift 18s ease-in-out infinite alternate;
      }
      @keyframes drift { 0% { transform: translate(0,0) rotate(0); } 100% { transform: translate(3%, -2%) rotate(4deg); } }
      .login-card { width: 420px; max-width: 92vw; padding: 32px; position: relative; z-index: 1; }
      @keyframes spin { to { transform: rotate(360deg); } }
    `),
  );
}

window.Screens = Object.assign(window.Screens || {}, { Patients, Login });
