import React from 'react'
import TeacherUploadModal from '../components/TeacherUploadModal'
import { sfx } from '../utils/audio'
import { toast, reward } from '../components/Toasts'
import { getRole, getUser } from '../utils/storage'


import { useColorBlindness } from '../context/ColorBlindnessContext'

function ColorBlindnessToggle() {
  const { isEnabled, setIsEnabled, type } = useColorBlindness()

  if (type === 'none') return <span className="text-xs text-slate-400">Normal</span>

  return (
    <button
      onClick={() => setIsEnabled(!isEnabled)}
      className={`relative w-12 h-6 rounded-full transition-colors ${isEnabled ? 'bg-indigo-500' : 'bg-slate-300'}`}
    >
      <div className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full shadow transition-transform ${isEnabled ? 'translate-x-6' : 'translate-x-0'}`} />
    </button>
  )
}

export default function Profile() {
  const [role] = React.useState(() => getRole() || 'student')
  const [user, setUser] = React.useState(getUser() || {})
  const [profile, setProfile] = React.useState({})
  const [loading, setLoading] = React.useState(true)
  const [editing, setEditing] = React.useState(false)
  const [open, setOpen] = React.useState(false)
  const { type, setType, setIsEnabled } = useColorBlindness()

  // Form states
  const [birthday, setBirthday] = React.useState('')
  const [gender, setGender] = React.useState('')
  const [socials, setSocials] = React.useState({ tiktok: '', instagram: '', facebook: '' })

  React.useEffect(() => {
    if (user.id) {
      fetch(`http://localhost/landingpage1/lomba/user.php?id=${user.id}`)
        .then(res => res.json())
        .then(data => {
          setProfile(data)
          setBirthday(data.birthday || '')
          setGender(data.gender || '')
          try {
            const s = JSON.parse(data.social_networks || '{}')
            setSocials({ tiktok: s.tiktok || '', instagram: s.instagram || '', facebook: s.facebook || '' })
          } catch { }
          setLoading(false)
        })
    }
  }, [user.id])

  const handleSave = async () => {
    try {
      const res = await fetch('http://localhost/landingpage1/lomba/user.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          id: user.id,
          birthday,
          gender,
          social_networks: socials
        })
      })
      if (res.ok) {
        toast('Profil diperbarui!', 'success')
        setEditing(false)
        setProfile({ ...profile, birthday, gender, social_networks: JSON.stringify(socials) })
      }
    } catch { toast('Gagal menyimpan', 'error') }
  }

  return (
    <div className="grid md:grid-cols-3 gap-6">
      <section className="bg-white rounded-3xl p-6 shadow-lg border border-slate-100">
        <div className="text-center mb-6">
          <div className="w-24 h-24 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-full mx-auto mb-4 flex items-center justify-center text-4xl text-white font-bold shadow-lg">
            {profile.name?.charAt(0) || user.name?.charAt(0)}
          </div>
          <h1 className="heading text-2xl text-slate-800">{profile.name || user.name}</h1>
          <p className="text-slate-500 text-sm">@{profile.username || 'username'}</p>
          <div className="mt-2 inline-block px-3 py-1 bg-indigo-50 text-indigo-600 rounded-full text-xs font-bold uppercase tracking-wider">
            {role === 'admin' ? 'Guru SD' : 'Siswa SD'}
          </div>
        </div>

        <div className="space-y-3 border-t pt-4">
          <div className="flex justify-between items-center">
            <span className="text-slate-500 font-medium">Streak</span>
            <span className="font-bold text-orange-500">🔥 {profile.streak_count || 0} Hari</span>
          </div>
          <div className="flex justify-between items-center">
            <span className="text-slate-500 font-medium">XP</span>
            <span className="font-bold text-yellow-500">⭐ 1,250</span>
          </div>
        </div>

        <div className="mt-6 border-t pt-4">
          <h3 className="font-bold text-slate-700 mb-2">Aksesibilitas</h3>
          <button
            onClick={() => {
              sfx.play('click')
              window.dispatchEvent(new Event('kk_color_test_retest'))
            }}
            className="w-full bg-slate-100 text-slate-600 font-bold py-3 rounded-xl hover:bg-slate-200 transition-colors flex items-center justify-center gap-2"
          >
            <span>👁️</span> Tes Ulang Mata Elang
          </button>

          {/* Color Blindness Mode Toggle */}
          <div className="mt-4 w-full py-3 px-4 bg-slate-50 border border-slate-200 rounded-xl">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-3">
                <span className="text-xl">🎨</span>
                <div className="flex flex-col text-left">
                  <span className="font-bold text-slate-700 text-sm">Mode Buta Warna</span>
                  <span className="text-xs text-slate-500">Sesuaikan profil warna Anda</span>
                </div>
              </div>
              <ColorBlindnessToggle />
            </div>

            <div className="mt-2 pl-10">
              <select
                value={type}
                onChange={(e) => {
                  const val = e.target.value;
                  setType(val);
                  // If user selects a type other than none, auto-enable
                  if (val !== 'none') setIsEnabled(true);
                  else setIsEnabled(false);
                }}
                className="w-full text-sm border-2 border-slate-200 rounded-lg p-2 bg-white outline-none focus:border-indigo-500"
              >
                <option value="none">Normal (Tidak ada filter)</option>
                <option value="protanopia">Protanopia (Merah total)</option>
                <option value="protanomaly">Protanomaly (Merah sebagian)</option>
                <option value="deuteranopia">Deuteranopia (Hijau total)</option>
                <option value="deuteranomaly">Deuteranomaly (Hijau sebagian)</option>
                <option value="tritanopia">Tritanopia (Biru total)</option>
                <option value="tritanomaly">Tritanomaly (Biru sebagian)</option>
                <option value="achromatopsia">Achromatopsia (Total)</option>
              </select>
            </div>
          </div>
        </div>

        {role === 'admin' && (
          <button onClick={() => { setOpen(true); sfx.play('click') }} className="w-full mt-6 bg-indigo-600 text-white font-bold py-3 rounded-xl hover:bg-indigo-700 transition-colors shadow-md">
            Upload Materi
          </button>
        )}
      </section>

      <section className="md:col-span-2 bg-white rounded-3xl p-6 shadow-lg border border-slate-100">
        <div className="flex justify-between items-center mb-6">
          <h2 className="heading text-xl text-slate-800">Data Diri</h2>
          <button
            onClick={() => editing ? handleSave() : setEditing(true)}
            className={`px-4 py-2 rounded-full font-bold text-sm transition-colors ${editing ? 'bg-green-500 text-white hover:bg-green-600' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}
          >
            {editing ? 'Simpan' : 'Edit Profil'}
          </button>
        </div>

        <div className="grid md:grid-cols-2 gap-6">
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Tanggal Lahir</label>
              {editing ? (
                <input type="date" value={birthday} onChange={e => setBirthday(e.target.value)} className="w-full border-2 border-slate-200 rounded-lg p-2 outline-none focus:border-indigo-500" />
              ) : (
                <p className="font-medium text-slate-700">{birthday || '-'}</p>
              )}
            </div>
            <div>
              <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">Jenis Kelamin</label>
              {editing ? (
                <select value={gender} onChange={e => setGender(e.target.value)} className="w-full border-2 border-slate-200 rounded-lg p-2 outline-none focus:border-indigo-500">
                  <option value="">Pilih...</option>
                  <option value="L">Laki-laki</option>
                  <option value="P">Perempuan</option>
                </select>
              ) : (
                <p className="font-medium text-slate-700">{gender === 'L' ? 'Laki-laki' : gender === 'P' ? 'Perempuan' : '-'}</p>
              )}
            </div>
          </div>

          <div className="space-y-4">
            <h3 className="font-bold text-slate-700 border-b pb-2">Social Networks</h3>
            <div className="flex items-center gap-3">
              <span className="w-8 text-xl">🎵</span>
              {editing ? (
                <input value={socials.tiktok} onChange={e => setSocials({ ...socials, tiktok: e.target.value })} placeholder="TikTok Username" className="flex-1 border-2 border-slate-200 rounded-lg p-2 text-sm" />
              ) : (
                <span className="text-slate-600">{socials.tiktok || '-'}</span>
              )}
            </div>
            <div className="flex items-center gap-3">
              <span className="w-8 text-xl">📸</span>
              {editing ? (
                <input value={socials.instagram} onChange={e => setSocials({ ...socials, instagram: e.target.value })} placeholder="Instagram Username" className="flex-1 border-2 border-slate-200 rounded-lg p-2 text-sm" />
              ) : (
                <span className="text-slate-600">{socials.instagram || '-'}</span>
              )}
            </div>
            <div className="flex items-center gap-3">
              <span className="w-8 text-xl">📘</span>
              {editing ? (
                <input value={socials.facebook} onChange={e => setSocials({ ...socials, facebook: e.target.value })} placeholder="Facebook Username" className="flex-1 border-2 border-slate-200 rounded-lg p-2 text-sm" />
              ) : (
                <span className="text-slate-600">{socials.facebook || '-'}</span>
              )}
            </div>
          </div>
        </div>
      </section>
      <TeacherUploadModal open={open} onClose={() => setOpen(false)} />
    </div>
  )
}
