import React from 'react'

import { sfx } from '../utils/audio'
import CustomModal from '../components/CustomModal'

import { getUser } from '../utils/storage'

export default function Friends() {
  const [tab, setTab] = React.useState('friends') // 'friends' | 'requests'
  const [items, setItems] = React.useState([])
  const user = getUser()

  const fetchItems = async () => {
    if (!user?.id) return
    try {
      const type = tab === 'requests' ? 'requests' : 'friends'
      const res = await fetch(`http://localhost/landingpage1/lomba/friends.php?user_id=${user.id}&type=${type}`)
      const data = await res.json()
      if (Array.isArray(data)) setItems(data)
      else setItems([])
    } catch (e) { console.error(e); setItems([]) }
  }

  React.useEffect(() => { fetchItems() }, [tab])

  const [modal, setModal] = React.useState({ open: false, title: '', msg: '', type: 'alert', onConfirm: null })

  const showModal = (msg, title = 'Info') => {
    setModal({ open: true, title, msg, type: 'alert', onConfirm: () => setModal(m => ({ ...m, open: false })) })
  }

  const [showAdd, setShowAdd] = React.useState(false)
  const [addUsername, setAddUsername] = React.useState('')
  const [loading, setLoading] = React.useState(false)

  const addFriend = async (e) => {
    e.preventDefault()
    if (!addUsername.trim()) return
    setLoading(true)
    try {
      const res = await fetch('http://localhost/landingpage1/lomba/friends.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: user.id, username: addUsername, action: 'add' })
      })
      const data = await res.json()
      if (res.ok) {
        showModal(data.message, 'Berhasil')
        setAddUsername('')
        setShowAdd(false)
        sfx.play('success')
      } else {
        showModal(data.message, 'Gagal')
      }
    } catch (e) {
      showModal('Gagal menambah teman', 'Error')
    } finally {
      setLoading(false)
    }
  }

  const handleAction = async (requesterId, action) => {
    try {
      const res = await fetch('http://localhost/landingpage1/lomba/friends.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_id: user.id, requester_id: requesterId, action })
      })
      const data = await res.json()
      if (res.ok) {
        sfx.play('success')
        showModal(data.message, 'Berhasil')
        fetchItems()
      } else {
        showModal(data.message, 'Gagal')
      }
    } catch (e) { showModal('Action failed', 'Error') }
  }

  const TabBtn = ({ id, label }) => (
    <button
      onClick={() => { setTab(id); sfx.play('click') }}
      className={`ui px-4 py-2 rounded-lg font-semibold border-b-4 ${tab === id ? 'border-onme-blue text-onme-blue' : 'border-transparent text-gray-600 hover:text-onme-blue'}`}
      aria-current={tab === id ? 'page' : undefined}
    >
      {label}
    </button>
  )

  return (
    <section className="mt-3">
      <CustomModal
        isOpen={modal.open}
        title={modal.title}
        message={modal.msg}
        type={modal.type}
        onConfirm={modal.onConfirm}
        onCancel={() => setModal(m => ({ ...m, open: false }))}
      />

      <h1 className="heading text-3xl text-onme-blue mb-4">Teman & Request</h1>

      <div className="flex items-center justify-between gap-3 mb-4">
        <nav className="flex gap-3" aria-label="Tabs">
          <TabBtn id="friends" label="Teman Saya" />
          <TabBtn id="requests" label="Permintaan Teman" />
        </nav>
        <button
          onClick={() => setShowAdd(!showAdd)}
          className="text-sm font-bold text-indigo-600 bg-indigo-50 px-3 py-2 rounded-full hover:bg-indigo-100 transition-colors border-2 border-indigo-100"
        >
          {showAdd ? 'Batal' : '+ Tambah Teman'}
        </button>
      </div>

      {showAdd && (
        <form onSubmit={addFriend} className="mb-6 bg-white p-4 rounded-xl border-2 border-indigo-100 flex gap-2 max-w-md">
          <input
            value={addUsername}
            onChange={e => setAddUsername(e.target.value)}
            placeholder="Masukkan username teman..."
            className="flex-1 border-2 border-slate-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-indigo-500"
            required
          />
          <button disabled={loading} className="bg-indigo-600 text-white font-bold px-4 py-2 rounded-lg text-sm hover:bg-indigo-700 disabled:opacity-50">
            {loading ? '...' : 'Tambah'}
          </button>
        </form>
      )}

      <h2 className="ui font-bold text-gray-700 mb-2">
        {tab === 'friends' ? `Teman (${items.length})` : `Permintaan Masuk (${items.length})`}
      </h2>

      {items.length === 0 && (
        <div className="text-center py-10 bg-slate-50 rounded-xl border-2 border-dashed border-slate-200 text-slate-400">
          {tab === 'friends' ? 'Belum ada teman. Yuk cari teman baru!' : 'Tidak ada permintaan pertemanan.'}
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {items.map(it => (
          <article key={it.id} className="rounded-xl bg-white border-2 border-onme-softBlue p-4 flex items-center gap-4">
            <div className="h-14 w-14 rounded-full flex items-center justify-center text-white font-bold text-xl shadow-inner" style={{ background: it.color }}>
              {it.name.charAt(0).toUpperCase()}
            </div>
            <div className="flex-1">
              <p className="ui font-semibold">{it.name}</p>
              <p className="ui text-sm text-gray-500">{it.role === 'admin' ? 'Guru' : 'Siswa'}</p>
            </div>
            {tab === 'friends' ? (
              <button onClick={() => sfx.play('click')} className="ui text-sm rounded-full bg-onme-lime text-black font-bold px-3 py-1">Sapa 👋</button>
            ) : (
              <div className="flex gap-2">
                <button onClick={() => handleAction(it.id, 'accept')} className="ui text-sm rounded-full bg-onme-lime text-black font-bold px-3 py-1">Terima</button>
                <button onClick={() => handleAction(it.id, 'reject')} className="ui text-sm rounded-full bg-white border-2 border-onme-softBlue px-3 py-1 hover:bg-red-50 hover:text-red-600 hover:border-red-200">Tolak</button>
              </div>
            )}
          </article>
        ))}
      </div>
    </section>
  )
}
