'use client';

import { useState } from 'react';
import PortalLayout from '@/app/layout-portal';
import { useAuth } from '@/lib/auth';
import { useNotify } from '@/lib/notifications';
import { useRouter } from 'next/navigation';
import {
  User, Lock, LogOut, Save, Loader2, AlertTriangle, CheckCircle, Eye, EyeOff,
} from 'lucide-react';

export default function ProfilePage() {
  const { user, logout, isAdmin } = useAuth();
  const { notify } = useNotify();
  const router = useRouter();

  const [currentPass, setCurrentPass] = useState('');
  const [newPass, setNewPass] = useState('');
  const [confirmPass, setConfirmPass] = useState('');
  const [showPasswords, setShowPasswords] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function handleChangePassword(e: React.FormEvent) {
    e.preventDefault();
    setError('');

    if (!currentPass || !newPass || !confirmPass) {
      setError('Vul alle wachtwoordvelden in');
      return;
    }
    if (newPass.length < 6) {
      setError('Nieuw wachtwoord moet minimaal 6 tekens zijn');
      return;
    }
    if (newPass !== confirmPass) {
      setError('Nieuwe wachtwoorden komen niet overeen');
      return;
    }

    setBusy(true);
    try {
      const res = await fetch('/api/auth/password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ address: user?.address, currentPassword: currentPass, newPassword: newPass }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Wachtwoord wijzigen mislukt');
      }
      notify({ type: 'success', title: 'Wachtwoord gewijzigd' });
      setCurrentPass('');
      setNewPass('');
      setConfirmPass('');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setBusy(false);
    }
  }

  async function handleLogout() {
    await logout();
    notify({ type: 'info', title: 'Uitgelogd' });
    router.push('/login');
  }

  return (
    <PortalLayout>
      {/* ── Header ── */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-white">Profiel</h1>
          <p className="text-sm text-surface-400 mt-1">Je accountinstellingen</p>
        </div>
        <button onClick={handleLogout}
          className="flex items-center gap-2 px-4 py-2 rounded-xl bg-accent-rose/10 text-accent-rose text-sm font-medium hover:bg-accent-rose/20 transition-colors">
          <LogOut className="w-4 h-4" />
          Uitloggen
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* ── Account info ── */}
        <div className="lg:col-span-1">
          <div className="glass rounded-xl p-5 space-y-4">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-brand-500 to-accent-purple flex items-center justify-center text-lg font-bold text-white">
                {user?.address?.charAt(2).toUpperCase() || '?'}
              </div>
              <div>
                <div className="text-sm font-semibold text-white font-mono">{user?.address ? `${user.address.slice(0, 6)}...${user.address.slice(-4)}` : 'Onbekend'}</div>
                <div className="text-xs text-surface-500">
                  {isAdmin ? 'Admin' : 'Gebruiker'}
                </div>
              </div>
            </div>

            <div className="pt-3 border-t border-surface-800 space-y-2">
              <div className="flex justify-between text-xs">
                <span className="text-surface-500">Rol</span>
                <span className={`font-medium ${isAdmin ? 'text-accent-amber' : 'text-surface-300'}`}>
                  {isAdmin ? 'Administrator' : 'User'}
                </span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-surface-500">Sessie</span>
                <span className="text-accent-green font-medium">Actief</span>
              </div>
            </div>
          </div>
        </div>

        {/* ── Wachtwoord wijzigen ── */}
        <div className="lg:col-span-2">
          <div className="glass rounded-xl p-5">
            <h2 className="text-sm font-semibold text-white mb-4 flex items-center gap-2">
              <Lock className="w-4 h-4 text-brand-400" />
              Wachtwoord wijzigen
            </h2>

            <form onSubmit={handleChangePassword} className="space-y-4 max-w-md">
              {error && (
                <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-accent-rose/10 text-accent-rose text-xs">
                  <AlertTriangle className="w-3.5 h-3.5 shrink-0" />
                  {error}
                </div>
              )}

              <div>
                <label className="text-xs text-surface-400 mb-1.5 block">Huidig wachtwoord</label>
                <input
                  value={currentPass} onChange={(e) => setCurrentPass(e.target.value)}
                  type={showPasswords ? 'text' : 'password'}
                  autoComplete="current-password"
                  className="w-full rounded-lg bg-surface-900 border border-surface-700 px-3 py-2 text-sm text-surface-200 placeholder:text-surface-500 focus:outline-none focus:border-brand-500 transition-colors"
                />
              </div>

              <div className="relative">
                <label className="text-xs text-surface-400 mb-1.5 block">Nieuw wachtwoord</label>
                <input
                  value={newPass} onChange={(e) => setNewPass(e.target.value)}
                  type={showPasswords ? 'text' : 'password'}
                  autoComplete="new-password"
                  placeholder="Minimaal 6 tekens"
                  className="w-full rounded-lg bg-surface-900 border border-surface-700 px-3 py-2 pr-10 text-sm text-surface-200 placeholder:text-surface-500 focus:outline-none focus:border-brand-500 transition-colors"
                />
              </div>

              <div>
                <label className="text-xs text-surface-400 mb-1.5 block">Bevestig nieuw wachtwoord</label>
                <input
                  value={confirmPass} onChange={(e) => setConfirmPass(e.target.value)}
                  type={showPasswords ? 'text' : 'password'}
                  autoComplete="new-password"
                  className="w-full rounded-lg bg-surface-900 border border-surface-700 px-3 py-2 text-sm text-surface-200 placeholder:text-surface-500 focus:outline-none focus:border-brand-500 transition-colors"
                />
              </div>

              {/* Toggle show passwords */}
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={showPasswords}
                  onChange={(e) => setShowPasswords(e.target.checked)}
                  className="rounded bg-surface-800 border-surface-600 text-brand-500 focus:ring-brand-500"
                />
                <span className="text-xs text-surface-500">Toon wachtwoorden</span>
              </label>

              <button type="submit" disabled={busy}
                className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-brand-600 hover:bg-brand-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium transition-colors"
              >
                {busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                {busy ? 'Bezig…' : 'Wachtwoord wijzigen'}
              </button>
            </form>
          </div>
        </div>
      </div>
    </PortalLayout>
  );
}
