// T2 Falcon Admin — User Details page (More Details from user row menu)
// Three tabs: Personal Information, Role & Status, Permissions & Privilege
// View + Edit modes, reuses au-* styles from adduser.

const { useState: useStateUD, useRef: useRefUD } = React;

const UD_TABS = [
  { id: 'personal',    label: 'Personal Information' },
  { id: 'role',        label: 'Role & Status' },
  { id: 'permissions', label: 'Permissions & Privilege' }
];

// Map seed user shape -> form shape used by detail/edit
const seedToForm = (u) => ({
  photo: u?.photo || '',
  firstName: u?.firstName || '',
  lastName:  u?.lastName  || (u?.firstName ? '' : ''),
  userName:  u?.username  || '',
  password:  '#####',
  nationalId: u?.nationalId || u?.firstName || '',
  phoneCountry: u?.phoneCountry || 'SA',
  phone:     u?.phone || '',
  phoneVerified: u?.status === 'pending' ? false : true,
  email:     u?.email || '',
  emailVerified: u?.status === 'pending' ? false : true,
  status:    u?.status || 'pending',
  role:      u?.role || 'system_admin',
  permGroup: u?.permGroup || 'admin',
  checker_whatsapp: u?.checker_whatsapp || 'level2',
  checker_voice:    u?.checker_voice    || 'level1'
});

// ============== Verification badge ==============
const UDVerifyBadge = ({ verified }) => (
  <span
    className={`ud-verify-badge ${verified ? 'is-verified' : 'is-unverified'}`}
    aria-label={verified ? 'Verified' : 'Not verified'}>
    {verified ? (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
        <polyline points="8 12.5 11 15.5 16.5 9.5" />
      </svg>
    ) : (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
        <line x1="12" y1="9" x2="12" y2="13" />
        <line x1="12" y1="17" x2="12.01" y2="17" />
      </svg>
    )}
    <span className="ud-verify-tooltip">{verified ? 'Verified' : 'Not verified'}</span>
  </span>
);

// ============== Read-only field display ==============
const UDField = ({ label, value, copy, mono, verified }) => (
  <div className="ud-field">
    <div className="ud-field-label">{label}</div>
    <div className={`ud-field-value ${mono ? 'mono' : ''}`}>
      <span>{value || <span className="ud-empty">—</span>}</span>
      {copy && value && (
        <button
          type="button"
          className="ud-copy-btn"
          onClick={(e) => { e.stopPropagation(); navigator.clipboard?.writeText(value); }}
          aria-label="Copy">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <rect x="9" y="9" width="13" height="13" rx="2" />
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
          </svg>
        </button>
      )}
      {value && verified !== undefined && verified !== null && (
        <UDVerifyBadge verified={!!verified} />
      )}
    </div>
  </div>
);

// Initials helper — falls back to first 1–2 letters of a name
const initialsFor = (form) => {
  const f = (form.firstName || '').trim();
  const l = (form.lastName  || '').trim();
  if (f && l) return (f[0] + l[0]).toUpperCase();
  if (f) return f.slice(0, 2).toUpperCase();
  if (form.userName) return form.userName.slice(0, 2).toUpperCase();
  return '?';
};

// ============== VIEW TABS ==============
const UDTabPersonal = ({ form }) => {
  const fullName = [form.firstName, form.lastName].filter(Boolean).join(' ') || form.userName || '—';
  return (
    <div className="ud-tab-pane">
      <div className="ud-avatar-row">
        <div className="ud-avatar-circle ud-avatar-circle-lg">
          {form.photo ? (
            <img src={form.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} />
          ) : (
            <span className="ud-avatar-initials">{initialsFor(form)}</span>
          )}
        </div>
        <div className="ud-avatar-meta">
          <div className="ud-avatar-name">{fullName}</div>
          <div className="ud-avatar-label">User Picture</div>
        </div>
      </div>

    <div className="ud-divider" />

    <div className="ud-grid-4">
      <UDField label="First Name"        value={form.firstName} />
      <UDField label="Last Name"         value={form.lastName || form.firstName} />
      <UDField label="User Name"         value={form.userName} />
      <UDField label="National ID/Iqama" value={form.nationalId} />
    </div>

    <div className="ud-grid-4" style={{ marginTop: 28 }}>
      <UDField label="Phone Number"  value={form.phone} verified={form.status === 'pending' ? form.phoneVerified : undefined} />
      <UDField label="Email Address" value={form.email} copy verified={form.status === 'pending' ? form.emailVerified : undefined} />
    </div>
  </div>
  );
};

