import { useState } from 'react'
import { useAuthStore } from '@/store/auth-store'
import { supabase } from '@/lib/supabase'
import { cn } from '@/lib/utils'

export function ProfileCard() {
  const user = useAuthStore((s) => s.user)
  const [editingName, setEditingName] = useState(false)
  const [editingEmail, setEditingEmail] = useState(false)
  const [nameInput, setNameInput] = useState(user?.name ?? '')
  const [emailInput, setEmailInput] = useState(user?.email ?? '')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  async function saveName() {
    if (!nameInput.trim()) return
    setSaving(true)
    setError('')
    try {
      const { error: err } = await supabase.auth.updateUser({ data: { name: nameInput.trim() } })
      if (err) throw err
      setEditingName(false)
    } catch {
      setError('Không thể lưu tên. Thử lại sau.')
    } finally {
      setSaving(false)
    }
  }

  async function saveEmail() {
    if (!emailInput.trim()) return
    setSaving(true)
    setError('')
    try {
      const { error: err } = await supabase.auth.updateUser({ email: emailInput.trim() })
      if (err) throw err
      setEditingEmail(false)
    } catch {
      setError('Không thể lưu email. Thử lại sau.')
    } finally {
      setSaving(false)
    }
  }

  const initials = (user?.name ?? 'U').charAt(0).toUpperCase()

  return (
    <section className="col-span-12 md:col-span-8 bg-white rounded-xl p-6 shadow-sm">
      <h2 className="text-lg font-bold mb-5 flex items-center gap-2 text-slate-800">
        <span className="material-symbols-outlined text-blue-600" style={{ fontSize: 22 }}>person</span>
        Hồ sơ cá nhân
      </h2>

      <div className="flex items-center gap-6">
        {/* Avatar */}
        <div className="relative flex-shrink-0">
          <div className="w-20 h-20 rounded-full bg-blue-600 flex items-center justify-center text-white text-2xl font-bold">
            {initials}
          </div>
        </div>

        {/* Fields */}
        <div className="flex-1 space-y-3">
          {/* Name */}
          <div className="flex items-center justify-between py-2 border-b border-slate-100">
            <div className="flex-1">
              <p className="text-xs text-slate-400 font-semibold uppercase tracking-wider">Họ và tên</p>
              {editingName ? (
                <input
                  autoFocus
                  value={nameInput}
                  onChange={(e) => setNameInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') setEditingName(false) }}
                  className="mt-0.5 text-base font-semibold w-full border border-blue-300 rounded-lg px-2 py-0.5 outline-none focus:ring-2 focus:ring-blue-200"
                />
              ) : (
                <p className="text-base font-semibold text-slate-800 mt-0.5">{user?.name ?? '—'}</p>
              )}
            </div>
            {editingName ? (
              <div className="flex gap-2 ml-3">
                <button onClick={saveName} disabled={saving} className={cn('text-blue-600 font-bold text-sm', saving && 'opacity-50')}>
                  {saving ? 'Lưu...' : 'Lưu'}
                </button>
                <button onClick={() => setEditingName(false)} className="text-slate-400 text-sm">Huỷ</button>
              </div>
            ) : (
              <button onClick={() => setEditingName(true)} className="ml-3 text-blue-600 font-bold text-sm hover:underline">Chỉnh sửa</button>
            )}
          </div>

          {/* Email */}
          <div className="flex items-center justify-between py-2">
            <div className="flex-1">
              <p className="text-xs text-slate-400 font-semibold uppercase tracking-wider">Email</p>
              {editingEmail ? (
                <input
                  autoFocus
                  type="email"
                  value={emailInput}
                  onChange={(e) => setEmailInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === 'Enter') saveEmail(); if (e.key === 'Escape') setEditingEmail(false) }}
                  className="mt-0.5 text-base font-semibold w-full border border-blue-300 rounded-lg px-2 py-0.5 outline-none focus:ring-2 focus:ring-blue-200"
                />
              ) : (
                <p className="text-base font-semibold text-slate-800 mt-0.5">{user?.email ?? '—'}</p>
              )}
            </div>
            {editingEmail ? (
              <div className="flex gap-2 ml-3">
                <button onClick={saveEmail} disabled={saving} className={cn('text-blue-600 font-bold text-sm', saving && 'opacity-50')}>
                  {saving ? 'Lưu...' : 'Lưu'}
                </button>
                <button onClick={() => setEditingEmail(false)} className="text-slate-400 text-sm">Huỷ</button>
              </div>
            ) : (
              <button onClick={() => setEditingEmail(true)} className="ml-3 text-blue-600 font-bold text-sm hover:underline">Chỉnh sửa</button>
            )}
          </div>
        </div>
      </div>

      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}
    </section>
  )
}
