import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth, authFetch } from '@/context/AuthContext'
import { useLang } from '@/context/LangContext'
import { User, CalendarDays, KeyRound, Receipt, Heart, ChevronLeft, LogOut, Mail, Phone, Link2, SquarePen, Lock, Briefcase, type LucideIcon } from 'lucide-react'

const GOLD = '#CD9E53'
const NAVY = '#032340'

/* extra org/identity fields — backend stores only name+phone, so these live in localStorage */
type Extra = { gender: 'male' | 'female'; faFirst: string; faLast: string; enFirst: string; enLast: string; position: string; org: string; expertise: string; tags: string; linkedin: string }
const EMPTY: Extra = { gender: 'male', faFirst: '', faLast: '', enFirst: '', enLast: '', position: '', org: '', expertise: '', tags: '', linkedin: '' }
const keyFor = (email: string) => `sfi_profile_${email}`
const loadExtra = (email: string): Extra => { try { return { ...EMPTY, ...JSON.parse(localStorage.getItem(keyFor(email)) || '{}') } } catch { return EMPTY } }
const saveExtra = (email: string, e: Extra) => { try { localStorage.setItem(keyFor(email), JSON.stringify(e)) } catch { /* ignore */ } }

type Section = 'profile' | 'events' | 'subs' | 'finance' | 'saved' | 'password'

export default function ProfilePage() {
  const { lang } = useLang()
  const { member, logout } = useAuth()
  const navigate = useNavigate()
  const fa = lang === 'fa'
  const [section, setSection] = useState<Section>('profile')

  useEffect(() => { if (!member) navigate('/login') }, [member, navigate])
  if (!member) return null

  const initials = member.name.split(' ').map(w => w[0]).join('').slice(0, 2)

  const MENU: { key: Section; label: string; Icon: LucideIcon }[] = [
    { key: 'profile',  label: fa ? 'پروفایل سازمانی'         : 'Organizational Profile', Icon: User },
    { key: 'events',   label: fa ? 'رویدادها و نشست‌های من'  : 'My Events',              Icon: CalendarDays },
    { key: 'subs',     label: fa ? 'اشتراک‌ها و دسترسی‌ها'   : 'Subscriptions',          Icon: KeyRound },
    { key: 'finance',  label: fa ? 'سوابق مالی / فاکتورها'    : 'Billing',                Icon: Receipt },
    { key: 'saved',    label: fa ? 'علاقه‌مندی‌ها'           : 'Saved',                  Icon: Heart },
    { key: 'password', label: fa ? 'تغییر رمز عبور'           : 'Change Password',        Icon: Lock },
  ]

  return (
    <div dir={fa ? 'rtl' : 'ltr'} style={{ minHeight: '100vh', background: '#eef0f3', padding: '32px 0 64px' }}>
      <div className="max-w-7xl mx-auto px-12 max-md:px-5">
        <div style={{ display: 'grid', gridTemplateColumns: fa ? '300px 1fr' : '1fr 300px', gap: 24, alignItems: 'start' }} className="max-lg:!grid-cols-1">

          {/* ── MAIN ── */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20, order: fa ? 2 : 1 }}>
            {section === 'profile' ? (
              <>
                <IdentityCard member={member} fa={fa} />
                <ContactCard member={member} fa={fa} />
              </>
            ) : section === 'password' ? (
              <PasswordCard fa={fa} />
            ) : (
              <Placeholder fa={fa} title={MENU.find(m => m.key === section)?.label || ''} />
            )}
          </div>

          {/* ── SIDEBAR ── */}
          <aside style={{ display: 'flex', flexDirection: 'column', gap: 16, order: fa ? 1 : 2 }}>
            {/* user card */}
            <div style={card}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexDirection: 'row' }}>
                <div style={{ width: 54, height: 54, borderRadius: '50%', background: `linear-gradient(135deg, ${GOLD}, #e8b96a)`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, fontWeight: 800, color: NAVY, flexShrink: 0 }}>{initials}</div>
                <div style={{ minWidth: 0, textAlign: fa ? 'right' : 'left' }}>
                  <div style={{ fontSize: 15, fontWeight: 800, color: NAVY }}>{member.name}</div>
                  <div style={{ fontSize: 12, color: '#8a8f98', direction: 'ltr', marginTop: 2 }}>{member.phone || member.email}</div>
                </div>
              </div>
            </div>

            {/* menu */}
            <div style={{ ...card, padding: 8 }}>
              {MENU.map(({ key, label, Icon }) => {
                const active = section === key
                return (
                  <button key={key} onClick={() => setSection(key)} style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '12px 12px', border: 'none', cursor: 'pointer',
                    background: active ? `${GOLD}1a` : 'transparent', borderRadius: 10, fontFamily: 'inherit',
                    color: active ? GOLD : NAVY, fontWeight: active ? 800 : 600, fontSize: 13.5,
                    flexDirection: 'row', textAlign: fa ? 'right' : 'left',
                  }}>
                    <Icon size={18} color={active ? GOLD : 'rgba(3,35,64,0.55)'} strokeWidth={2} />
                    <span style={{ flex: 1 }}>{label}</span>
                    <ChevronLeft size={16} color="rgba(3,35,64,0.3)" className="no-rtl-flip" />
                  </button>
                )
              })}
            </div>

            {/* logout */}
            <button onClick={() => { logout(); navigate('/') }} style={{
              ...card, padding: '13px 16px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              border: '1px solid #f1c9c4', background: '#fdf2f1', color: '#c0392b', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit',
            }}>
              <LogOut size={16} className="no-rtl-flip" />
              {fa ? 'خروج از حساب کاربری' : 'Log out'}
            </button>
          </aside>

        </div>
      </div>
    </div>
  )
}