const STATUS_LABEL = {
  active: 'Active', suspended: 'Suspended', deleted: 'Deleted',
  locked: 'Locked', pending: 'Pending', inactive: 'Inactive'
};
const ROLE_LABEL = {
  system_admin: 'System Admin', operation: 'Operation',
  products: 'Products', support: 'Support', viewer: 'Viewer'
};
const PERM_LABEL = {
  admin: 'Admin Group', readonly: 'Read Only Group',
  ops: 'Operations Group', support: 'Support Group',
  Support: 'Admin Group', Ops: 'Operations Group'
};
const CHECKER_LABEL = {
  none: 'None', level1: 'Checker Level One', level2: 'Checker Level Two'
};

const UDTabRole = ({ form }) => (
  <div className="ud-tab-pane">
    <div className="ud-grid-2">
      <UDField label="User Status" value={STATUS_LABEL[form.status] || form.status} />
      <UDField label="User Role"   value={ROLE_LABEL[form.role] || form.role} />
    </div>
  </div>
);

const UDTabPermissions = ({ form }) => (
  <div className="ud-tab-pane">
    <div className="ud-perm-block">
      <div className="ud-field-label">Assigned Permission Group</div>
      <div className="ud-perm-value">{PERM_LABEL[form.permGroup] || form.permGroup}</div>
    </div>

    <div className="ud-perm-spacer" />

    <div className="ud-perm-block">
      <div className="ud-field-label">CommChannel Checker Level</div>
      <div className="ud-checker-grid">
        <div>
          <div className="ud-checker-ch">WhatsApp</div>
          <div className="ud-checker-val">{CHECKER_LABEL[form.checker_whatsapp]}</div>
        </div>
        <div>
          <div className="ud-checker-ch">Voice</div>
          <div className="ud-checker-val">{CHECKER_LABEL[form.checker_voice]}</div>
        </div>
      </div>
    </div>
  </div>
);

