'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import Navbar from '@/components/Navbar'

export default function ProfilePage() {
  const { data: session } = useSession()
  const [loading, setLoading] = useState(false)
  const [profile, setProfile] = useState<any>(null)
  
  const [whatsappNumber, setWhatsappNumber] = useState('')
  const [telegramId, setTelegramId] = useState('')
  const [message, setMessage] = useState({ text: '', type: '' })

  useEffect(() => {
    if (session?.user?.id) {
      fetch('/api/user/profile')
        .then(res => res.json())
        .then(data => {
          if (data.user) {
            setProfile(data.user)
            setWhatsappNumber(data.user.whatsappNumber || '')
            setTelegramId(data.user.telegramId || '')
          }
        })
        .catch(console.error)
    }
  }, [session])

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setMessage({ text: '', type: '' })

    try {
      const res = await fetch('/api/user/profile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ whatsappNumber, telegramId })
      })
      const data = await res.json()
      
      if (!res.ok) throw new Error(data.error || 'Gagal menyimpan profil')
      
      setMessage({ text: 'Profil berhasil diperbarui!', type: 'success' })
    } catch (err: any) {
      setMessage({ text: err.message, type: 'error' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <main style={{ minHeight: '100vh', background: '#0a0a0f', display: 'flex', flexDirection: 'column' }}>
      <Navbar />
      <div style={{ paddingTop: '80px', maxWidth: '800px', margin: '0 auto', padding: '80px 24px 60px', width: '100%' }}>
        <h1 className="font-game" style={{ fontSize: '28px', fontWeight: 700, color: '#f1f5f9', marginBottom: '8px' }}>
          👤 Pengaturan Profil
        </h1>
        <p style={{ color: '#64748b', marginBottom: '32px' }}>Atur pengaitan akun untuk menerima notifikasi pesanan otomatis.</p>

        <form onSubmit={handleSave} className="card" style={{ padding: '32px' }}>
          {message.text && (
            <div style={{ padding: '12px', borderRadius: '8px', marginBottom: '24px', fontSize: '14px', background: message.type === 'error' ? 'rgba(239,68,68,0.1)' : 'rgba(16,185,129,0.1)', color: message.type === 'error' ? '#ef4444' : '#10b981', border: `1px solid ${message.type === 'error' ? 'rgba(239,68,68,0.2)' : 'rgba(16,185,129,0.2)'}` }}>
              {message.text}
            </div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
            <div>
              <label className="label">Nama Lengkap</label>
              <input className="input" value={profile?.name || ''} disabled style={{ opacity: 0.7 }} />
            </div>
            
            <div>
              <label className="label">Email Terdaftar</label>
              <input className="input" value={profile?.email || ''} disabled style={{ opacity: 0.7 }} />
              <div style={{ fontSize: '12px', color: '#64748b', marginTop: '6px' }}>Notifikasi email akan selalu dikirim ke alamat ini.</div>
            </div>

            <hr style={{ border: 'none', borderTop: '1px solid rgba(255,255,255,0.05)', margin: '10px 0' }} />
            
            <h3 style={{ color: '#f1f5f9', fontSize: '16px', margin: 0 }}>Pengaitan Platform Bot</h3>
            
            <div>
              <label className="label">Nomor WhatsApp</label>
              <input 
                className="input" 
                placeholder="Contoh: 6281234567890" 
                value={whatsappNumber} 
                onChange={e => setWhatsappNumber(e.target.value)} 
              />
              <div style={{ fontSize: '12px', color: '#64748b', marginTop: '6px' }}>Gunakan kode negara (62). Notifikasi sukses/gagal akan dikirim ke WA ini.</div>
            </div>

            <div>
              <label className="label">Telegram Chat ID</label>
              <input 
                className="input" 
                placeholder="Contoh: 123456789" 
                value={telegramId} 
                onChange={e => setTelegramId(e.target.value)} 
              />
              <div style={{ fontSize: '12px', color: '#64748b', marginTop: '6px' }}>
                Masukkan Chat ID Telegram Anda. Anda juga bisa menautkan secara otomatis nanti.
              </div>
            </div>

            <button type="submit" className="btn btn-primary" disabled={loading} style={{ marginTop: '10px' }}>
              {loading ? 'Menyimpan...' : 'Simpan Profil'}
            </button>
          </div>
        </form>
      </div>
    </main>
  )
}