/* ═══ Identity card (read ↔ inline edit) ═══ */
function IdentityCard({ member, fa }: { member: { name: string; email: string; phone?: string }; fa: boolean }) {
  const { updateMember } = useAuth()
  const initial = (): Extra => {
    const ex = loadExtra(member.email)
    if (!ex.faFirst && !ex.faLast) { const parts = member.name.split(' '); ex.faFirst = parts[0] || ''; ex.faLast = parts.slice(1).join(' ') }
    return ex
  }
  const [editing, setEditing] = useState(false)
  const [ex, setEx] = useState<Extra>(initial)
  const [draft, setDraft] = useState<Extra>(ex)
  const [saving, setSaving] = useState(false)
  const set = (k: keyof Extra, v: string) => setDraft(d => ({ ...d, [k]: v }))

  async function save() {
    setSaving(true)
    const name = `${draft.faFirst} ${draft.faLast}`.trim() || member.name
    try { await authFetch('/api/members/me', { method: 'PUT', body: JSON.stringify({ name, phone: member.phone }) }); updateMember({ name }) } catch { /* keep going */ }
    saveExtra(member.email, draft); setEx(draft); setEditing(false); setSaving(false)
  }

  const tags = ex.tags.split(/[,،]/).map(s => s.trim()).filter(Boolean)

  return (
    <div style={card}>
      <CardHead title={fa ? 'اطلاعات هویتی و سازمانی' : 'Identity & Organization'}
        action={!editing && <EditLink fa={fa} onClick={() => { setDraft(ex); setEditing(true) }} />} />

      {!editing ? (
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <ReadRow fa={fa} label={fa ? 'نام سازمان / شرکت متبوع' : 'Organization'} value={ex.org || '—'} />
          <ReadRow fa={fa} label={fa ? 'سمت شغلی' : 'Position'} value={ex.position || '—'} />
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexDirection: 'row' }}>
            <span style={{ fontSize: 13, color: '#8a8f98', minWidth: 130, textAlign: fa ? 'right' : 'left' }}>{fa ? 'حوزه تخصصی:' : 'Expertise:'}</span>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', flex: 1 }}>
              {tags.length ? tags.map(t => <span key={t} style={{ fontSize: 12, fontWeight: 700, color: NAVY, background: `${GOLD}22`, borderRadius: 6, padding: '3px 10px' }}># {t}</span>) : <span style={{ fontSize: 13, color: NAVY }}>{ex.expertise || '—'}</span>}
            </div>
          </div>
        </div>
      ) : (
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {/* gender */}
          <div style={{ display: 'flex', gap: 22, flexDirection: 'row' }}>
            {(['male', 'female'] as const).map(g => (
              <label key={g} style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer', flexDirection: 'row' }}>
                <input type="radio" name="gender" checked={draft.gender === g} onChange={() => set('gender', g)} style={{ accentColor: GOLD }} />
                <span style={{ fontSize: 13.5, color: NAVY }}>{g === 'male' ? (fa ? 'مذکر' : 'Male') : (fa ? 'مونث' : 'Female')}</span>
              </label>
            ))}
          </div>
          <Row><Field label={fa ? 'نام به فارسی' : 'First name (FA)'} v={draft.faFirst} set={v => set('faFirst', v)} /><Field label={fa ? 'نام خانوادگی به فارسی' : 'Last name (FA)'} v={draft.faLast} set={v => set('faLast', v)} /></Row>
          <Row><Field label={fa ? 'نام به انگلیسی' : 'First name (EN)'} v={draft.enFirst} set={v => set('enFirst', v)} dir="ltr" /><Field label={fa ? 'نام خانوادگی به انگلیسی' : 'Last name (EN)'} v={draft.enLast} set={v => set('enLast', v)} dir="ltr" /></Row>
          <Row><Field label={fa ? 'سمت شغلی' : 'Position'} v={draft.position} set={v => set('position', v)} /><Field label={fa ? 'نام سازمان' : 'Organization'} v={draft.org} set={v => set('org', v)} /></Row>
          <Field label={fa ? 'تخصص (با ویرگول جدا کنید)' : 'Expertise (comma separated)'} v={draft.tags} set={v => set('tags', v)} />
          <div style={{ display: 'flex', gap: 12, marginTop: 4, flexDirection: fa ? 'row' : 'row-reverse', justifyContent: 'flex-end' }}>
            <button onClick={save} disabled={saving} style={{ background: NAVY, color: '#fff', border: 'none', borderRadius: 10, padding: '11px 30px', fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit' }}>{saving ? '...' : (fa ? 'ذخیره' : 'Save')}</button>
            <button onClick={() => setEditing(false)} style={{ background: '#fff', color: NAVY, border: `1.5px solid ${NAVY}33`, borderRadius: 10, padding: '11px 30px', fontWeight: 700, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit' }}>{fa ? 'انصراف' : 'Cancel'}</button>
          </div>
        </div>
      )}
    </div>
  )
}

/* ═══ Contact card ═══ */
function ContactCard({ member, fa }: { member: { email: string; phone?: string }; fa: boolean }) {
  const ex = loadExtra(member.email)
  return (
    <div style={card}>
      <CardHead title={fa ? 'اطلاعات تماس و شبکه‌سازی' : 'Contact & Networking'} />
      <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <ContactRow fa={fa} Icon={Mail} label={fa ? 'آدرس ایمیل:' : 'Email:'} value={member.email} ltr />
        <ContactRow fa={fa} Icon={Phone} label={fa ? 'شماره موبایل:' : 'Mobile:'} value={member.phone || '—'} ltr />
        <ContactRow fa={fa} Icon={Link2} label={fa ? 'پروفایل لینکدین:' : 'LinkedIn:'} value={ex.linkedin || '—'} ltr />
      </div>
    </div>
  )
}

/* ═══ Password card — change with current password, or reset via SMS code ═══ */
function PasswordCard({ fa }: { fa: boolean }) {
  const [mode, setMode] = useState<'pw' | 'sms'>('pw')
  const [cur, setCur] = useState(''); const [nx, setNx] = useState(''); const [cf, setCf] = useState('')
  const [code, setCode] = useState(''); const [sent, setSent] = useState(false)
  const [msg, setMsg] = useState(''); const [ok, setOk] = useState(false); const [saving, setSaving] = useState(false)

  function reset() { setCur(''); setNx(''); setCf(''); setCode(''); setMsg('') }

  async function save(e: React.FormEvent) {
    e.preventDefault(); setMsg(''); setOk(false)
    if (nx !== cf) { setMsg(fa ? 'رمزها یکسان نیستند' : 'Passwords do not match'); return }
    setSaving(true)
    try {
      const res = await authFetch('/api/members/me/password', { method: 'PUT', body: JSON.stringify({ currentPassword: cur, newPassword: nx }) })
      const d = await res.json(); if (!res.ok) throw new Error(d.error)
      setOk(true); setMsg(fa ? 'رمز تغییر یافت' : 'Password changed'); reset()
    } catch (err: unknown) { setMsg(err instanceof Error ? err.message : (fa ? 'خطا' : 'Error')) }
    finally { setSaving(false) }
  }

  async function sendCode() {
    setMsg(''); setOk(false); setSaving(true)
    try {
      const res = await authFetch('/api/members/me/password-otp/send', { method: 'POST', body: '{}' })
      const d = await res.json(); if (!res.ok) throw new Error(d.error)
      setSent(true); setMsg(fa ? 'کد به شماره موبایل شما پیامک شد' : 'Code sent to your phone'); setOk(true)
    } catch (err: unknown) { setMsg(err instanceof Error ? err.message : (fa ? 'ارسال کد ناموفق بود' : 'Failed to send code')) }
    finally { setSaving(false) }
  }

  async function saveSms(e: React.FormEvent) {
    e.preventDefault(); setMsg(''); setOk(false)
    if (nx !== cf) { setMsg(fa ? 'رمزها یکسان نیستند' : 'Passwords do not match'); return }
    setSaving(true)
    try {
      const res = await authFetch('/api/members/me/password-otp/set', { method: 'POST', body: JSON.stringify({ code, newPassword: nx }) })
      const d = await res.json(); if (!res.ok) throw new Error(d.error)
      setOk(true); setMsg(fa ? 'رمز با موفقیت تنظیم شد' : 'Password set'); setSent(false); setMode('pw'); reset()
    } catch (err: unknown) { setMsg(err instanceof Error ? err.message : (fa ? 'خطا' : 'Error')) }
    finally { setSaving(false) }
  }

  const submitBtn = { alignSelf: 'flex-start' as const, background: NAVY, color: '#fff', border: 'none', borderRadius: 10, padding: '11px 30px', fontWeight: 800, fontSize: 13.5, cursor: 'pointer', fontFamily: 'inherit' }
  const linkBtn = { background: 'none', border: 'none', color: GOLD, fontSize: 12.5, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', padding: 0, textAlign: (fa ? 'right' : 'left') as 'right' | 'left', alignSelf: 'flex-start' as const }

  return (
    <div style={card}>
      <CardHead title={fa ? 'تغییر رمز عبور' : 'Change Password'} />

      {mode === 'pw' ? (
        <form onSubmit={save} style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 420 }}>
          <Field label={fa ? 'رمز فعلی' : 'Current password'} v={cur} set={setCur} type="password" dir="ltr" />
          <Field label={fa ? 'رمز جدید' : 'New password'} v={nx} set={setNx} type="password" dir="ltr" />
          <Field label={fa ? 'تکرار رمز جدید' : 'Confirm password'} v={cf} set={setCf} type="password" dir="ltr" />
          {msg && <div style={{ fontSize: 13, color: ok ? '#1a8a4c' : '#c0392b' }}>{msg}</div>}
          <button type="submit" disabled={saving} style={submitBtn}>{saving ? '...' : (fa ? 'تغییر رمز' : 'Change')}</button>
          <button type="button" onClick={() => { setMode('sms'); reset() }} style={linkBtn}>
            {fa ? 'رمز فعلی را نمی‌دانید؟ تنظیم رمز با کد پیامک' : "Don't know your password? Set it via SMS code"}
          </button>
        </form>
      ) : (
        <form onSubmit={saveSms} style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 420 }}>
          {!sent ? (
            <>
              <p style={{ margin: 0, fontSize: 13, color: '#777', lineHeight: 1.9 }}>
                {fa ? 'یک کد تأیید به شماره موبایل ثبت‌شده شما پیامک می‌شود.' : 'A verification code will be sent to your registered phone.'}
              </p>
              {msg && <div style={{ fontSize: 13, color: ok ? '#1a8a4c' : '#c0392b' }}>{msg}</div>}
              <button type="button" onClick={sendCode} disabled={saving} style={submitBtn}>{saving ? '...' : (fa ? 'ارسال کد' : 'Send code')}</button>
            </>
          ) : (
            <>
              <Field label={fa ? 'کد تأیید' : 'Verification code'} v={code} set={setCode} dir="ltr" />
              <Field label={fa ? 'رمز جدید' : 'New password'} v={nx} set={setNx} type="password" dir="ltr" />
              <Field label={fa ? 'تکرار رمز جدید' : 'Confirm password'} v={cf} set={setCf} type="password" dir="ltr" />
              {msg && <div style={{ fontSize: 13, color: ok ? '#1a8a4c' : '#c0392b' }}>{msg}</div>}
              <button type="submit" disabled={saving} style={submitBtn}>{saving ? '...' : (fa ? 'تنظیم رمز جدید' : 'Set password')}</button>
            </>
          )}
          <button type="button" onClick={() => { setMode('pw'); setSent(false); reset() }} style={linkBtn}>
            ← {fa ? 'بازگشت به تغییر رمز با رمز فعلی' : 'Back to current-password change'}
          </button>
        </form>
      )}
    </div>
  )
}

function Placeholder({ fa, title }: { fa: boolean; title: string }) {
  return (
    <div style={{ ...card, textAlign: 'center', padding: '64px 24px' }}>
      <div style={{ width: 56, height: 56, borderRadius: 14, background: `${GOLD}1a`, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
        <CalendarDays size={26} color={GOLD} />
      </div>
      <h3 style={{ fontSize: 17, fontWeight: 800, color: NAVY, margin: '0 0 8px' }}>{title}</h3>
      <p style={{ fontSize: 13.5, color: '#8a8f98', margin: 0 }}>{fa ? 'این بخش به‌زودی فعال می‌شود.' : 'This section is coming soon.'}</p>
    </div>
  )
}

/* ═══ primitives ═══ */
const card: React.CSSProperties = { background: '#fff', borderRadius: 16, padding: '22px 24px', border: '1px solid rgba(3,35,64,0.06)', boxShadow: '0 6px 24px -16px rgba(3,35,64,0.25)' }

function CardHead({ title, action }: { title: string; action?: React.ReactNode }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, paddingBottom: 14, borderBottom: '1px solid rgba(3,35,64,0.07)', flexDirection: 'row' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexDirection: 'row' }}>
        <span style={{ width: 30, height: 30, borderRadius: 8, background: `${GOLD}18`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Briefcase size={16} color={GOLD} /></span>
        <h3 style={{ fontSize: 15.5, fontWeight: 800, color: NAVY, margin: 0 }}>{title}</h3>
      </div>
      {action}
    </div>
  )
}

function EditLink({ fa, onClick }: { fa: boolean; onClick: () => void }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', color: GOLD, fontWeight: 700, fontSize: 12.5, fontFamily: 'inherit' }}>
      <SquarePen size={14} />{fa ? 'ویرایش اطلاعات' : 'Edit'}
    </button>
  )
}

function ReadRow({ fa, label, value }: { fa: boolean; label: string; value: string }) {
  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexDirection: 'row' }}>
      <span style={{ fontSize: 13, color: '#8a8f98', minWidth: 130, textAlign: fa ? 'right' : 'left' }}>{label}{fa ? ':' : ''}</span>
      <span style={{ fontSize: 13.5, color: NAVY, fontWeight: 600 }}>{value}</span>
    </div>
  )
}