// ============== EDIT TABS (reusing au-* styles) ==============
const UDEditPersonal = ({ form, onChange }) => {
  const fileRef = useRefUD(null);
  const [otpChannel, setOtpChannel] = useStateUD(null);
  // Editing phone or email clears its verification badge
  const onPhoneChange = (k, v) => {
    onChange(k, v);
    if (k === 'phone' && form.phoneVerified) onChange('phoneVerified', false);
  };
  const onEmailChange = (v) => {
    onChange('email', v);
    if (form.emailVerified) onChange('emailVerified', false);
  };
  return (
    <div className="ud-tab-pane">
      <div className="au-avatar-row" style={{ margin: 0 }}>
        <div className="au-avatar-left">
          <div className="au-avatar-circle">
            {form.photo ? (
              <img src={form.photo} alt="avatar" style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} />
            ) : (
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#0d3f44" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="8" r="4" /><path d="M4 20c0-4 4-6 8-6s8 2 8 6" />
              </svg>
            )}
            {form.photo && <>
              <button
                type="button"
                className="au-avatar-edit"
                aria-label="Edit photo"
                onClick={(e) => { e.stopPropagation(); fileRef.current?.click(); }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M12 20h9" /><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
                </svg>
              </button>
              <button
                type="button"
                className="au-avatar-delete"
                aria-label="Remove photo"
                onClick={(e) => { e.stopPropagation(); onChange('photo', ''); }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="6" y1="6" x2="18" y2="18" /><line x1="6" y1="18" x2="18" y2="6" />
                </svg>
              </button>
            </>}
          </div>
          <div className="au-avatar-label">
            User Picture
            <span className="sub">PNG, JPG up to 2MB</span>
          </div>
        </div>
        <div className="au-avatar-right">
          <span className="au-drag-hint">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="16 16 12 12 8 16" /><line x1="12" y1="12" x2="12" y2="21" />
              <path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3" />
            </svg>
            Drag a photo here or
          </span>
          <button type="button" className="btn btn-primary" onClick={() => fileRef.current.click()}>Upload Photo</button>
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }}
            onChange={(e) => {
              const f = e.target.files[0];
              if (f) { const r = new FileReader(); r.onload = (ev) => onChange('photo', ev.target.result); r.readAsDataURL(f); }
            }} />
        </div>
      </div>

      <div className="au-divider" />

      <div className="au-form-grid au-form-grid-3">
        <div className="au-field">
          <label className="au-label">First Name <span className="req">*</span></label>
          <input className="au-input" value={form.firstName} onChange={(e) => onChange('firstName', e.target.value)} />
        </div>
        <div className="au-field">
          <label className="au-label">Last Name <span className="req">*</span></label>
          <input className="au-input" value={form.lastName} onChange={(e) => onChange('lastName', e.target.value)} />
        </div>
        <div className="au-field">
          <label className="au-label">User Name <span className="req">*</span></label>
          <input className="au-input" value={form.userName} onChange={(e) => onChange('userName', e.target.value)} />
        </div>
        <div className="au-field">
          <label className="au-label">National ID / Iqama</label>
          <input className="au-input" value={form.nationalId} onChange={(e) => onChange('nationalId', e.target.value)} />
        </div>
        <div className="au-field">
          <label className="au-label">Phone Number <span className="req">*</span></label>
          <PhoneInput
            data={form}
            onChange={onPhoneChange}
            showVerify={form.status === 'pending'}
            verified={form.phoneVerified}
            onVerify={() => { onChange('phoneVerified', false); setOtpChannel('phone'); }}
          />
        </div>
        <div className="au-field">
          <label className="au-label">Email Address <span className="req">*</span></label>
          <EmailInput
            value={form.email}
            onChange={onEmailChange}
            showVerify={form.status === 'pending'}
            verified={form.emailVerified}
            onVerify={() => { onChange('emailVerified', false); setOtpChannel('email'); }}
          />
        </div>
      </div>

      {otpChannel && (
        <OtpModal
          channel={otpChannel}
          target={otpChannel === 'phone' ? `${form.phone || ''}` : (form.email || '')}
          onClose={() => setOtpChannel(null)}
          onSuccess={() => {
            if (otpChannel === 'phone') onChange('phoneVerified', true);
            else onChange('emailVerified', true);
            setOtpChannel(null);
          }}
        />
      )}
    </div>
  );
};

const UDEditRole = ({ form, onChange }) => (
  <div className="ud-tab-pane">
    <div className="au-form-grid au-form-grid-2">
      <div className="au-field">
        <label className="au-label">User Status</label>
        <div className="au-select-wrap au-select-wrap-disabled">
          <select className="au-select au-select-disabled" value={form.status} onChange={(e) => onChange('status', e.target.value)} disabled>
            <option value="active">Active</option>
            <option value="pending">Pending</option>
            <option value="suspended">Suspended</option>
            <option value="locked">Locked</option>
            <option value="deleted">Deleted</option>
          </select>
          <IcChevronDown size={14} stroke={2} className="au-select-chevron" />
        </div>
      </div>
      <div className="au-field">
        <label className="au-label">User Role</label>
        <div className="au-select-wrap">
          <select className="au-select" value={form.role} onChange={(e) => onChange('role', e.target.value)}>
            <option value="system_admin">System Admin</option>
            <option value="operation">Operation</option>
            <option value="products">Products</option>
            <option value="support">Support</option>
            <option value="viewer">Viewer</option>
          </select>
          <IcChevronDown size={14} stroke={2} className="au-select-chevron" />
        </div>
      </div>
    </div>
  </div>
);

const UD_CHECKER_OPTIONS = [
  { value: 'none', label: 'None' },
  { value: 'level1', label: 'Checker Level One' },
  { value: 'level2', label: 'Checker Level Two' }
];

