import React, { useState } from 'react';
import toast from 'react-hot-toast';
import { Moon, Sun, Eye, EyeOff, LogIn, AlertTriangle } from 'lucide-react';
import { login, fetchCsrf } from '../api';

export default function Login({ onSuccess, theme, toggleTheme }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    if (!username.trim() || !password) {
      setError('Nama pengguna dan kata sandi wajib diisi.');
      return;
    }
    setLoading(true);
    try {
      await fetchCsrf();
      const res = await login(username.trim(), password);
      toast.success('Selamat datang!');
      onSuccess(res.data);
    } catch (err) {
      setError(err.response?.data?.error?.message || 'Gagal masuk. Periksa kembali kredensial Anda.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-full flex items-center justify-center p-6 relative">
      <span className="deco-sparkle" style={{ top: '10%', left: '8%', fontSize: 32 }}>✦</span>
      <span className="deco-sparkle" style={{ top: '20%', right: '10%', fontSize: 22 }}>✧</span>
      <span className="deco-sparkle" style={{ bottom: '15%', left: '15%', fontSize: 26 }}>⊹</span>
      <span className="deco-sparkle" style={{ bottom: '25%', right: '12%', fontSize: 20 }}>♡</span>

      <button
        onClick={toggleTheme}
        className="btn btn-sm btn-secondary fixed top-4 right-4 z-50"
        title={theme === 'midnight' ? 'Mode Terang' : 'Mode Gelap'}
      >
        {theme === 'midnight' ? <Sun size={16} /> : <Moon size={16} />}
      </button>

      <div className="w-full" style={{ maxWidth: 420 }}>
        <div className="window-card">
          <div className="window-header">
            <div className="window-dots">
              <div className="window-dot window-dot-red" />
              <div className="window-dot window-dot-yellow" />
              <div className="window-dot window-dot-green" />
            </div>
            <div className="window-title">🔐 Syamsu Files — Masuk</div>
          </div>

          <div className="window-body">
            <div className="text-center mb-6">
              <div
                className="inline-flex items-center justify-center rounded-xl mb-3"
                style={{
                  width: 72, height: 72,
                  background: 'var(--accent-soft)',
                  border: '2.5px solid var(--border-soft)',
                  boxShadow: 'var(--shadow-btn)',
                  fontSize: 36
                }}
              >
                📁
              </div>
              <h1 className="font-bold text-lg" style={{ color: 'var(--ink)' }}>Syamsu Files</h1>
              <p className="text-sm mt-1" style={{ color: 'var(--ink-muted)' }}>
                Masukkan kredensial untuk mengelola file Anda
              </p>
            </div>

            {error && (
              <div
                className="flex items-start gap-3 p-3 rounded-lg mb-4"
                style={{
                  background: 'var(--danger-bg)',
                  border: '2px solid var(--danger)',
                  fontSize: 14
                }}
              >
                <AlertTriangle size={18} style={{ color: 'var(--danger)', flexShrink: 0, marginTop: 1 }} />
                <span style={{ color: 'var(--danger)' }}>{error}</span>
              </div>
            )}

            <form onSubmit={handleSubmit}>
              <div className="mb-4">
                <label className="block text-sm font-bold mb-2" style={{ color: 'var(--ink-secondary)' }}>
                  Nama Pengguna
                </label>
                <input
                  type="text"
                  value={username}
                  onChange={(e) => { setUsername(e.target.value); setError(''); }}
                  className="input"
                  placeholder="admin"
                  autoComplete="username"
                  autoFocus
                />
              </div>

              <div className="mb-6">
                <label className="block text-sm font-bold mb-2" style={{ color: 'var(--ink-secondary)' }}>
                  Kata Sandi
                </label>
                <div className="relative">
                  <input
                    type={showPw ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => { setPassword(e.target.value); setError(''); }}
                    className="input"
                    style={{ paddingRight: 48 }}
                    placeholder="••••••"
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPw(!showPw)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 btn btn-ghost btn-icon"
                    style={{ minWidth: 36, minHeight: 36 }}
                    tabIndex={-1}
                  >
                    {showPw ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="btn btn-primary w-full"
                style={{ minHeight: 48, fontSize: 16 }}
              >
                {loading ? (
                  <><span className="animate-spin">⏳</span> Memproses...</>
                ) : (
                  <><LogIn size={18} /> Masuk</>
                )}
              </button>
            </form>
          </div>

          <div
            className="px-5 py-3 text-center"
            style={{
              fontSize: 12,
              color: 'var(--ink-muted)',
              borderTop: '1.5px dashed var(--border-faint)',
              background: 'var(--panel-alt)'
            }}
          >
            ✦ Penyimpanan file pribadi yang aman ✦
          </div>
        </div>
      </div>
    </div>
  );
}
