import React, { useState } from 'react';
import toast from 'react-hot-toast';
import { ArrowLeft, Shield, Eye, EyeOff, Save, RotateCcw } from 'lucide-react';
import { changePassword } from '../api';

function passwordStrength(pw) {
  if (!pw) return { score: 0, label: '', color: '' };
  let score = 0;
  if (pw.length >= 6) score++;
  if (pw.length >= 10) score++;
  if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) score++;
  if (/[0-9]/.test(pw)) score++;
  if (/[^A-Za-z0-9]/.test(pw)) score++;

  if (score <= 1) return { score: 1, label: 'Lemah', color: 'var(--danger)' };
  if (score <= 2) return { score: 2, label: 'Sedang', color: 'var(--warning)' };
  if (score <= 3) return { score: 3, label: 'Baik', color: 'var(--accent)' };
  return { score: 4, label: 'Kuat', color: 'var(--success)' };
}

export default function Settings({ onLogout, navigate }) {
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [loading, setLoading] = useState(false);

  const strength = passwordStrength(newPassword);
  const match = confirmPassword && newPassword === confirmPassword;
  const mismatch = confirmPassword && newPassword !== confirmPassword;

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!currentPassword || !newPassword) {
      toast.error('Semua kolom wajib diisi.');
      return;
    }
    if (newPassword.length < 6) {
      toast.error('Kata sandi baru minimal 6 karakter.');
      return;
    }
    if (newPassword !== confirmPassword) {
      toast.error('Konfirmasi tidak cocok.');
      return;
    }
    setLoading(true);
    try {
      await changePassword(currentPassword, newPassword);
      toast.success('Kata sandi berhasil diubah!');
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
    } catch (err) {
      toast.error(err.response?.data?.error?.message || 'Gagal mengubah kata sandi.');
    } finally {
      setLoading(false);
    }
  };

  const clearForm = () => {
    setCurrentPassword('');
    setNewPassword('');
    setConfirmPassword('');
  };

  return (
    <div className="flex flex-col h-full gap-2 min-h-0">
      <div className="flex-shrink-0">
        <button onClick={() => navigate('/app')} className="btn btn-secondary btn-sm">
          <ArrowLeft size={16} /> Kembali
        </button>
      </div>

      <div className="window-card flex-1 flex flex-col min-h-0 mx-auto w-full" style={{ maxWidth: 520 }}>
        <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">🔒 Keamanan — Ganti Kata Sandi</div>
        </div>

        <div className="flex-1 overflow-y-auto min-h-0">
          <div className="window-body">
            <div className="flex items-start gap-4 mb-6">
              <div
                className="rounded-xl p-3 flex-shrink-0"
                style={{
                  background: 'var(--accent-soft)',
                  border: '2.5px solid var(--border-soft)',
                  boxShadow: 'var(--shadow-btn)'
                }}
              >
                <Shield size={28} style={{ color: 'var(--accent)' }} />
              </div>
              <div>
                <p className="font-bold text-base mb-1">Perbarui Kata Sandi</p>
                <p className="text-sm" style={{ color: 'var(--ink-muted)' }}>
                  Ganti kata sandi akun untuk keamanan lebih baik.
                </p>
              </div>
            </div>

            <div style={{ height: 1.5, background: 'var(--border-faint)', marginBottom: 20 }} />

            <form onSubmit={handleSubmit}>
              <div className="mb-4">
                <label className="block text-sm font-bold mb-2" style={{ color: 'var(--ink-secondary)' }}>
                  Kata sandi saat ini
                </label>
                <div className="relative">
                  <input
                    type={showCurrent ? 'text' : 'password'}
                    value={currentPassword}
                    onChange={(e) => setCurrentPassword(e.target.value)}
                    className="input"
                    style={{ paddingRight: 48 }}
                    placeholder="••••••"
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowCurrent(!showCurrent)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 btn btn-ghost btn-icon"
                    style={{ minWidth: 36, minHeight: 36 }}
                    tabIndex={-1}
                  >
                    {showCurrent ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
              </div>

              <div className="mb-4">
                <label className="block text-sm font-bold mb-2" style={{ color: 'var(--ink-secondary)' }}>
                  Kata sandi baru
                </label>
                <div className="relative">
                  <input
                    type={showNew ? 'text' : 'password'}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="input"
                    style={{ paddingRight: 48 }}
                    placeholder="Minimal 6 karakter"
                    autoComplete="new-password"
                  />
                  <button
                    type="button"
                    onClick={() => setShowNew(!showNew)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 btn btn-ghost btn-icon"
                    style={{ minWidth: 36, minHeight: 36 }}
                    tabIndex={-1}
                  >
                    {showNew ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>

                {newPassword && (
                  <div className="mt-2">
                    <div className="flex gap-1" style={{ height: 6 }}>
                      {[1, 2, 3, 4].map(i => (
                        <div
                          key={i}
                          className="flex-1 rounded-full"
                          style={{
                            background: i <= strength.score ? strength.color : 'var(--border-faint)',
                            border: '1.5px solid var(--border-soft)',
                            transition: 'background 0.2s',
                          }}
                        />
                      ))}
                    </div>
                    <p className="text-xs mt-1 font-semibold" style={{ color: strength.color }}>
                      {strength.label}
                    </p>
                  </div>
                )}
              </div>

              <div className="mb-6">
                <label className="block text-sm font-bold mb-2" style={{ color: 'var(--ink-secondary)' }}>
                  Konfirmasi kata sandi baru
                </label>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="input"
                  placeholder="Ulangi kata sandi baru"
                  autoComplete="new-password"
                />
                {match && (
                  <p className="text-xs mt-1 font-semibold" style={{ color: 'var(--success)' }}>
                    ✅ Cocok
                  </p>
                )}
                {mismatch && (
                  <p className="text-xs mt-1 font-semibold" style={{ color: 'var(--danger)' }}>
                    ❌ Tidak cocok
                  </p>
                )}
              </div>

              <div className="flex justify-end gap-3">
                <button type="button" onClick={clearForm} className="btn btn-secondary">
                  <RotateCcw size={16} /> Bersihkan
                </button>
                <button
                  type="submit"
                  disabled={loading || !currentPassword || !newPassword || !confirmPassword || mismatch}
                  className="btn btn-primary"
                >
                  {loading ? '⏳ Menyimpan...' : <><Save size={16} /> Simpan</>}
                </button>
              </div>
            </form>
          </div>
        </div>

        <div
          className="px-5 py-2.5 flex-shrink-0"
          style={{
            fontSize: 12,
            color: 'var(--ink-muted)',
            borderTop: '1.5px dashed var(--border-faint)',
            background: 'var(--panel-alt)',
            textAlign: 'center'
          }}
        >
          ✦ Pengaturan keamanan akun ✦
        </div>
      </div>
    </div>
  );
}
