// SPDX-License-Identifier: GPL-3.0-or-later

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Shield, Loader2, CheckCircle, AlertCircle, Key, Server } from 'lucide-react';
import { register } from '../lib/api';
import Alert from '../components/Alert';

type SetupStep = 'welcome' | 'connecting' | 'registering' | 'complete' | 'error';

export default function Setup() {
  const navigate = useNavigate();
  const [step, setStep] = useState<SetupStep>('welcome');
  const [error, setError] = useState<string | null>(null);
  const [certHash, setCertHash] = useState<string | null>(null);

  const handleSetup = async () => {
    setStep('connecting');
    setError(null);

    try {
      // Small delay for UX
      await new Promise((resolve) => setTimeout(resolve, 1000));
      
      setStep('registering');
      
      // Register with backend (which handles server registration)
      const result = await register();
      
      setCertHash(result.cert_hash);
      setStep('complete');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Registration failed');
      setStep('error');
    }
  };

  const handleContinue = () => {
    navigate('/');
  };

  const handleRetry = () => {
    setStep('welcome');
    setError(null);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4">
      <div className="w-full max-w-lg">
        {/* Logo */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-20 h-20 rounded-2xl bg-primary-600 mb-4">
            <Shield className="w-10 h-10 text-white" />
          </div>
          <h1 className="text-3xl font-bold text-white">Private Archive</h1>
          <p className="text-slate-400 mt-2">Privacy-focused encrypted backups</p>
        </div>

        {/* Card */}
        <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-xl overflow-hidden">
          {/* Welcome Step */}
          {step === 'welcome' && (
            <div className="p-8">
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-4">
                Welcome to Private Archive
              </h2>
              <p className="text-slate-600 dark:text-slate-300 mb-6">
                Let's set up your secure backup account. This will:
              </p>
              <ul className="space-y-3 mb-8">
                <li className="flex items-start">
                  <div className="flex-shrink-0 w-6 h-6 rounded-full bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center mr-3 mt-0.5">
                    <Key className="w-3.5 h-3.5 text-primary-600 dark:text-primary-400" />
                  </div>
                  <div>
                    <p className="text-slate-700 dark:text-slate-200 font-medium">Generate encryption keys</p>
                    <p className="text-sm text-slate-500 dark:text-slate-400">Your data is encrypted before leaving your device</p>
                  </div>
                </li>
                <li className="flex items-start">
                  <div className="flex-shrink-0 w-6 h-6 rounded-full bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center mr-3 mt-0.5">
                    <Server className="w-3.5 h-3.5 text-primary-600 dark:text-primary-400" />
                  </div>
                  <div>
                    <p className="text-slate-700 dark:text-slate-200 font-medium">Connect via Tor</p>
                    <p className="text-sm text-slate-500 dark:text-slate-400">Anonymous, secure connection to backup server</p>
                  </div>
                </li>
                <li className="flex items-start">
                  <div className="flex-shrink-0 w-6 h-6 rounded-full bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center mr-3 mt-0.5">
                    <Shield className="w-3.5 h-3.5 text-primary-600 dark:text-primary-400" />
                  </div>
                  <div>
                    <p className="text-slate-700 dark:text-slate-200 font-medium">Create backup key file</p>
                    <p className="text-sm text-slate-500 dark:text-slate-400">Your only way to access backups - keep it safe!</p>
                  </div>
                </li>
              </ul>
              <button
                onClick={handleSetup}
                className="w-full btn-primary py-3 text-lg"
              >
                Get Started
              </button>
            </div>
          )}

          {/* Connecting/Registering Step */}
          {(step === 'connecting' || step === 'registering') && (
            <div className="p-8 text-center">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary-100 dark:bg-primary-900/30 mb-6">
                <Loader2 className="w-8 h-8 text-primary-600 animate-spin" />
              </div>
              <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                {step === 'connecting' ? 'Connecting to Tor...' : 'Registering account...'}
              </h2>
              <p className="text-slate-600 dark:text-slate-400">
                {step === 'connecting'
                  ? 'Establishing secure connection'
                  : 'Creating your encryption keys and registering with the server'}
              </p>
            </div>
          )}

          {/* Complete Step */}
          {step === 'complete' && (
            <div className="p-8">
              <div className="text-center mb-6">
                <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 dark:bg-green-900/30 mb-4">
                  <CheckCircle className="w-8 h-8 text-green-600" />
                </div>
                <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                  Account Created!
                </h2>
                <p className="text-slate-600 dark:text-slate-400">
                  Your secure backup account is ready to use.
                </p>
              </div>

              <Alert type="warning" title="Important: Save Your Backup Key">
                <p className="mb-2">
                  Your backup key file has been created. This is the <strong>only way</strong> to access your backups.
                </p>
                <ul className="list-disc list-inside text-sm space-y-1">
                  <li>There is NO password reset</li>
                  <li>There is NO account recovery</li>
                  <li>Store copies in multiple secure locations</li>
                </ul>
              </Alert>

              {certHash && (
                <div className="mt-4 p-3 bg-slate-100 dark:bg-slate-700 rounded-lg">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Certificate Hash</p>
                  <p className="text-sm font-mono text-slate-700 dark:text-slate-200 break-all">
                    {certHash}
                  </p>
                </div>
              )}

              <button
                onClick={handleContinue}
                className="w-full btn-primary py-3 text-lg mt-6"
              >
                Continue to Dashboard
              </button>
            </div>
          )}

          {/* Error Step */}
          {step === 'error' && (
            <div className="p-8">
              <div className="text-center mb-6">
                <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 dark:bg-red-900/30 mb-4">
                  <AlertCircle className="w-8 h-8 text-red-600" />
                </div>
                <h2 className="text-xl font-semibold text-slate-900 dark:text-white mb-2">
                  Setup Failed
                </h2>
                <p className="text-slate-600 dark:text-slate-400">
                  We couldn't complete the setup process.
                </p>
              </div>

              {error && (
                <Alert type="error" title="Error Details">
                  {error}
                </Alert>
              )}

              <div className="mt-6 space-y-3">
                <button
                  onClick={handleRetry}
                  className="w-full btn-primary py-3"
                >
                  Try Again
                </button>
                <p className="text-center text-sm text-slate-500 dark:text-slate-400">
                  Make sure the backend daemon is running
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <p className="text-center text-sm text-slate-500 mt-6">
          Your data is encrypted locally. We can't see your files.
        </p>
      </div>
    </div>
  );
}
