import React, { useEffect, useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { loginWithPin } from '../api';

export default function PinLoginPage() {
  const [pin, setPin] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const maskChar = '•';
  const masked = pin.length ? maskChar.repeat(pin.length) : '\u00A0';

  const push = (d) => {
    if (loading) return;
    setError('');
    setPin((p) => (p.length < 6 ? p + d : p));
  };
  const backspace = () => !loading && setPin((p) => p.slice(0, -1));
  const reset = () => { if (!loading) { setPin(''); setError(''); } };

  const submit = async () => {
    if (pin.length !== 6) { setError('PIN muss 6 Ziffern haben'); return; }
    setLoading(true);
    try {
      const user = await loginWithPin(pin);
      setPin('');
      // Sofort navigieren; Order lädt parallel alle Daten (Promise.all)
      navigate('/order', { replace: true, state: { user } });
    } catch (e) {
      setError(e.message || 'Login fehlgeschlagen');
    } finally { setLoading(false); }
  };

  useEffect(() => {
    const onKey = (e) => {
      if (/^[0-9]$/.test(e.key)) push(e.key);
      else if (e.key === 'Backspace') backspace();
      else if (e.key === 'Enter') submit();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pin, loading]);

  return (
    <div
      className="relative min-h-screen w-full flex items-start md:items-center justify-center
                 bg-gradient-to-br from-[#000F2E] via-[#00246C] to-[#002D86] p-6 md:p-10"
    >
      {/* Management-Link oben rechts */}
      <Link
        to="/management-login"
        title="Management-Login"
        className="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors"
        aria-label="Zum Management-Login"
      >
        {/* kleines Zahnrad als Inline-SVG */}
        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" width="26" height="26">
          <path d="M19.14,12.94a7.14,7.14,0,0,0,.05-.94,7.14,7.14,0,0,0-.05-.94l2.11-1.65a.48.48,0,0,0,.12-.61l-2-3.46a.48.48,0,0,0-.58-.21l-2.49,1a6.77,6.77,0,0,0-1.63-.94l-.38-2.65A.49.49,0,0,0,14.67,2H9.33a.49.49,0,0,0-.48.4l-.38,2.65a6.77,6.77,0,0,0-1.63.94l-2.49-1a.48.48,0,0,0-.58.21l-2,3.46a.48.48,0,0,0,.12.61L4,11.06a7.14,7.14,0,0,0-.05.94,7.14,7.14,0,0,0,.05.94l-2.11,1.65a.48.48,0,0,0-.12.61l2,3.46a.48.48,0,0,0,.58.21l2.49-1a6.77,6.77,0,0,0,1.63.94l.38,2.65a.49.49,0,0,0,.48.4h5.34a.49.49,0,0,0,.48-.4l.38-2.65a6.77,6.77,0,0,0,1.63-.94l2.49,1a.48.48,0,0,0,.58-.21l2-3.46a.48.48,0,0,0-.12-.61ZM12,15.5A3.5,3.5,0,1,1,15.5,12,3.5,3.5,0,0,1,12,15.5Z"/>
        </svg>
      </Link>

      <div className="w-full max-w-[760px]">
        {/* Kopf mit SVGs aus /public */}
        <div className="flex items-center justify-center gap-6 mb-6 select-none">
          <img src="/logo_grape.svg" alt="Trauben" className="w-12 h-12 md:w-14 md:h-14" draggable={false} />
          <h1 className="text-4xl md:text-5xl font-extrabold tracking-[0.25em] text-white">BACCHUS</h1>
          <img src="/logo_glass.svg" alt="Glas" className="w-12 h-12 md:w-14 md:h-14" draggable={false} />
        </div>

        {/* Maskenfeld – feste Höhe */}
        <div className="mx-auto max-w-[640px] mb-6">
          <div
            className="w-full h-16 md:h-20 rounded-2xl px-6 md:px-8
                       bg-[#000F2E]/85 text-white
                       border border-[#2B2B45] shadow-[inset_0_0_0_1px_rgba(0,0,0,.25)]
                       ring-1 ring-[#0c2a36]/40
                       flex items-center justify-center"
          >
            <p className="text-3xl md:text-4xl font-black tracking-[0.5em] leading-none select-none">
              {masked}
            </p>
          </div>
          {error && <div className="mt-3 text-center text-red-400 font-medium">{error}</div>}
        </div>

        {/* Keypad */}
        <div className="mx-auto max-w-[640px] space-y-4">
          {[
            ['1','2','3'],
            ['4','5','6'],
            ['7','8','9'],
          ].map((row, i) => (
            <div key={i} className="grid grid-cols-3 gap-4">
              {row.map((n) => (
                <button
                  key={n}
                  onClick={() => push(n)}
                  disabled={loading}
                  className="rounded-2xl py-5 md:py-6
                             text-white text-3xl font-extrabold
                             bg-[#000F2E] hover:bg-[#2f3951] active:translate-y-[1px]
                             border border-[#2B2B45] ring-1 ring-[#0c2a36]/40 shadow
                             transition disabled:opacity-50"
                >
                  {n}
                </button>
              ))}
            </div>
          ))}

          {/* Untere Reihe */}
          <div className="grid grid-cols-3 gap-4">
            <button
              onClick={reset}
              disabled={loading}
              className="rounded-2xl py-5 md:py-6 text-white text-2xl font-extrabold
                         bg-[#7a1010] hover:bg-[#8f1414] active:translate-y-[1px]
                         border border-[#2B2B45] ring-1 ring-[#3e0a0a]/50 shadow transition disabled:opacity-50"
            >
              X
            </button>

            <button
              onClick={() => push('0')}
              disabled={loading}
              className="rounded-2xl py-5 md:py-6
                         text-white text-3xl font-extrabold
                         bg-[#000F2E] hover:bg-[#2f3951] active:translate-y-[1px]
                         border border-[#2B2B45] ring-1 ring-[#0c2a36]/40 shadow
                         transition disabled:opacity-50"
            >
              0
            </button>

            <button
              onClick={submit}
              disabled={loading || pin.length !== 6}
              className="rounded-2xl py-5 md:py-6
                         text-white text-2xl md:text-3xl font-extrabold
                         bg-[#00DD00] hover:bg-[#009030] active:translate-y-[1px]
                         border border-[#0a3b20] ring-1 ring-[#0a3b20]/50 shadow transition
                         disabled:opacity-50"
            >
              OK
            </button>
          </div>

          <div className="pt-3 text-center text-white/60 text-xs select-none">
            Hier maybe noch Impressum etc
          </div>
        </div>
      </div>
    </div>
  );
}