function ContactRow({ fa, Icon, label, value, ltr }: { fa: boolean; Icon: LucideIcon; label: string; value: string; ltr?: boolean }) {
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexDirection: 'row' }}>
      <Icon size={16} color={GOLD} style={{ flexShrink: 0 }} />
      <span style={{ fontSize: 13, color: '#8a8f98', minWidth: 120, textAlign: fa ? 'right' : 'left' }}>{label}</span>
      <span style={{ fontSize: 13.5, color: NAVY, fontWeight: 600, direction: ltr ? 'ltr' : undefined, wordBreak: 'break-all' }}>{value}</span>
    </div>
  )
}

function Row({ children }: { children: React.ReactNode }) {
  return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }} className="max-sm:!grid-cols-1">{children}</div>
}

function Field({ label, v, set, type = 'text', dir }: { label: string; v: string; set: (v: string) => void; type?: string; dir?: 'ltr' | 'rtl' }) {
  const [focus, setFocus] = useState(false)
  return (
    <label style={{ display: 'block' }}>
      <span style={{ display: 'block', fontSize: 12, color: GOLD, fontWeight: 700, marginBottom: 6 }}>{label}</span>
      <input type={type} value={v} onChange={e => set(e.target.value)} dir={dir} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{ width: '100%', padding: '11px 14px', borderRadius: 10, border: `1.5px solid ${focus ? GOLD : '#e2e5e9'}`, background: '#fff', color: NAVY, fontSize: 14, outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit' }} />
    </label>
  )
}
