import React, { useState } from 'react';
import { testAdminOIDCConfig, testAdminSwarmConfig } from '../../../../services/apiService';

const NetworkIdentityCard = ({ context }) => {
  const {
      collapsedSections,
      setCollapsedSections,
      adminConfig,
      setAdminConfig,
      handleSaveAdminConfig,
      fileInputRef,
      userProfile,
      labelClass,
      inputClass
  } = context;

  const [localTestStatus, setLocalTestStatus] = useState({ oidc: null, swarm: null }); 
  const [isTesting, setIsTesting] = useState({ oidc: false, swarm: false });
  const [lastTestedConfig, setLastTestedConfig] = useState({ oidc: null, swarm: null });

  const doTest = async (type) => {
      setIsTesting(prev => ({...prev, [type]: true}));
      setLocalTestStatus(prev => ({...prev, [type]: null}));
      
      let response;
      try {
          if (type === 'oidc') {
              response = await testAdminOIDCConfig(adminConfig.oidc);
          } else {
              response = await testAdminSwarmConfig(adminConfig.swarm);
          }
          
          setLocalTestStatus(prev => ({...prev, [type]: response}));
          if (response?.success) {
              setLastTestedConfig(prev => ({...prev, [type]: JSON.stringify(adminConfig[type]) }));
          } else {
              setLastTestedConfig(prev => ({...prev, [type]: null }));
          }
      } catch (err) {
          setLocalTestStatus(prev => ({...prev, [type]: { success: false, message: err.message || 'Connection test failed' }}));
          setLastTestedConfig(prev => ({...prev, [type]: null }));
      } finally {
          setIsTesting(prev => ({...prev, [type]: false}));
      }
  };

  const isOidcValid = !adminConfig.oidc?.server_url || lastTestedConfig.oidc === JSON.stringify(adminConfig.oidc);
  const isSwarmValid = (!adminConfig.swarm?.external_endpoint || !adminConfig.swarm?.grpc_endpoint) || lastTestedConfig.swarm === JSON.stringify(adminConfig.swarm);

  if (userProfile?.role !== 'admin') return null;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-3xl shadow-xl overflow-hidden border border-gray-100 dark:border-gray-700 backdrop-blur-sm transition-all duration-300">
      <div 
        onClick={() => setCollapsedSections(prev => ({ ...prev, infrastructure: !prev.infrastructure }))}
        className="p-6 border-b border-gray-100 dark:border-gray-700 bg-gray-50/30 dark:bg-gray-800/50 cursor-pointer hover:bg-gray-100/50 dark:hover:bg-gray-700/50 transition-colors flex items-center justify-between group"
      >
        <div className="flex items-center gap-3">
          <svg className={`w-6 h-6 text-amber-500 transition-transform duration-300 ${collapsedSections.infrastructure ? '-rotate-90' : 'rotate-0'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.1c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
          <div>
            <h2 className="text-xl font-black text-gray-900 dark:text-white flex items-center gap-3">
              Network Access & External Identity
            </h2>
            <p className="text-[10px] text-gray-400 mt-1 font-bold leading-none">Manage authentication protocols, SSO, and swarm deployment endpoints</p>
          </div>
        </div>
        <div className="bg-amber-50 dark:bg-amber-950/30 p-2 rounded-xl border border-amber-100 dark:border-amber-900/50 group-hover:scale-110 transition-transform duration-300">
          <svg className={`w-4 h-4 text-amber-600 dark:text-amber-400 transition-transform duration-300 ${collapsedSections.infrastructure ? 'rotate-180' : 'rotate-0'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M19 9l-7 7-7-7" /></svg>
        </div>
      </div>

      {!collapsedSections.infrastructure && (
        <div className="animate-fade-in-down">
          <div className="p-8 sm:p-12 space-y-12">
            {/* Access Security Model */}
            <div className="space-y-8">
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 p-6 bg-indigo-50/30 dark:bg-indigo-900/10 rounded-3xl border border-indigo-100/50 dark:border-indigo-900/30">
                <div className="max-w-2xl">
                  <h3 className="text-xl font-black text-gray-900 dark:text-white flex items-center gap-3 lowercase italic opacity-80 mb-2">
                    <svg className="w-5 h-5 text-indigo-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                    Access Security Model
                  </h3>
                  <p className="text-sm text-gray-400 font-bold leading-relaxed">
                    Access Policy: You may enable OIDC, Local Password, or both. For safety, at least one authentication method must remain active.
                  </p>
                </div>
                <div className="flex flex-col gap-3 min-w-[200px]">
                   <button
                     type="button"
                     onClick={() => handleSaveAdminConfig('app', { ...(adminConfig.app || {}), allow_password_login: !adminConfig.app?.allow_password_login })}
                     className={`w-full px-6 py-3 rounded-2xl text-[10px] font-black transition-all ${adminConfig.app?.allow_password_login ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-500/20' : 'bg-gray-100 dark:bg-gray-800 text-gray-400 dark:text-gray-500'}`}
                   >
                     {adminConfig.app?.allow_password_login ? 'Local Password Enabled' : 'Local Password Prohibited'}
                   </button>
                   <button
                     type="button"
                     onClick={() => handleSaveAdminConfig('oidc', { ...(adminConfig.oidc || {}), enabled: !adminConfig.oidc?.enabled })}
                     className={`w-full px-6 py-3 rounded-2xl text-[10px] font-black transition-all ${adminConfig.oidc?.enabled ? 'bg-emerald-600 text-white shadow-lg shadow-emerald-500/20' : 'bg-gray-100 dark:bg-gray-800 text-gray-400 dark:text-gray-500'}`}
                   >
                     {adminConfig.oidc?.enabled ? 'OIDC/SSO Integration Active' : 'OIDC/SSO Disabled'}
                   </button>
                </div>
              </div>
            </div>

            {/* OIDC Details */}
            <div className="space-y-4 pt-10 border-t border-gray-100 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-black text-gray-900 dark:text-white">
                    OIDC Configuration Details
                  </h3>
                  <p className="text-[10px] text-gray-400 font-bold mt-1">Enterprise Social Login & Identity Synchronization</p>
                </div>
                <div className="flex items-center gap-4">
                  <button
                    type="button"
                    disabled={isTesting.oidc}
                    onClick={() => doTest('oidc')}
                    className="px-4 py-2 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-xl text-[10px] font-black hover:bg-indigo-100 dark:hover:bg-indigo-900/50 transition-all border border-indigo-100 dark:border-indigo-800"
                  >
                    {isTesting.oidc ? 'Verifying...' : 'Test Connection'}
                  </button>
                </div>
              </div>
              
              {/* OIDC Test Message Inline Feedback */}
              {isTesting.oidc && (
                <div className="text-[10px] font-bold text-indigo-500 animate-pulse text-right">
                  Attempting to discover OIDC provider configuration...
                </div>
              )}
              {localTestStatus.oidc && (
                <div className={`text-[11px] font-bold p-3 rounded-lg border ${localTestStatus.oidc.success ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-red-50 text-red-700 border-red-200'}`}>
                    {localTestStatus.oidc.success ? '✅ ' : '❌ '} {localTestStatus.oidc.message}
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50/50 dark:bg-gray-900/30 p-6 rounded-3xl border border-gray-100 dark:border-gray-700">
                <div className="space-y-1.5">
                  <label className={labelClass}>Client ID</label>
                  <input
                    type="text"
                    id="oidc_client_id"
                    name="oidc_client_id"
                    value={adminConfig.oidc?.client_id || ''}
                    onChange={e => setAdminConfig({...adminConfig, oidc: {...adminConfig.oidc, client_id: e.target.value}})}
                    className={inputClass}
                    placeholder="e.g. 123456789.apps.googleusercontent.com"
                    autoComplete="off"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className={labelClass}>Client Secret</label>
                  <input
                    type="password"
                    id="oidc_client_secret"
                    name="oidc_client_secret"
                    value={adminConfig.oidc?.client_secret || ''}
                    onChange={e => setAdminConfig({...adminConfig, oidc: {...adminConfig.oidc, client_secret: e.target.value}})}
                    className={inputClass}
                    placeholder="••••••••••••••••"
                    autoComplete="new-password"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className={labelClass}>Discovery / Server URL</label>
                  <input
                    type="text"
                    id="oidc_server_url"
                    name="oidc_server_url"
                    value={adminConfig.oidc?.server_url || ''}
                    onChange={e => setAdminConfig({...adminConfig, oidc: {...adminConfig.oidc, server_url: e.target.value}})}
                    className={inputClass}
                    placeholder="https://accounts.google.com"
                    autoComplete="off"
                  />
                </div>
                <div className="space-y-1.5">
                  <label className={labelClass}>Redirect URI</label>
                  <input
                    type="text"
                    id="oidc_redirect_uri"
                    name="oidc_redirect_uri"
                    value={adminConfig.oidc?.redirect_uri || ''}
                    onChange={e => setAdminConfig({...adminConfig, oidc: {...adminConfig.oidc, redirect_uri: e.target.value}})}
                    className={inputClass}
                    placeholder="https://ai.example.com/login/callback"
                    autoComplete="off"
                  />
                </div>
                <div className="md:col-span-2 flex items-center justify-end gap-3 mt-4">
                  {!isOidcValid && adminConfig.oidc?.server_url && (
                      <span className="text-[10px] text-amber-600 font-bold">⚠️ Test required before saving!</span>
                  )}
                  <button
                    type="button"
                    disabled={!isOidcValid}
                    onClick={() => handleSaveAdminConfig('oidc', adminConfig.oidc)}
                    className={`px-6 py-2 rounded-xl text-[10px] font-black shadow-md transition-all font-sans ${isOidcValid ? 'bg-indigo-600 text-white hover:bg-indigo-700' : 'bg-gray-300 text-gray-500 cursor-not-allowed opacity-60'}`}
                  >
                    Update OIDC Identity
                  </button>
                </div>
              </div>
            </div>

            {/* Swarm Endpoint Details */}
            <div className="space-y-4 pt-10 border-t border-gray-100 dark:border-gray-700">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-black text-gray-900 dark:text-white flex items-center gap-2">
                    Swarm Access Configuration
                  </h3>
                  <p className="text-[10px] text-gray-400 font-bold mt-1">Infrastructure gRPC Connectivity & Discovery</p>
                </div>
                <div className="flex items-center gap-4">
                   <button
                     type="button"
                     disabled={isTesting.swarm}
                     onClick={() => doTest('swarm')}
                     className="px-4 py-2 bg-indigo-50 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 rounded-xl text-[10px] font-black hover:bg-indigo-100 dark:hover:bg-indigo-900/50 transition-all border border-indigo-100 dark:border-indigo-800"
                   >
                     {isTesting.swarm ? 'Verifying...' : 'Test Connection'}
                   </button>
                </div>
              </div>

              {/* Swarm Test Message Inline Feedback */}
              {isTesting.swarm && (
                <div className="text-[10px] font-bold text-indigo-500 animate-pulse text-right">
                  Pinging Swarm external endpoint...
                </div>
              )}
              {localTestStatus.swarm && (
                <div className={`text-[11px] font-bold p-3 rounded-lg border ${localTestStatus.swarm.success ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-red-50 text-red-700 border-red-200'}`}>
                    {localTestStatus.swarm.success ? '✅ ' : '❌ '} {localTestStatus.swarm.message}
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 bg-gray-50/50 dark:bg-gray-900/30 p-6 rounded-3xl border border-gray-100 dark:border-gray-700">
                <div className="space-y-1.5">
                  <label className={labelClass}>External Hub URL (REST/HTTPS)</label>
                  <p className="text-[10px] text-gray-400 mb-2 italic font-medium">Used by agents to download OTA updates and push REST logs.</p>
                  <input
                    type="text"
                    id="swarm_external_endpoint"
                    name="swarm_external_endpoint"
                    value={adminConfig.swarm?.external_endpoint || ''}
                    onChange={e => setAdminConfig({...adminConfig, swarm: {...adminConfig.swarm, external_endpoint: e.target.value}})}
                    className={inputClass}
                    placeholder="https://ai.company.com"
                    autoComplete="off"
                  />
                </div>
                <div className="space-y-1.5 mt-2 md:mt-0">
                  <label className={labelClass}>gRPC Target Origin</label>
                  <p className="text-[10px] text-gray-400 mb-2 italic font-medium">The precise Domain:Port agents use for continuous data streaming.</p>
                  <input
                    type="text"
                    id="swarm_grpc_endpoint"
                    name="swarm_grpc_endpoint"
                    value={adminConfig.swarm?.grpc_endpoint || ''}
                    onChange={e => setAdminConfig({...adminConfig, swarm: {...adminConfig.swarm, grpc_endpoint: e.target.value}})}
                    className={inputClass}
                    placeholder="ai.company.com:443"
                    autoComplete="off"
                  />
                </div>
                <div className="flex items-center justify-end gap-3 mt-4">
                  {!isSwarmValid && adminConfig.swarm?.external_endpoint && (
                      <span className="text-[10px] text-amber-600 font-bold">⚠️ Test required before saving!</span>
                  )}
                  <button
                    type="button"
                    disabled={!isSwarmValid}
                    onClick={() => handleSaveAdminConfig('swarm', adminConfig.swarm)}
                    className={`px-6 py-2 rounded-xl text-[10px] font-black shadow-md transition-all font-sans ${isSwarmValid ? 'bg-indigo-600 text-white hover:bg-indigo-700' : 'bg-gray-300 text-gray-500 cursor-not-allowed opacity-60'}`}
                  >
                    Update Swarm Endpoint
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default NetworkIdentityCard;