const UDEditPermissions = ({ form, onChange }) => (
  <div className="ud-tab-pane">
    <div className="au-perm-section">
      <label className="au-label au-perm-label">Assigned Permission Group</label>
      <div className="au-select-wrap au-perm-select-wrap">
        <select className="au-select" value={form.permGroup} onChange={(e) => onChange('permGroup', e.target.value)}>
          <option value="admin">Admin Group</option>
          <option value="readonly">Read Only Group</option>
          <option value="ops">Operations Group</option>
          <option value="support">Support Group</option>
        </select>
        <IcChevronDown size={14} stroke={2} className="au-select-chevron" />
      </div>
    </div>

    <div className="au-divider" />

    <div className="au-perm-section">
      <div className="au-checker-title">CommChannel Checker Level</div>
      <div className="au-checker-table">
        {[
          { id: 'whatsapp', label: 'WhatsApp' },
          { id: 'voice',    label: 'Voice' }
        ].map((ch) => (
          <div key={ch.id} className="au-checker-row">
            <span className="au-checker-ch-label">{ch.label}</span>
            <div className="au-checker-options">
              {UD_CHECKER_OPTIONS.map((opt) => (
                <label key={opt.value} className="au-radio-label">
                  <input type="radio" name={`ud-checker-${ch.id}`} value={opt.value}
                    checked={form[`checker_${ch.id}`] === opt.value}
                    onChange={() => onChange(`checker_${ch.id}`, opt.value)}
                    className="au-radio" />
                  <span className="au-radio-mark" />
                  <span>{opt.label}</span>
                </label>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ============== Main UserDetailsPage ==============
const UserDetailsPage = ({ user, node, onBack, t, pushToast }) => {
  const [form, setForm]         = useStateUD(seedToForm(user));
  const [origForm, setOrigForm] = useStateUD(seedToForm(user));
  const [activeTab, setActiveTab] = useStateUD('personal');
  const [editing, setEditing]     = useStateUD(false);
  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const startEdit = () => { setOrigForm(form); setEditing(true); };
  const cancelEdit = () => { setForm(origForm); setEditing(false); };
  const saveEdit = () => {
    setOrigForm(form);
    setEditing(false);
    pushToast && pushToast('User updated ✓');
  };

  const isRoot = !node || node.type === 'root';
  const displayName = node ? node.name : 'Falcon';

  return (
    <div className="ud-wrap">
      {/* Top header (matches node-header pattern) */}
      <div className="ud-top-bar">
        <div className="ud-top-left">
          {isRoot ? (
            <span className="node-avatar"><IcFalcon size={18} /></span>
          ) : node && node.type === 'client' ? (
            <BrandLogo brand={node.brand} size={32} />
          ) : (
            <span className="node-avatar" style={{ background: '#0d3f44', color: 'white' }}>
              <span style={{ fontSize: 12, fontWeight: 700 }}>{displayName.slice(0, 1)}</span>
            </span>
          )}
          <span className="ud-top-name">{displayName}</span>
        </div>
        <div className="ud-top-actions">
          {editing ? (
            <>
              <button className="btn btn-secondary" onClick={cancelEdit}>Cancel</button>
              <button className="btn btn-primary" onClick={saveEdit}>Save</button>
            </>
          ) : (
            <>
              <button className="btn btn-secondary" onClick={onBack}>
                <IcArrowLeft size={14} stroke={1.8} className="flip-rtl" />
                Back to User list
              </button>
              <button className="btn btn-primary ud-edit-btn" onClick={startEdit}>
                <IcEdit size={14} stroke={1.8} />
                Edit
              </button>
            </>
          )}
        </div>
      </div>

      {/* Card */}
      <div className="ud-card">
        <div className="ud-card-head">
          <h2 className="ud-card-title">{editing ? 'Edit User' : 'User Profile'}</h2>
        </div>

        {/* Tabs */}
        <div className="ud-tabs">
          {UD_TABS.map((tb) => (
            <button
              key={tb.id}
              className={`ud-tab ${activeTab === tb.id ? 'active' : ''}`}
              onClick={() => setActiveTab(tb.id)}>
              {tb.label}
            </button>
          ))}
        </div>

        {/* Pane */}
        {!editing ? (
          <>
            {activeTab === 'personal'    && <UDTabPersonal    form={form} />}
            {activeTab === 'role'        && <UDTabRole        form={form} />}
            {activeTab === 'permissions' && <UDTabPermissions form={form} />}
          </>
        ) : (
          <>
            {activeTab === 'personal'    && <UDEditPersonal    form={form} onChange={update} />}
            {activeTab === 'role'        && <UDEditRole        form={form} onChange={update} />}
            {activeTab === 'permissions' && <UDEditPermissions form={form} onChange={update} />}
          </>
        )}
      </div>
    </div>
  );
};

window.UserDetailsPage = UserDetailsPage;
