'use client';

import { useState, useEffect } from 'react';
import { bootstrapMasterKey } from '@/lib/actions/apiKeyActions';
import KeyDisplay from '@/components/admin/KeyDisplay';
import AdminFormInput from '@/components/admin/AdminFormInput';
import AdminButton from '@/components/admin/AdminButton';
import { NarrowSection } from '@/components/shared/NarrowSection';

const STORAGE_KEY = 'banatie_master_key';

export default function MasterKeyPage() {
  const [masterKey, setMasterKey] = useState('');
  const [manualKey, setManualKey] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // Load saved key from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      setMasterKey(saved);
    }
  }, []);

  const handleBootstrap = async () => {
    setLoading(true);
    setError('');
    setSuccess('');

    const result = await bootstrapMasterKey();

    if (result.success && result.apiKey) {
      setMasterKey(result.apiKey);
      setSuccess('Master key generated successfully!');
    } else {
      setError(result.error || 'Failed to bootstrap master key');
    }

    setLoading(false);
  };

  const handleSave = () => {
    if (masterKey) {
      localStorage.setItem(STORAGE_KEY, masterKey);
      setSuccess('Master key saved to localStorage!');
      setTimeout(() => setSuccess(''), 3000);
    }
  };

  const handleManualSave = () => {
    if (manualKey) {
      localStorage.setItem(STORAGE_KEY, manualKey);
      setMasterKey(manualKey);
      setManualKey('');
      setSuccess('Master key saved to localStorage!');
      setTimeout(() => setSuccess(''), 3000);
    }
  };

  const handleClear = () => {
    localStorage.removeItem(STORAGE_KEY);
    setMasterKey('');
    setSuccess('Master key cleared from localStorage');
    setTimeout(() => setSuccess(''), 3000);
  };

  return (
    <NarrowSection>
      {/* Page Header */}
      <div className="mb-8">
        <h1 className="text-4xl font-bold text-white mb-2">Master Key Management</h1>
        <p className="text-slate-400">
          Bootstrap your master key or manually configure it. This key is required to generate
          project API keys.
        </p>
      </div>

      {/* Messages */}
      {error && (
        <div className="mb-6 p-4 bg-red-900/30 border border-red-700 rounded-lg text-red-300">
          {error}
        </div>
      )}
      {success && (
        <div className="mb-6 p-4 bg-green-900/30 border border-green-700 rounded-lg text-green-300">
          {success}
        </div>
      )}

      {/* Bootstrap Section */}
      <div className="mb-8 p-6 bg-slate-800/50 backdrop-blur-sm border border-slate-700 rounded-2xl">
        <h2 className="text-2xl font-semibold text-white mb-4">Bootstrap Master Key</h2>
        <p className="text-slate-400 mb-6">
          Generate the first master key for your system. This only works if no keys exist yet.
        </p>
        <AdminButton onClick={handleBootstrap} disabled={loading}>
          {loading ? 'Generating...' : 'Generate Master Key'}
        </AdminButton>
      </div>

      {/* Current Key Display */}
      {masterKey && (
        <div className="mb-8 p-6 bg-slate-800/50 backdrop-blur-sm border border-slate-700 rounded-2xl">
          <h2 className="text-2xl font-semibold text-white mb-4">Current Master Key</h2>
          <KeyDisplay apiKey={masterKey} />
          <div className="mt-4 flex gap-3">
            <AdminButton onClick={handleSave} variant="primary">
              Save to LocalStorage
            </AdminButton>
            <AdminButton onClick={handleClear} variant="danger">
              Clear from LocalStorage
            </AdminButton>
          </div>
        </div>
      )}

      {/* Manual Entry Section */}
      <div className="p-6 bg-slate-800/50 backdrop-blur-sm border border-slate-700 rounded-2xl">
        <h2 className="text-2xl font-semibold text-white mb-4">Manual Key Entry</h2>
        <p className="text-slate-400 mb-6">
          Already have a master key? Enter it here to save it to localStorage.
        </p>
        <AdminFormInput
          label="Master Key"
          value={manualKey}
          onChange={setManualKey}
          placeholder="bnt_..."
          className="mb-4"
        />
        <AdminButton onClick={handleManualSave} disabled={!manualKey}>
          Save Manual Key
        </AdminButton>
      </div>
    </NarrowSection>
  );
}
