/* global React, Icon */
const { useState, useEffect } = React;

function ProfilePage({ navigate }) {
  const [profile, setProfile] = useState(null);
  const [addresses, setAddresses] = useState([]);
  const [tab, setTab] = useState('profile'); // profile | addresses
  const [form, setForm] = useState({ full_name: '', phone: '' });
  const [loading, setLoading] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState(null);
  const [editingAddr, setEditingAddr] = useState(null);
  const [editAddrForm, setEditAddrForm] = useState({});

  useEffect(() => {
    if (!window.IndieAuth.isLoggedIn()) { navigate('/gallery'); return; }
    const p = window.IndieAuth.getProfile();
    setProfile(p);
    setForm({ full_name: p?.full_name || '', phone: p?.phone || '' });
    window.IndieAuth.loadAddresses().then(setAddresses);
  }, []);

  const saveProfile = async () => {
    setLoading(true); setError(null); setSaved(false);
    try {
      const sb = window.supabase.createClient(
        'https://indie.supabase.co',
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Indsc3pqdnZveXltd2dwbXRnd2V4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ1ODg5OTcsImV4cCI6MjA5MDE2NDk5N30.5emUfc2jlLxutLhtGZFD0Rq3MOUl4JAcU3Fd5RydjRU'
      );
      const session = window.IndieAuth.getSession();
      await sb.from('customer_profiles')
        .update({ full_name: form.full_name, phone: form.phone })
        .eq('id', session.user.id);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch(e) { setError(e.message); }
    finally { setLoading(false); }
  };

  const deleteAddress = async (id) => {
    const sb = window.supabase.createClient(
      'https://indie.supabase.co',
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Indsc3pqdnZveXltd2dwbXRnd2V4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ1ODg5OTcsImV4cCI6MjA5MDE2NDk5N30.5emUfc2jlLxutLhtGZFD0Rq3MOUl4JAcU3Fd5RydjRU'
    );
    await sb.from('customer_addresses').delete().eq('id', id);
    setAddresses(a => a.filter(x => x.id !== id));
  };

  const saveEditAddr = async () => {
    if (!editingAddr) return;
    setLoading(true);
    try {
      await window.IndieAuth.saveAddress({ ...editAddrForm, id: editingAddr });
      const updated = await window.IndieAuth.loadAddresses();
      setAddresses(updated);
      setEditingAddr(null);
    } catch(e) { setError(e.message); }
    finally { setLoading(false); }
  };

  if (!profile) return (
    <main className="fade-in">
      <div className="shell" style={{padding:'80px 0', textAlign:'center', color:'var(--ink-meta)'}}>Memuat profil…</div>
    </main>
  );

  return (
    <main className="fade-in">
      <div className="shell" style={{maxWidth:680, paddingBlock:'clamp(32px,6vw,64px)'}}>
        <nav className="crumb" style={{marginBottom:32}}>
          <a onClick={() => navigate('/gallery')}>Gallery</a>
          <span className="sep">/</span>
          <span className="here">Profil</span>
        </nav>

        <div style={{display:'flex', gap:8, marginBottom:32, borderBottom:'1px solid var(--paper-card-edge)', paddingBottom:0}}>
          {[['profile','Profil saya'],['addresses','Alamat']].map(([id,label]) => (
            <button key={id} onClick={() => setTab(id)} style={{
              padding:'10px 20px', border:'none', background:'none', cursor:'pointer',
              fontFamily:'var(--font-sans)', fontSize:14, fontWeight:500,
              color: tab===id ? 'var(--ink)' : 'var(--ink-meta)',
              borderBottom: tab===id ? '2px solid var(--ink)' : '2px solid transparent',
              marginBottom:-1,
            }}>{label}</button>
          ))}
        </div>

        {tab === 'profile' && (
          <div>
            <div className="field" style={{marginBottom:16}}>
              <label style={{display:'block',fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.1em',color:'var(--ink-meta)',marginBottom:6}}>Nama lengkap</label>
              <input type="text" value={form.full_name} onChange={e => setForm(f=>({...f,full_name:e.target.value}))}
                style={{width:'100%',boxSizing:'border-box',padding:'10px 12px',border:'1px solid var(--paper-card-edge)',fontFamily:'var(--font-sans)',fontSize:14,color:'var(--ink)',outline:'none'}} />
            </div>
            <div className="field" style={{marginBottom:16}}>
              <label style={{display:'block',fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.1em',color:'var(--ink-meta)',marginBottom:6}}>Email</label>
              <input type="email" value={profile.email || ''} disabled
                style={{width:'100%',boxSizing:'border-box',padding:'10px 12px',border:'1px solid var(--paper-card-edge)',fontFamily:'var(--font-sans)',fontSize:14,color:'var(--ink-meta)',background:'var(--paper-cream)',outline:'none'}} />
            </div>
            <div className="field" style={{marginBottom:24}}>
              <label style={{display:'block',fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.1em',color:'var(--ink-meta)',marginBottom:6}}>WhatsApp</label>
              <input type="text" value={form.phone} onChange={e => setForm(f=>({...f,phone:e.target.value}))}
                placeholder="+62 81..."
                style={{width:'100%',boxSizing:'border-box',padding:'10px 12px',border:'1px solid var(--paper-card-edge)',fontFamily:'var(--font-sans)',fontSize:14,color:'var(--ink)',outline:'none'}} />
            </div>
            {error && <div style={{padding:'10px',background:'#FEF2F2',color:'#DC2626',fontSize:13,marginBottom:12}}>{error}</div>}
            {saved && <div style={{padding:'10px',background:'#F0FDF4',color:'#166534',fontSize:13,marginBottom:12}}>Profil berhasil disimpan!</div>}
            <button className="btn btn-primary" onClick={saveProfile} disabled={loading}>
              {loading ? 'Menyimpan...' : 'Simpan perubahan'}
            </button>
          </div>
        )}

        {tab === 'addresses' && (
          <div>
            {addresses.length === 0 ? (
              <div style={{padding:'40px 0',textAlign:'center',color:'var(--ink-meta)'}}>
                <p>Belum ada alamat tersimpan.</p>
                <button className="btn btn-primary" onClick={() => navigate('/checkout')}>Checkout untuk tambah alamat</button>
              </div>
            ) : (
              <div style={{display:'flex',flexDirection:'column',gap:12}}>
                {addresses.map(addr => (
                  <div key={addr.id} style={{border:'1px solid var(--paper-card-edge)',background:'var(--paper-card)'}}>
                    {editingAddr === addr.id ? (
                      <div style={{padding:'16px',display:'flex',flexDirection:'column',gap:10}}>
                        {[
                          ['label','Label (contoh: Rumah, Kantor)'],
                          ['street','Alamat lengkap'],
                          ['city','Kota'],
                          ['province','Provinsi'],
                          ['postal_code','Kode pos'],
                        ].map(([key, placeholder]) => (
                          <input key={key} type="text"
                            value={editAddrForm[key] || ''}
                            onChange={e => setEditAddrForm(f => ({...f, [key]: e.target.value}))}
                            placeholder={placeholder}
                            style={{width:'100%',boxSizing:'border-box',padding:'8px 10px',border:'1px solid var(--paper-card-edge)',fontFamily:'var(--font-sans)',fontSize:13,outline:'none'}}
                          />
                        ))}
                        <div style={{display:'flex',gap:8}}>
                          <button className="btn btn-primary btn-sm" onClick={saveEditAddr} disabled={loading}>Simpan</button>
                          <button className="btn btn-ghost btn-sm" onClick={() => setEditingAddr(null)}>Batal</button>
                        </div>
                      </div>
                    ) : (
                      <div style={{padding:'16px',display:'flex',justifyContent:'space-between',alignItems:'flex-start',gap:12}}>
                        <div>
                          <div style={{fontWeight:500,fontSize:14,marginBottom:4}}>{addr.label || 'Alamat'}</div>
                          <div style={{fontSize:13,color:'var(--ink-soft)'}}>{addr.street}</div>
                          <div style={{fontSize:13,color:'var(--ink-meta)'}}>{addr.city}{addr.province ? ', '+addr.province : ''} {addr.postal_code}</div>
                        </div>
                        <div style={{display:'flex',gap:4,flexShrink:0}}>
                          <button
                            onClick={() => { setEditingAddr(addr.id); setEditAddrForm(addr); }}
                            style={{background:'none',border:'1px solid var(--paper-card-edge)',cursor:'pointer',color:'var(--ink-soft)',padding:'4px 8px',fontSize:11,fontFamily:'var(--font-sans)'}}
                          >Edit</button>
                          <button onClick={() => deleteAddress(addr.id)}
                            style={{background:'none',border:'none',cursor:'pointer',color:'var(--ink-faint)',padding:4}}
                            title="Hapus"><Icon.X /></button>
                        </div>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </main>
  );
}

window.ProfilePage = ProfilePage;
