

import React, { useState } from "react";
import { useMatrix } from "../matrix/MatrixProvider.jsx";


/**
 * UI for linking AeThex and Matrix accounts.
 * 1. User logs in with AeThex credentials (simulate for now)
 * 2. User logs in with Matrix credentials
 * 3. Store mapping in localStorage (or call backend in real app)
 */
export default function AccountLinker({ onLinked }) {
  const matrixCtx = useMatrix();
  if (!matrixCtx) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-[#1a1a2e] via-[#23234a] to-[#0f3460]">
        <div className="relative flex flex-col items-center">
          <div className="w-16 h-16 mb-6">
            <svg className="animate-spin-slow" viewBox="0 0 50 50">
              <circle className="opacity-20" cx="25" cy="25" r="20" stroke="#fff" strokeWidth="5" fill="none" />
              <circle className="animate-spinner" cx="25" cy="25" r="20" stroke="#ff6bcb" strokeWidth="5" fill="none" strokeDasharray="100" strokeDashoffset="60" />
            </svg>
          </div>
          <div className="toast bg-[#23234a] text-white px-6 py-4 rounded-xl shadow-lg border border-pink-400 animate-fade-in">
            <span className="font-bold text-pink-400">Hang tight!</span> <br />
            <span className="text-sm text-blue-200">We’re prepping your login experience…</span>
          </div>
        </div>
        <style>{`
          .animate-spin-slow { animation: spin 1.8s linear infinite; }
          @keyframes spin { 100% { transform: rotate(360deg); } }
          .animate-spinner { animation: dash 1.5s ease-in-out infinite; }
          @keyframes dash {
            0% { stroke-dashoffset: 100; }
            50% { stroke-dashoffset: 20; }
            100% { stroke-dashoffset: 100; }
          }
          .animate-fade-in { animation: fadeIn 0.8s cubic-bezier(.4,0,.2,1) both; }
          @keyframes fadeIn { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: none; } }
        `}</style>
      </div>
    );
  }
  const { login } = matrixCtx;
  const [aethexUser, setAethexUser] = useState("");
  const [aethexPass, setAethexPass] = useState("");
  const [matrixUser, setMatrixUser] = useState("");
  const [matrixPass, setMatrixPass] = useState("");
  const [step, setStep] = useState(1);
  const [error, setError] = useState(null);

  // Simulate AeThex auth (replace with real API call)
  const handleAethexLogin = (e) => {
    e.preventDefault();
    if (aethexUser && aethexPass) {
      setStep(2);
      setError(null);
    } else {
      setError("Enter AeThex username and password.");
    }
  };

  // Simulate Matrix auth (let MatrixProvider handle real login)
  const handleMatrixLogin = (e) => {
    e.preventDefault();
    if (matrixUser && matrixPass) {
      // Store mapping (simulate)
      localStorage.setItem("aethex-matrix-link", JSON.stringify({ aethexUser, matrixUser }));
      setError(null);
      if (onLinked) onLinked({ aethexUser, matrixUser, matrixPass });
    } else {
      setError("Enter Matrix username and password.");
    }
  };

  // Demo login handler
  const handleDemoLogin = async () => {
    setAethexUser('demo');
    setAethexPass('demo123');
    setStep(2);
    setTimeout(async () => {
      setMatrixUser('@mrpiglr:matrix.org');
      setMatrixPass('Max!FTW2023!');
      setTimeout(async () => {
        localStorage.setItem("aethex-matrix-link", JSON.stringify({ aethexUser: 'demo', matrixUser: '@mrpiglr:matrix.org' }));
        setError(null);
        if (login) {
          try {
            await login('@mrpiglr:matrix.org', 'Max!FTW2023!');
          } catch (e) {
            setError(e.message || 'Login failed.');
            return;
          }
        }
        if (onLinked) onLinked({ aethexUser: 'demo', matrixUser: '@mrpiglr:matrix.org', matrixPass: 'Max!FTW2023!' });
        // window.location.href = '/';
      }, 500);
    }, 500);
  };

  return (
    <div className="login-bg min-h-screen flex flex-col items-center justify-center" style={{background: "linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)"}}>
      <div className="account-linker bg-[#181818cc] p-8 rounded-2xl max-w-md w-full mx-auto shadow-2xl border border-[#23234a] flex flex-col items-center animate-fade-in">
        <img src="/favicon.svg" alt="AeThex Logo" className="w-16 h-16 mb-4 drop-shadow-lg" />
        <h1 className="text-3xl font-extrabold mb-2 text-white tracking-tight text-center">AeThex Connect</h1>
        <h2 className="text-lg font-semibold mb-6 text-blue-300 text-center">Sign in to your account</h2>
        <button onClick={handleDemoLogin} className="mb-4 w-full bg-gradient-to-r from-yellow-400 to-pink-500 text-white rounded-lg py-2 font-bold shadow hover:from-yellow-500 hover:to-pink-600 transition">Demo Login</button>
        {error && <div className="mb-2 text-red-400 text-center w-full">{error}</div>}
        {/* Show MatrixProvider error if present */}
        {matrixCtx && matrixCtx.error && (
          <div className="mb-2 text-red-400 text-center w-full">Matrix error: {matrixCtx.error}</div>
        )}
        {step === 1 && (
          <form onSubmit={handleAethexLogin} className="flex flex-col gap-4 w-full">
            <input
              type="text"
              placeholder="AeThex Username"
              className="px-4 py-3 rounded-lg bg-[#23234a] text-white border border-[#2d2d5a] focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
              value={aethexUser}
              onChange={e => setAethexUser(e.target.value)}
              autoFocus
            />
            <input
              type="password"
              placeholder="AeThex Password"
              className="px-4 py-3 rounded-lg bg-[#23234a] text-white border border-[#2d2d5a] focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
              value={aethexPass}
              onChange={e => setAethexPass(e.target.value)}
            />
            <button type="submit" className="bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg py-3 font-bold mt-2 shadow-lg hover:from-blue-700 hover:to-purple-700 transition">Continue to Matrix</button>
          </form>
        )}
        {step === 2 && (
          <form onSubmit={handleMatrixLogin} className="flex flex-col gap-4 w-full">
            <input
              type="text"
              placeholder="Matrix Username (@user:matrix.org)"
              className="px-4 py-3 rounded-lg bg-[#23234a] text-white border border-[#2d2d5a] focus:outline-none focus:ring-2 focus:ring-green-500 transition"
              value={matrixUser}
              onChange={e => setMatrixUser(e.target.value)}
              autoFocus
            />
            <input
              type="password"
              placeholder="Matrix Password"
              className="px-4 py-3 rounded-lg bg-[#23234a] text-white border border-[#2d2d5a] focus:outline-none focus:ring-2 focus:ring-green-500 transition"
              value={matrixPass}
              onChange={e => setMatrixPass(e.target.value)}
            />
            <button type="submit" className="bg-gradient-to-r from-green-500 to-blue-500 text-white rounded-lg py-3 font-bold mt-2 shadow-lg hover:from-green-600 hover:to-blue-600 transition">Link Accounts & Login</button>
          </form>
        )}
        <div className="mt-6 text-center text-gray-400 text-xs w-full">
          <span>By continuing, you agree to the <a href="/terms" className="underline hover:text-blue-300">Terms of Service</a> and <a href="/privacy" className="underline hover:text-blue-300">Privacy Policy</a>.</span>
        </div>
      </div>
      <style>{`
        .animate-fade-in { animation: fadeIn 0.8s cubic-bezier(.4,0,.2,1) both; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: none; } }
      `}</style>
    </div>
  );
}
