'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import AdminLayout from '@/components/admin/AdminLayout';

export default function AdminProfilePage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [fullName, setFullName] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [photoFile, setPhotoFile] = useState<File | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [msg, setMsg] = useState('');
  const [msgType, setMsgType] = useState<'success' | 'error'>('success');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem('admin_token');
    if (!token) { router.push('/admin/login'); return; }
    fetchUser();
  }, [router]);

  const fetchUser = async () => {
    try {
      const token = localStorage.getItem('admin_token');
      const res = await fetch(`${apiUrl}/api/auth/me`, {
        headers: { 'Authorization': `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setUser(data);
        setFullName(data.fullName || '');
      } else {
        router.push('/admin/login');
      }
    } catch (e) { router.push('/admin/login'); }
    finally { setLoading(false); }
  };

  const validatePassword = (pwd: string) => {
    if (!pwd) return true;
    if (pwd.length < 8) return false;
    if (!/[A-Z]/.test(pwd)) return false;
    if (!/[0-9]/.test(pwd)) return false;
    if (!/[!@#$%^&*(),.?":{}|<>_\-]/.test(pwd)) return false;
    return true;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMsg('');
    setSaving(true);

    if (newPassword && newPassword !== confirmPassword) {
      setMsg('Konfirmasi password baru tidak sama dengan password baru'); setMsgType('error'); setSaving(false); return;
    }
    if (newPassword && !validatePassword(newPassword)) {
      setMsg('Password harus minimal 8 karakter, kombinasi huruf besar, angka, dan simbol'); setMsgType('error'); setSaving(false); return;
    }

    const fd = new FormData();
    fd.append('fullName', fullName);
    if (newPassword) fd.append('newPassword', newPassword);
    if (photoFile) fd.append('photo', photoFile);

    try {
      const token = localStorage.getItem('admin_token');
      const res = await fetch(`${apiUrl}/api/auth/profile`, {
        method: 'PUT',
        headers: { 'Authorization': `Bearer ${token}` },
        body: fd,
      });
      const data = await res.json();
      if (res.ok) {
        setMsg('Profil berhasil diupdate!');
        setMsgType('success');
        setNewPassword('');
        setConfirmPassword('');
        setPhotoFile(null);
        setPhotoPreview(null);
        fetchUser();
      } else {
        setMsg(data.message || 'Gagal update profil');
        setMsgType('error');
      }
    } catch (e) {
      setMsg('Gagal update profil');
      setMsgType('error');
    }
    finally { setSaving(false); }
  };

  if (loading) return <AdminLayout title="Profil Saya"><p className="text-gray-400">Memuat...</p></AdminLayout>;
  if (!user) return null;

  const userInitial = (user.fullName || user.username || 'A').charAt(0).toUpperCase();

  return (
    <AdminLayout title="Profil Saya">
      <div className="max-w-2xl mx-auto space-y-6">
        {/* Card Profile Info */}
        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          <div className="h-24 bg-gradient-to-r from-gold/30 to-gold/10"></div>
          <div className="px-6 pb-6 -mt-12">
            <div className="flex items-end gap-5">
              <div className="w-20 h-20 rounded-full overflow-hidden border-4 border-white shadow-md bg-gray-100">
                {user.photo ? (
                  <img src={user.photo} className="w-full h-full object-cover" />
                ) : (
                  <span className="flex items-center justify-center w-full h-full text-2xl font-bold text-gold bg-gold/10">{userInitial}</span>
                )}
              </div>
              <div className="pb-1">
                <h2 className="text-xl font-bold text-gray-800">{user.fullName || user.username}</h2>
                <p className="text-sm text-gray-500 capitalize">@{user.username} · {user.role}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Edit Form */}
        <div className="bg-white rounded-xl border border-gray-200 p-6">
          <h3 className="font-semibold text-gray-800 mb-5">Edit Profil</h3>

          {msg && (
            <div className={`p-3 rounded-lg text-sm flex items-center gap-2 mb-4 ${msgType === 'success' ? 'bg-green-50 border border-green-100 text-green-600' : 'bg-red-50 border border-red-100 text-red-600'}`}>
              <span>{msgType === 'success' ? '✅' : '❌'}</span>{msg}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-lg">
              <div>
                <label className="admin-label">Username</label>
                <input type="text" value={user.username} disabled
                  className="admin-input bg-gray-50 text-gray-500 cursor-not-allowed" />
                <p className="text-xs text-gray-400 mt-1">Tidak dapat diubah</p>
              </div>
            </div>

            <div>
              <label className="admin-label">Nama Lengkap</label>
              <input type="text" value={fullName} onChange={(e) => setFullName(e.target.value)}
                className="admin-input max-w-md" placeholder="Nama lengkap Anda" />
            </div>

            <div>
              <label className="admin-label">Role</label>
              <input type="text" value={user.role || ''} disabled
                className="admin-input max-w-md bg-gray-50 text-gray-500 capitalize cursor-not-allowed" />
            </div>

            <div>
              <label className="admin-label">Foto Profil (max 5MB)</label>
              <label className="inline-flex items-center gap-2 px-4 py-2 bg-gold text-white text-xs font-semibold rounded-lg cursor-pointer hover:bg-gold-dark transition">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                Pilih Foto
                <input type="file" accept="image/*" onChange={(e) => {
                  const f = e.target.files?.[0];
                  if (f) { setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); }
                }} className="hidden" />
              </label>
              {photoPreview && (
                <div className="mt-3 flex items-center gap-3">
                  <img src={photoPreview} className="w-16 h-16 rounded-full object-cover border" />
                  <span className="text-xs text-gray-400">Foto baru</span>
                </div>
              )}
              {user.photo && !photoPreview && (
                <p className="text-xs text-gray-400 mt-2">Foto saat ini: <span className="text-gray-500">{user.photo.split('/').pop()}</span></p>
              )}
            </div>

            <hr className="border-gray-100" />

            <div>
              <p className="text-sm font-medium text-gray-600 mb-3">🔑 Ganti Password (opsional)</p>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-lg">
                <div>
                  <label className="admin-label">Password Baru</label>
                  <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)}
                    className="admin-input" placeholder="Min 8 karakter" />
                  <p className="text-xs text-gray-400 mt-1.5 flex items-center gap-1">
                    <span className={newPassword && newPassword.length >= 8 ? 'text-green-500' : 'text-gray-400'}>✓ 8+ karakter</span>
                    <span className="text-gray-300">·</span>
                    <span className={/[A-Z]/.test(newPassword) ? 'text-green-500' : 'text-gray-400'}>✓ Huruf besar</span>
                    <span className="text-gray-300">·</span>
                    <span className={/[0-9]/.test(newPassword) ? 'text-green-500' : 'text-gray-400'}>✓ Angka</span>
                    <span className="text-gray-300">·</span>
                    <span className={/[!@#$%^&*(),.?":{}|<>_\-]/.test(newPassword) ? 'text-green-500' : 'text-gray-400'}>✓ Simbol</span>
                  </p>
                </div>
                <div>
                  <label className="admin-label">Konfirmasi Password</label>
                  <input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)}
                    className="admin-input" placeholder="Ulangi password" />
                  {confirmPassword && newPassword !== confirmPassword && (
                    <p className="text-xs text-red-500 mt-1">❌ Password tidak sama</p>
                  )}
                  {confirmPassword && newPassword === confirmPassword && (
                    <p className="text-xs text-green-500 mt-1">✅ Password sama</p>
                  )}
                </div>
              </div>
            </div>

            <div className="flex gap-3 justify-end pt-3 border-t border-gray-100">
              <button type="submit" disabled={saving}
                className="px-6 py-2.5 bg-gold hover:bg-gold-dark text-white text-sm font-semibold rounded-lg transition disabled:opacity-50">
                {saving ? 'Menyimpan...' : 'Simpan Perubahan'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </AdminLayout>
  );
}
