import { useState, useEffect } from 'react';
import { 
  Cloud, 
  Download, 
  Upload, 
  CheckCircle2, 
  Loader2, 
  HardDrive, 
  RefreshCw, 
  ExternalLink, 
  AlertCircle, 
  FileArchive, 
  Folder, 
  File, 
  Database,
  Check,
  Server,
  CloudLightning,
  Settings,
  Link2
} from 'lucide-react';
import { User } from '../types';

interface BackupFile {
  filename: string;
  size: number;
  createdAt: string;
  path: string;
}

interface CloudStoragePanelProps {
  currentUser: User | null;
}

export default function CloudStoragePanel({ currentUser }: CloudStoragePanelProps) {
  const [backups, setBackups] = useState<BackupFile[]>([]);
  const [loadingBackups, setLoadingBackups] = useState(false);
  const [generating, setGenerating] = useState(false);
  
  // Cloud integrations state
  const [activeProvider, setActiveProvider] = useState<'google_drive' | 'dropbox' | 's3'>('google_drive');
  const [isConnected, setIsConnected] = useState<Record<string, boolean>>({
    google_drive: false,
    dropbox: false,
    s3: false
  });
  const [connecting, setConnecting] = useState<string | null>(null);
  
  // Uploading state
  const [uploadingFile, setUploadingFile] = useState<string | null>(null);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [cloudFiles, setCloudFiles] = useState<any[]>([]);

  // Flat list of consolidated files inside propertyhub to show to user
  const [activeSubTab, setActiveSubTab] = useState<'backups' | 'all_files' | 'config'>('backups');
  
  const consolidatedFiles = [
    { path: 'propertyhub/index.php', type: 'Core Bootstrap', size: '4.2 KB' },
    { path: 'propertyhub/.htaccess', type: 'Server Rules', size: '150 B' },
    { path: 'propertyhub/database.sql', type: 'MySQL Schema & Seed', size: '12.8 KB' },
    { path: 'propertyhub/application/config/config.php', type: 'Configuration', size: '18.5 KB' },
    { path: 'propertyhub/application/config/database.php', type: 'Configuration', size: '4.1 KB' },
    { path: 'propertyhub/application/config/routes.php', type: 'Configuration', size: '2.8 KB' },
    { path: 'propertyhub/application/controllers/Dashboard.php', type: 'PHP Controller', size: '3.4 KB' },
    { path: 'propertyhub/application/controllers/Property.php', type: 'PHP Controller', size: '5.2 KB' },
    { path: 'propertyhub/application/controllers/Auth.php', type: 'PHP Controller', size: '4.8 KB' },
    { path: 'propertyhub/application/models/Property_model.php', type: 'PHP Model', size: '8.1 KB' },
    { path: 'propertyhub/application/models/User_model.php', type: 'PHP Model', size: '2.5 KB' },
    { path: 'propertyhub/application/views/dashboard.php', type: 'PHP View', size: '11.2 KB' },
    { path: 'propertyhub/application/views/properties/list.php', type: 'PHP View', size: '7.4 KB' },
    { path: 'propertyhub/application/views/properties/add.php', type: 'PHP View', size: '4.9 KB' },
    { path: 'propertyhub/application/views/templates/header.php', type: 'PHP View Layout', size: '3.1 KB' },
    { path: 'propertyhub/application/views/templates/sidebar.php', type: 'PHP View Layout', size: '4.5 KB' },
    { path: 'propertyhub/application/views/templates/footer.php', type: 'PHP View Layout', size: '2.2 KB' },
  ];

  const fetchBackups = async () => {
    setLoadingBackups(true);
    try {
      const res = await fetch('/api/cloud/backups');
      if (res.ok) {
        const data = await res.json();
        setBackups(data);
      }
    } catch (e) {
      console.error('Gagal mengambil backup:', e);
    } finally {
      setLoadingBackups(false);
    }
  };

  useEffect(() => {
    fetchBackups();
    // Load simulated cloud files from localStorage
    const saved = localStorage.getItem('simulated_cloud_files');
    if (saved) {
      setCloudFiles(JSON.parse(saved));
    }
  }, []);

  const handleGenerateBackup = async () => {
    setGenerating(true);
    try {
      const res = await fetch('/api/cloud/backup/generate', {
        method: 'POST',
      });
      if (res.ok) {
        const data = await res.json();
        fetchBackups();
        alert('Sukses! Folder & file CodeIgniter 3 di /propertyhub berhasil digabungkan menjadi satu file ZIP.');
      } else {
        alert('Gagal membuat backup gabungan.');
      }
    } catch (e) {
      alert('Koneksi terputus: Gagal memproses backup.');
    } finally {
      setGenerating(false);
    }
  };

  const connectProvider = (provider: string) => {
    setConnecting(provider);
    setTimeout(() => {
      setIsConnected(prev => ({ ...prev, [provider]: true }));
      setConnecting(null);
    }, 1500);
  };

  const disconnectProvider = (provider: string) => {
    setIsConnected(prev => ({ ...prev, [provider]: false }));
  };

  const handleCloudUpload = async (backup: BackupFile) => {
    if (!isConnected[activeProvider]) {
      alert(`Silakan hubungkan akun ${activeProvider === 'google_drive' ? 'Google Drive' : activeProvider === 'dropbox' ? 'Dropbox' : 'AWS S3'} terlebih dahulu!`);
      return;
    }

    setUploadingFile(backup.filename);
    setUploadProgress(10);

    // Simulate progress ticks
    const interval = setInterval(() => {
      setUploadProgress(prev => {
        if (prev >= 90) {
          clearInterval(interval);
          return 90;
        }
        return prev + 20;
      });
    }, 400);

    try {
      const res = await fetch('/api/cloud/upload', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          filename: backup.filename,
          provider: activeProvider
        })
      });

      if (res.ok) {
        const data = await res.json();
        setTimeout(() => {
          setUploadProgress(100);
          setTimeout(() => {
            const newCloudFile = {
              id: data.details.cloudFileId,
              filename: data.details.filename,
              provider: data.details.provider,
              size: data.details.fileSize,
              uploadedAt: data.details.uploadedAt,
              url: data.details.backupUrl
            };
            
            const updated = [newCloudFile, ...cloudFiles];
            setCloudFiles(updated);
            localStorage.setItem('simulated_cloud_files', JSON.stringify(updated));
            
            setUploadingFile(null);
            setUploadProgress(0);
          }, 500);
        }, 1200);
      } else {
        clearInterval(interval);
        setUploadingFile(null);
        alert('Gagal mengunggah file ke cloud.');
      }
    } catch (e) {
      clearInterval(interval);
      setUploadingFile(null);
      alert('Koneksi terputus saat mengunggah.');
    }
  };

  const formatSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getProviderName = (id: string) => {
    if (id === 'google_drive') return 'Google Drive API v3';
    if (id === 'dropbox') return 'Dropbox Business SDK';
    return 'Amazon Web Services S3 Bucket';
  };

  return (
    <div className="space-y-6" id="cloud-storage-container">
      {/* Page Header (AdminLTE breadcrumb style) */}
      <div className="flex justify-between items-center bg-white p-4 rounded-xl border border-gray-100 shadow-xs">
        <div>
          <h1 className="text-xl font-bold text-gray-900 tracking-tight flex items-center space-x-2">
            <Cloud className="h-6 w-6 text-blue-600" />
            <span>Penyimpanan Cloud & Integrasi Drive</span>
          </h1>
          <p className="text-xs text-gray-500 mt-1">
            Ekspor codebase terpadu, sinkronisasi cadangan file ke Google Drive, Dropbox, atau Amazon S3 secara aman.
          </p>
        </div>
        <div className="text-xs font-mono bg-gray-100 px-3 py-1.5 rounded-lg text-gray-500 hidden sm:block">
          Home / <span className="font-bold text-gray-700">Cloud Storage</span>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        {/* Left column (2/3 width) - Consolidated Files & Generated ZIP Backups */}
        <div className="lg:col-span-2 space-y-6">
          
          {/* Card: Consolidated Codebase Packager */}
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-xs">
            {/* AdminLTE Card Header */}
            <div className="bg-gradient-to-r from-blue-700 to-blue-800 px-5 py-4 flex justify-between items-center">
              <h3 className="text-sm font-bold text-white flex items-center space-x-2">
                <Database className="h-4 w-4 text-blue-200" />
                <span>Consolidated Backup Packager (File Gabungan)</span>
              </h3>
              <div className="bg-blue-600 text-blue-100 text-[10px] font-mono px-2 py-0.5 rounded">
                PropertyHub Codebase
              </div>
            </div>

            <div className="p-5 space-y-4">
              <div className="bg-blue-50/50 border border-blue-100 rounded-lg p-3.5 text-xs text-blue-800 leading-relaxed flex items-start space-x-2.5">
                <CloudLightning className="h-5 w-5 text-blue-600 shrink-0 mt-0.5" />
                <div>
                  <span className="font-bold">Informasi Penggabungan Folder:</span> Menggabungkan seluruh direktori PHP CodeIgniter 3 (<code>application</code>, <code>system</code>, <code>assets</code>, <code>index.php</code>, <code>database.sql</code>) di bawah folder <code>/propertyhub</code> ke dalam satu arsip ZIP siap pakai. Hal ini mempermudah migrasi ke server hosting atau XAMPP lokal dengan satu kali unduh!
                </div>
              </div>

              {/* Sub-tabs inside the package card */}
              <div className="flex border-b text-xs">
                <button
                  onClick={() => setActiveSubTab('backups')}
                  className={`px-4 py-2 font-medium border-b-2 transition-all cursor-pointer ${
                    activeSubTab === 'backups' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Daftar Backup ZIP Server ({backups.length})
                </button>
                <button
                  onClick={() => setActiveSubTab('all_files')}
                  className={`px-4 py-2 font-medium border-b-2 transition-all cursor-pointer ${
                    activeSubTab === 'all_files' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700'
                  }`}
                >
                  Struktur File Terkonsolidasi ({consolidatedFiles.length})
                </button>
              </div>

              {activeSubTab === 'all_files' && (
                <div className="space-y-3">
                  <p className="text-xs text-gray-500">
                    Berikut adalah representasi file-file penting yang digabungkan ke dalam folder <code>/propertyhub</code>:
                  </p>
                  <div className="border border-gray-200 rounded-lg overflow-hidden max-h-60 overflow-y-auto">
                    <table className="w-full text-left text-xs">
                      <thead className="bg-gray-50 border-b text-gray-600 font-semibold">
                        <tr>
                          <th className="p-2.5">Lokasi File</th>
                          <th className="p-2.5">Kategori / Fungsi</th>
                          <th className="p-2.5 text-right">Ukuran</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-100">
                        {consolidatedFiles.map((file, i) => (
                          <tr key={i} className="hover:bg-gray-50/50">
                            <td className="p-2.5 font-mono text-gray-700 flex items-center space-x-1.5">
                              {file.path.endsWith('.php') ? (
                                <File className="h-3.5 w-3.5 text-indigo-500 shrink-0" />
                              ) : file.path.endsWith('.sql') ? (
                                <Database className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
                              ) : (
                                <Settings className="h-3.5 w-3.5 text-gray-500 shrink-0" />
                              )}
                              <span>{file.path}</span>
                            </td>
                            <td className="p-2.5 text-gray-500">{file.type}</td>
                            <td className="p-2.5 text-right font-mono text-gray-600">{file.size}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>
              )}

              {activeSubTab === 'backups' && (
                <div className="space-y-3">
                  {loadingBackups ? (
                    <div className="flex flex-col items-center justify-center py-10 text-gray-400">
                      <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
                      <span className="text-xs mt-2">Memuat daftar backup server...</span>
                    </div>
                  ) : backups.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 border border-dashed border-gray-200 rounded-lg bg-gray-50 text-gray-400">
                      <FileArchive className="h-10 w-10 text-gray-300" />
                      <span className="text-xs mt-2">Belum ada file backup ZIP di server</span>
                      <span className="text-[10px] text-gray-400 mt-0.5">Klik tombol di bawah untuk membuat cadangan ZIP baru pertama Anda</span>
                    </div>
                  ) : (
                    <div className="border rounded-lg overflow-hidden divide-y">
                      {backups.map((b) => (
                        <div key={b.filename} className="p-3 hover:bg-gray-50 flex items-center justify-between text-xs transition-colors">
                          <div className="flex items-center space-x-3">
                            <div className="p-2 bg-blue-50 rounded-lg text-blue-600">
                              <FileArchive className="h-5 w-5" />
                            </div>
                            <div>
                              <p className="font-semibold text-gray-800 font-mono break-all">{b.filename}</p>
                              <div className="flex space-x-4 text-[10px] text-gray-500 mt-1">
                                <span>Ukuran: <strong className="text-gray-700">{formatSize(b.size)}</strong></span>
                                <span>Dibuat: <strong>{new Date(b.createdAt).toLocaleString('id-ID')}</strong></span>
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2 shrink-0">
                            <a
                              href={`/api/cloud/backup/download/${b.filename}`}
                              download
                              className="bg-gray-100 hover:bg-gray-200 text-gray-700 p-1.5 rounded-lg border border-gray-200 transition-colors flex items-center space-x-1 cursor-pointer"
                              title="Download ke Komputer"
                            >
                              <Download className="h-3.5 w-3.5" />
                              <span className="hidden sm:inline">Unduh</span>
                            </a>
                            <button
                              onClick={() => handleCloudUpload(b)}
                              disabled={uploadingFile !== null}
                              className={`bg-blue-600 hover:bg-blue-700 text-white px-2.5 py-1.5 rounded-lg transition-all flex items-center space-x-1 cursor-pointer font-semibold ${
                                uploadingFile !== null ? 'opacity-50 cursor-not-allowed' : ''
                              }`}
                            >
                              <Upload className="h-3.5 w-3.5" />
                              <span>Upload ke Cloud</span>
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Uploading Progress Indicator */}
                  {uploadingFile && (
                    <div className="bg-amber-50 border border-amber-200 p-3 rounded-lg text-xs space-y-1.5">
                      <div className="flex justify-between items-center font-semibold text-amber-800">
                        <span className="flex items-center space-x-1.5">
                          <Loader2 className="h-3.5 w-3.5 animate-spin text-amber-600" />
                          <span>Mengunggah {uploadingFile} ke {activeProvider === 'google_drive' ? 'Google Drive' : activeProvider === 'dropbox' ? 'Dropbox' : 'AWS S3'}...</span>
                        </span>
                        <span>{uploadProgress}%</span>
                      </div>
                      <div className="w-full bg-amber-200 h-2 rounded-full overflow-hidden">
                        <div 
                          className="bg-amber-500 h-full transition-all duration-300"
                          style={{ width: `${uploadProgress}%` }}
                        ></div>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Package action trigger */}
              <div className="pt-2 flex justify-end">
                <button
                  onClick={handleGenerateBackup}
                  disabled={generating}
                  className="bg-blue-700 hover:bg-blue-800 text-white font-bold px-4 py-2.5 rounded-xl border border-blue-800 shadow-md transition-all flex items-center space-x-2 cursor-pointer disabled:opacity-50 text-xs"
                >
                  {generating ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin text-white" />
                      <span>Menggabungkan & Mengompres File...</span>
                    </>
                  ) : (
                    <>
                      <RefreshCw className="h-4 w-4 text-blue-200" />
                      <span>Gabungkan & Ekspor ZIP Baru</span>
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>

          {/* Card: Simulated Cloud Storage Files list */}
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-xs">
            <div className="bg-gradient-to-r from-emerald-700 to-emerald-800 px-5 py-4 flex justify-between items-center">
              <h3 className="text-sm font-bold text-white flex items-center space-x-2">
                <Cloud className="h-4 w-4 text-emerald-200" />
                <span>Simulasi Cloud File Explorer (Google Drive / S3)</span>
              </h3>
              <span className="bg-emerald-600 text-emerald-100 text-[10px] font-mono px-2 py-0.5 rounded">
                Cloud Sync Status: Active
              </span>
            </div>

            <div className="p-5 space-y-4">
              <p className="text-xs text-gray-500 leading-relaxed">
                Menampilkan daftar berkas zip codebase yang telah berhasil dikirimkan atau dipublikasikan ke layanan Cloud Storage di luar server lokal Anda.
              </p>

              {cloudFiles.length === 0 ? (
                <div className="text-center py-10 border border-dashed rounded-lg bg-gray-50 text-gray-400 text-xs">
                  <Cloud className="h-8 w-8 mx-auto text-gray-300 mb-2" />
                  <p>Belum ada file di Cloud Drive Anda.</p>
                  <p className="text-[10px] text-gray-400 mt-1">Gunakan tombol "Upload ke Cloud" di daftar cadangan di atas untuk menyinkronkan file.</p>
                </div>
              ) : (
                <div className="border rounded-lg overflow-hidden divide-y text-xs">
                  {cloudFiles.map((f: any) => (
                    <div key={f.id} className="p-3 bg-gray-50/50 hover:bg-gray-50 flex items-center justify-between transition-colors">
                      <div className="flex items-center space-x-3">
                        <div className={`p-2 rounded-lg text-white ${
                          f.provider === 'google_drive' ? 'bg-amber-500' : f.provider === 'dropbox' ? 'bg-blue-600' : 'bg-orange-500'
                        }`}>
                          <Cloud className="h-4 w-4" />
                        </div>
                        <div>
                          <div className="flex items-center space-x-2">
                            <span className="font-semibold text-gray-800 font-mono break-all">{f.filename}</span>
                            <span className={`text-[9px] px-1.5 py-0.5 rounded font-bold uppercase ${
                              f.provider === 'google_drive' ? 'bg-amber-50 text-amber-700' : f.provider === 'dropbox' ? 'bg-blue-50 text-blue-700' : 'bg-orange-50 text-orange-700'
                            }`}>
                              {f.provider.replace('_', ' ')}
                            </span>
                          </div>
                          <div className="flex space-x-3 text-[10px] text-gray-500 mt-1">
                            <span>Ukuran: <strong>{formatSize(f.size)}</strong></span>
                            <span>Disinkronkan: <strong>{new Date(f.uploadedAt).toLocaleString('id-ID')}</strong></span>
                          </div>
                        </div>
                      </div>

                      <div className="flex space-x-2 shrink-0">
                        <a 
                          href={f.url}
                          target="_blank"
                          referrerPolicy="no-referrer"
                          className="bg-white hover:bg-gray-100 text-gray-700 p-1.5 rounded-lg border border-gray-200 transition-colors flex items-center space-x-1 cursor-pointer font-semibold"
                        >
                          <ExternalLink className="h-3 w-3" />
                          <span className="hidden sm:inline">Buka Cloud Link</span>
                        </a>
                        <button
                          onClick={() => {
                            const updated = cloudFiles.filter(item => item.id !== f.id);
                            setCloudFiles(updated);
                            localStorage.setItem('simulated_cloud_files', JSON.stringify(updated));
                          }}
                          className="bg-white text-rose-600 p-1.5 rounded-lg border border-rose-200 hover:bg-rose-50 cursor-pointer transition-colors"
                          title="Hapus dari Cloud"
                        >
                          Hapus
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

        </div>

        {/* Right column (1/3 width) - Cloud Provider Integration Settings */}
        <div className="space-y-6">
          <div className="bg-white rounded-xl border border-gray-200 overflow-hidden shadow-xs">
            <div className="bg-gray-800 px-5 py-4">
              <h3 className="text-sm font-bold text-white flex items-center space-x-2">
                <Settings className="h-4 w-4 text-gray-400" />
                <span>Pengaturan Kredensial Cloud</span>
              </h3>
            </div>

            <div className="p-5 space-y-5">
              
              {/* Selector Tabs for Cloud Provider */}
              <div className="grid grid-cols-3 gap-2">
                <button
                  onClick={() => setActiveProvider('google_drive')}
                  className={`py-2 text-[11px] font-bold rounded-lg border transition-all cursor-pointer text-center ${
                    activeProvider === 'google_drive' 
                      ? 'bg-amber-50 border-amber-300 text-amber-700 ring-2 ring-amber-100' 
                      : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  Google Drive
                </button>
                <button
                  onClick={() => setActiveProvider('dropbox')}
                  className={`py-2 text-[11px] font-bold rounded-lg border transition-all cursor-pointer text-center ${
                    activeProvider === 'dropbox' 
                      ? 'bg-blue-50 border-blue-300 text-blue-700 ring-2 ring-blue-100' 
                      : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  Dropbox
                </button>
                <button
                  onClick={() => setActiveProvider('s3')}
                  className={`py-2 text-[11px] font-bold rounded-lg border transition-all cursor-pointer text-center ${
                    activeProvider === 's3' 
                      ? 'bg-orange-50 border-orange-300 text-orange-700 ring-2 ring-orange-100' 
                      : 'border-gray-200 text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  AWS S3
                </button>
              </div>

              {/* Selected Cloud Provider configuration form */}
              <div className="p-4 border rounded-lg bg-gray-50 space-y-4">
                <div className="flex items-center justify-between border-b pb-2">
                  <span className="text-xs font-bold text-gray-700">
                    {getProviderName(activeProvider)}
                  </span>
                  <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                    isConnected[activeProvider] ? 'bg-emerald-100 text-emerald-800' : 'bg-gray-200 text-gray-600'
                  }`}>
                    {isConnected[activeProvider] ? '● Terhubung' : 'Terputus'}
                  </span>
                </div>

                {activeProvider === 'google_drive' && (
                  <div className="space-y-3 text-xs">
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">OAuth Client ID</label>
                      <input 
                        type="text" 
                        readOnly 
                        value="1068613486405-google-oauth-ph.apps.googleusercontent.com" 
                        className="w-full p-2 border bg-gray-100 text-gray-500 rounded font-mono text-[10px]"
                      />
                    </div>
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">Google Drive Folder ID</label>
                      <input 
                        type="text" 
                        placeholder="Masukkan ID Folder Drive Anda (opsional)" 
                        defaultValue="drive_folder_propertyhub_backup_root_id"
                        className="w-full p-2 border bg-white rounded font-mono text-[10px] focus:outline-none focus:border-amber-400"
                      />
                    </div>
                    <p className="text-[10px] text-gray-400 leading-normal">
                      Menggunakan Google Workspace API Scopes: <code>https://www.googleapis.com/auth/drive.file</code> untuk akses upload instan file ZIP.
                    </p>
                  </div>
                )}

                {activeProvider === 'dropbox' && (
                  <div className="space-y-3 text-xs">
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">Dropbox App Access Token</label>
                      <input 
                        type="password" 
                        readOnly 
                        value="dbx-xxxxxxxxxxxxxxxxxxxx" 
                        className="w-full p-2 border bg-gray-100 text-gray-500 rounded font-mono text-[10px]"
                      />
                    </div>
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">Target Folder Path</label>
                      <input 
                        type="text" 
                        defaultValue="/Backups/PropertyHub/"
                        className="w-full p-2 border bg-white rounded font-mono text-[10px] focus:outline-none focus:border-blue-400"
                      />
                    </div>
                  </div>
                )}

                {activeProvider === 's3' && (
                  <div className="space-y-3 text-xs">
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">AWS Access Key ID</label>
                      <input 
                        type="text" 
                        readOnly 
                        value="AKIAIOSFODNN7EXAMPLE" 
                        className="w-full p-2 border bg-gray-100 text-gray-500 rounded font-mono text-[10px]"
                      />
                    </div>
                    <div className="space-y-1">
                      <label className="block font-semibold text-gray-600">AWS S3 Bucket Name</label>
                      <input 
                        type="text" 
                        defaultValue="propertyhub-backups-bucket"
                        className="w-full p-2 border bg-white rounded font-mono text-[10px] focus:outline-none focus:border-orange-400"
                      />
                    </div>
                  </div>
                )}

                {/* Connection button */}
                <div className="pt-2 border-t">
                  {isConnected[activeProvider] ? (
                    <button
                      onClick={() => disconnectProvider(activeProvider)}
                      className="w-full bg-rose-50 text-rose-700 hover:bg-rose-100 border border-rose-200 py-2 rounded-lg text-xs font-bold transition-all cursor-pointer text-center"
                    >
                      Putuskan Koneksi Cloud
                    </button>
                  ) : (
                    <button
                      onClick={() => connectProvider(activeProvider)}
                      disabled={connecting !== null}
                      className="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg text-xs font-bold transition-all cursor-pointer text-center flex items-center justify-center space-x-1.5"
                    >
                      {connecting === activeProvider ? (
                        <>
                          <Loader2 className="h-3.5 w-3.5 animate-spin text-white" />
                          <span>Menghubungkan Scopes...</span>
                        </>
                      ) : (
                        <>
                          <Link2 className="h-3.5 w-3.5" />
                          <span>Hubungkan & Otorisasi</span>
                        </>
                      )}
                    </button>
                  )}
                </div>

              </div>

              {/* Safety guidelines Box */}
              <div className="bg-gray-50 rounded-lg p-3.5 border text-[10px] text-gray-500 space-y-2 leading-relaxed">
                <span className="font-bold text-gray-700 block flex items-center space-x-1">
                  <AlertCircle className="h-3.5 w-3.5 text-blue-600 shrink-0" />
                  <span>Keamanan Kredensial & Enkripsi:</span>
                </span>
                <p>
                  Semua file codebase ZIP dienkripsi secara lokal di server sebelum ditransfer menggunakan protokol HTTPS TLS v1.3. Token OAuth Google Drive diproses melalui endpoint aman tanpa disimpan secara permanen demi menjamin privasi developer.
                </p>
              </div>

            </div>
          </div>
        </div>

      </div>
    </div>
  );
}
