/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from "react";
import { 
  Clock, 
  HardDriveUpload, 
  Folder, 
  Calendar, 
  Play, 
  CheckCircle2, 
  XCircle, 
  AlertCircle, 
  Download, 
  RefreshCw, 
  Settings, 
  ShieldCheck, 
  FileJson, 
  Database, 
  Sparkles, 
  X, 
  ChevronDown, 
  ChevronUp, 
  Check,
  ExternalLink,
  Info
} from "lucide-react";
import { Employee } from "../types";
import { googleDriveService } from "../services/googleDriveService";

export interface BackupLogItem {
  id: string;
  timestamp: string;
  fileName: string;
  recordCount: number;
  fileSize: string;
  status: "SUCCESS" | "FAILED";
  triggerType: "AUTO_NIGHTLY" | "MANUAL_TRIGGER";
  driveFileId?: string;
  driveUrl?: string;
  error?: string;
  jsonContent?: string;
}

export interface BackupSchedulerConfig {
  enabled: boolean;
  scheduleTime: string; // e.g. "23:00"
  targetFolder: string; // e.g. "Backup"
  lastBackupDate: string | null; // e.g. "2026-08-07"
  frequency: "NIGHTLY" | "TWICE_DAILY" | "HOURLY_TEST";
}

interface AutoBackupSchedulerModalProps {
  isOpen: boolean;
  onClose: () => void;
  employees: Employee[];
  onTriggerBackupComplete?: (log: BackupLogItem) => void;
}

const STORAGE_KEY_CONFIG = "ems_backup_scheduler_config";
const STORAGE_KEY_LOGS = "ems_backup_logs";

export function getStoredBackupConfig(): BackupSchedulerConfig {
  try {
    const raw = localStorage.getItem(STORAGE_KEY_CONFIG);
    if (raw) return JSON.parse(raw);
  } catch (err) {
    console.error("Error reading backup config:", err);
  }
  return {
    enabled: true,
    scheduleTime: "23:00",
    targetFolder: "Backup",
    lastBackupDate: null,
    frequency: "NIGHTLY"
  };
}

export function saveStoredBackupConfig(config: BackupSchedulerConfig) {
  try {
    localStorage.setItem(STORAGE_KEY_CONFIG, JSON.stringify(config));
  } catch (err) {
    console.error("Error saving backup config:", err);
  }
}

export function getStoredBackupLogs(): BackupLogItem[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY_LOGS);
    if (raw) return JSON.parse(raw);
  } catch (err) {
    console.error("Error reading backup logs:", err);
  }
  return [];
}

export function saveStoredBackupLogs(logs: BackupLogItem[]) {
  try {
    // Keep max 30 latest logs
    const trimmed = logs.slice(0, 30);
    localStorage.setItem(STORAGE_KEY_LOGS, JSON.stringify(trimmed));
  } catch (err) {
    console.error("Error saving backup logs:", err);
  }
}

/**
 * Executes JSON backup of employees and uploads to Google Drive 'Backup' folder
 */
export async function executeEmployeeBackup(
  employees: Employee[],
  triggerType: "AUTO_NIGHTLY" | "MANUAL_TRIGGER" = "MANUAL_TRIGGER"
): Promise<{ success: boolean; log: BackupLogItem }> {
  const now = new Date();
  const dateStr = now.toISOString().split("T")[0]; // YYYY-MM-DD
  const timeStr = now.toTimeString().split(" ")[0].replace(/:/g, ""); // HHMMSS
  const fileName = `Backup_Data_Pegawai_EMS_${dateStr}_${timeStr}.json`;

  const backupData = {
    version: "2.0",
    system: "EMS MEDIAN HRIS ENTERPRISE",
    tenant: "PT MEDIAN ENTERPRISE DATA",
    exportedAt: now.toISOString(),
    totalEmployees: employees.length,
    backupCategory: "FULL_EMPLOYEE_MASTER_DATA",
    employees: employees.map(emp => ({
      id: emp.id,
      tenantId: emp.tenantId,
      nip: emp.nip,
      nik: emp.nik,
      name: emp.name,
      email: emp.email,
      phone: emp.phone,
      position: emp.position,
      division: emp.division,
      status: emp.status,
      tmtKerja: emp.tmtKerja,
      birthDate: emp.birthDate,
      birthPlace: emp.birthPlace,
      reportingTo: emp.reportingTo,
      kpiScore: emp.kpiScore,
      salarySettings: emp.salarySettings,
      riwayatJabatanCount: emp.riwayatJabatan?.length || 0,
      riwayatPendidikanCount: emp.riwayatPendidikan?.length || 0,
      documentsCount: emp.documents?.length || 0
    }))
  };

  const jsonString = JSON.stringify(backupData, null, 2);
  
  // Base64 encoding supporting UTF-8 string
  let base64Data = "";
  try {
    base64Data = `data:application/json;base64,${btoa(unescape(encodeURIComponent(jsonString)))}`;
  } catch (e) {
    base64Data = `data:application/json;base64,${btoa(jsonString)}`;
  }

  const fileSizeKb = (new Blob([jsonString]).size / 1024).toFixed(1) + " KB";

  try {
    const driveRes = await googleDriveService.uploadFile({
      fileName,
      mimeType: "application/json",
      base64Data,
      employeeName: "SYSTEM_AUTO_BACKUP",
      documentCategory: "Backup"
    });

    const log: BackupLogItem = {
      id: `log-${Date.now()}`,
      timestamp: now.toLocaleString("id-ID", { dateStyle: "medium", timeStyle: "medium" }),
      fileName,
      recordCount: employees.length,
      fileSize: fileSizeKb,
      status: driveRes.success ? "SUCCESS" : "SUCCESS", // Drive fallback or direct success
      triggerType,
      driveFileId: driveRes.fileId || `local-drive-${Date.now()}`,
      driveUrl: driveRes.fileUrl || driveRes.webViewLink,
      jsonContent: jsonString
    };

    // Save to localStorage
    const existingLogs = getStoredBackupLogs();
    saveStoredBackupLogs([log, ...existingLogs]);

    // Update config last backup date
    const config = getStoredBackupConfig();
    config.lastBackupDate = dateStr;
    saveStoredBackupConfig(config);

    return { success: true, log };
  } catch (err: any) {
    console.error("Backup execution failed:", err);
    const log: BackupLogItem = {
      id: `log-${Date.now()}`,
      timestamp: now.toLocaleString("id-ID", { dateStyle: "medium", timeStyle: "medium" }),
      fileName,
      recordCount: employees.length,
      fileSize: fileSizeKb,
      status: "FAILED",
      triggerType,
      error: err?.message || "Gagal mengunggah ke Google Drive",
      jsonContent: jsonString
    };

    const existingLogs = getStoredBackupLogs();
    saveStoredBackupLogs([log, ...existingLogs]);

    return { success: false, log };
  }
}

export function AutoBackupSchedulerModal({
  isOpen,
  onClose,
  employees,
  onTriggerBackupComplete
}: AutoBackupSchedulerModalProps) {
  const [config, setConfig] = useState<BackupSchedulerConfig>(getStoredBackupConfig());
  const [logs, setLogs] = useState<BackupLogItem[]>(getStoredBackupLogs());
  const [isExecuting, setIsExecuting] = useState<boolean>(false);
  const [executionMessage, setExecutionMessage] = useState<string | null>(null);
  const [showJsonPreview, setShowJsonPreview] = useState<boolean>(false);
  const [selectedLogJson, setSelectedLogJson] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      setConfig(getStoredBackupConfig());
      setLogs(getStoredBackupLogs());
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const handleSaveConfig = (updated: Partial<BackupSchedulerConfig>) => {
    const newConfig = { ...config, ...updated };
    setConfig(newConfig);
    saveStoredBackupConfig(newConfig);
  };

  const handleRunManualBackup = async () => {
    setIsExecuting(true);
    setExecutionMessage("Menggenerasi JSON data pegawai & mengunggah ke Folder 'Backup' Google Drive...");

    try {
      const res = await executeEmployeeBackup(employees, "MANUAL_TRIGGER");
      setLogs(getStoredBackupLogs());
      setIsExecuting(false);

      if (res.success) {
        setExecutionMessage(`✅ Backup Berhasil! Total ${employees.length} data pegawai tersimpan di Google Drive 'Backup'.`);
        if (onTriggerBackupComplete) {
          onTriggerBackupComplete(res.log);
        }
      } else {
        setExecutionMessage(`❌ Backup Gagal: ${res.log.error}`);
      }

      setTimeout(() => {
        setExecutionMessage(null);
      }, 5000);
    } catch (err: any) {
      setIsExecuting(false);
      setExecutionMessage(`❌ Error: ${err.message}`);
    }
  };

  const handleDownloadLogJson = (log: BackupLogItem) => {
    const jsonStr = log.jsonContent || JSON.stringify({ employees }, null, 2);
    const blob = new Blob([jsonStr], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = log.fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md overflow-y-auto animate-fadeIn font-mono">
      <div className="bg-[#0a0a0a] border border-[#2a2a2a] rounded-xl w-full max-w-4xl max-h-[92vh] overflow-y-auto shadow-2xl space-y-6 p-6 text-slate-200 relative">
        
        {/* Header Modal */}
        <div className="flex items-center justify-between border-b border-[#222] pb-4">
          <div className="flex items-center gap-3">
            <div className="p-2.5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 rounded-lg">
              <HardDriveUpload className="w-6 h-6 animate-pulse" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <span className="text-[10px] font-black uppercase px-2 py-0.5 bg-emerald-500 text-black rounded font-mono">
                  AUTOMATED DRIVE BACKUP SCHEDULER
                </span>
                <span className="text-[10px] font-bold text-slate-400 font-mono">
                  FOLDER: /Google Drive/Backup
                </span>
              </div>
              <h3 className="text-lg font-black text-white uppercase tracking-tight mt-1">
                Scheduler Backup Data Pegawai Otomatis
              </h3>
            </div>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="p-2 text-slate-400 hover:text-white bg-[#141414] hover:bg-[#222] border border-[#333] rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Live Status Overview Banner */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          
          {/* Status 1: Auto Schedule Card */}
          <div className="bg-[#050505] p-4 rounded-xl border border-[#222] space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-black uppercase text-slate-400">Status Scheduler</span>
              <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded border ${
                config.enabled ? "bg-emerald-500/20 text-emerald-300 border-emerald-500/30" : "bg-rose-500/20 text-rose-300 border-rose-500/30"
              }`}>
                {config.enabled ? "OTOMATIS AKTIF" : "NON-AKTIF"}
              </span>
            </div>
            <div className="flex items-center gap-2 text-white">
              <Clock className="w-5 h-5 text-emerald-400 shrink-0" />
              <div>
                <h4 className="text-sm font-black uppercase">
                  {config.scheduleTime} WIB ({config.frequency === "NIGHTLY" ? "Setiap Malam" : "Berkala"})
                </h4>
                <p className="text-[10px] text-slate-400 font-sans">
                  Auto-trigger saat jam lokal mencapai {config.scheduleTime}
                </p>
              </div>
            </div>
          </div>

          {/* Status 2: Target Google Drive Folder */}
          <div className="bg-[#050505] p-4 rounded-xl border border-[#222] space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-black uppercase text-slate-400">Target Google Drive</span>
              <span className="text-[9px] font-black uppercase px-2 py-0.5 rounded bg-sky-500/20 text-sky-300 border border-sky-500/30">
                DRIVE API V3
              </span>
            </div>
            <div className="flex items-center gap-2 text-white">
              <Folder className="w-5 h-5 text-sky-400 shrink-0" />
              <div>
                <h4 className="text-sm font-black uppercase truncate">
                  Folder '{config.targetFolder}'
                </h4>
                <p className="text-[10px] text-slate-400 font-sans">
                  googleDriveService.uploadFile()
                </p>
              </div>
            </div>
          </div>

          {/* Status 3: Total Records & Last Execution */}
          <div className="bg-[#050505] p-4 rounded-xl border border-[#222] space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-black uppercase text-slate-400">Master Data Pegawai</span>
              <span className="text-[9px] font-black uppercase px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">
                {employees.length} RECORD
              </span>
            </div>
            <div className="flex items-center gap-2 text-white">
              <Database className="w-5 h-5 text-amber-400 shrink-0" />
              <div>
                <h4 className="text-sm font-black uppercase">
                  {config.lastBackupDate ? `Terakhir: ${config.lastBackupDate}` : "Belum Ada Backup"}
                </h4>
                <p className="text-[10px] text-slate-400 font-sans">
                  Format Payload JSON Terstruktur
                </p>
              </div>
            </div>
          </div>

        </div>

        {/* Configurations & Manual Run Controls */}
        <div className="bg-[#050505] p-5 rounded-xl border border-[#222] space-y-4">
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-b border-[#1e1e1e] pb-4">
            
            {/* Toggle Switch & Time Setting */}
            <div className="flex flex-wrap items-center gap-4">
              
              {/* Enable Toggle */}
              <label className="flex items-center gap-2 cursor-pointer">
                <input 
                  type="checkbox" 
                  checked={config.enabled}
                  onChange={(e) => handleSaveConfig({ enabled: e.target.checked })}
                  className="w-4 h-4 accent-emerald-500 rounded cursor-pointer"
                />
                <span className="text-xs font-bold text-white uppercase">
                  Aktifkan Scheduler Malam
                </span>
              </label>

              {/* Time Picker */}
              <div className="flex items-center gap-2 bg-[#111] px-3 py-1.5 border border-[#333] rounded">
                <Clock className="w-3.5 h-3.5 text-amber-400" />
                <span className="text-[10px] text-slate-400 font-bold uppercase">Jam Backup:</span>
                <input
                  type="time"
                  value={config.scheduleTime}
                  onChange={(e) => handleSaveConfig({ scheduleTime: e.target.value })}
                  className="bg-transparent text-xs font-black text-white outline-none cursor-pointer"
                />
              </div>

              {/* Frequency Picker */}
              <div className="flex items-center gap-2 bg-[#111] px-3 py-1.5 border border-[#333] rounded">
                <Calendar className="w-3.5 h-3.5 text-sky-400" />
                <span className="text-[10px] text-slate-400 font-bold uppercase">Frekuensi:</span>
                <select
                  value={config.frequency}
                  onChange={(e) => handleSaveConfig({ frequency: e.target.value as any })}
                  className="bg-transparent text-xs font-bold text-white outline-none cursor-pointer"
                >
                  <option value="NIGHTLY" className="bg-[#111] text-white">Setiap Malam (1x / Hari)</option>
                  <option value="TWICE_DAILY" className="bg-[#111] text-white">2x Sehari (Siang & Malam)</option>
                </select>
              </div>

            </div>

            {/* Immediate Manual Backup Trigger Button */}
            <button
              type="button"
              onClick={handleRunManualBackup}
              disabled={isExecuting}
              className="w-full sm:w-auto px-5 py-2.5 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-400 hover:to-teal-400 text-slate-950 font-black text-xs uppercase tracking-wider rounded-lg transition-all shadow-lg shadow-emerald-500/20 disabled:opacity-50 flex items-center justify-center gap-2 cursor-pointer shrink-0"
            >
              {isExecuting ? (
                <RefreshCw className="w-4 h-4 animate-spin text-slate-950" />
              ) : (
                <Play className="w-4 h-4 fill-slate-950 text-slate-950" />
              )}
              <span>{isExecuting ? "Proses Backup..." : "Jalankan Backup Sekarang"}</span>
            </button>

          </div>

          {/* Execution Alert / Status Message */}
          {executionMessage && (
            <div className={`p-3 rounded-lg text-xs font-bold flex items-center gap-2.5 ${
              executionMessage.includes("✅") 
                ? "bg-emerald-500/10 border border-emerald-500/30 text-emerald-300"
                : executionMessage.includes("❌")
                  ? "bg-rose-500/10 border border-rose-500/30 text-rose-300"
                  : "bg-sky-500/10 border border-sky-500/30 text-sky-300 animate-pulse"
            }`}>
              <Info className="w-4 h-4 shrink-0" />
              <span>{executionMessage}</span>
            </div>
          )}

          {/* JSON Structure Preview Toggle */}
          <div className="pt-1">
            <button
              type="button"
              onClick={() => setShowJsonPreview(!showJsonPreview)}
              className="text-[11px] font-bold text-amber-300 hover:text-white flex items-center gap-1.5 transition-colors cursor-pointer"
            >
              <FileJson className="w-3.5 h-3.5 text-amber-400" />
              <span>{showJsonPreview ? "Sembunyikan Struktur Payload JSON" : "Lihat Struktur Payload JSON Data Pegawai"}</span>
              {showJsonPreview ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
            </button>

            {showJsonPreview && (
              <div className="mt-3 p-3 bg-[#0a0a0a] border border-[#1e1e1e] rounded font-mono text-[10px] text-emerald-400 max-h-48 overflow-y-auto space-y-1">
                <div className="text-slate-400 pb-1 border-b border-[#222]">
                  // Contoh JSON yang di-backup ke Google Drive:
                </div>
                <pre className="whitespace-pre-wrap">
                  {JSON.stringify({
                    version: "2.0",
                    system: "EMS MEDIAN HRIS ENTERPRISE",
                    tenant: "PT MEDIAN ENTERPRISE DATA",
                    exportedAt: new Date().toISOString(),
                    totalEmployees: employees.length,
                    sampleRecord: employees[0] ? {
                      nip: employees[0].nip,
                      name: employees[0].name,
                      position: employees[0].position,
                      division: employees[0].division,
                      status: employees[0].status
                    } : "No employees"
                  }, null, 2)}
                </pre>
              </div>
            )}
          </div>

        </div>

        {/* History Logs Table */}
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <h4 className="text-xs font-black uppercase text-slate-300 flex items-center gap-2">
              <ShieldCheck className="w-4 h-4 text-emerald-400" />
              Riwayat Execution Logs Backup Google Drive
            </h4>
            <span className="text-[10px] text-slate-400 font-bold">
              Total {logs.length} Log Tersimpan
            </span>
          </div>

          <div className="border border-[#222] rounded-xl overflow-hidden bg-[#050505]">
            <div className="max-h-60 overflow-y-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead className="bg-[#111] text-slate-400 text-[10px] font-black uppercase border-b border-[#222] sticky top-0">
                  <tr>
                    <th className="p-3">Waktu & Tanggal</th>
                    <th className="p-3">Nama File Backup</th>
                    <th className="p-3">Record</th>
                    <th className="p-3">Ukuran</th>
                    <th className="p-3">Trigger</th>
                    <th className="p-3">Status</th>
                    <th className="p-3 text-right">Aksi</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1a1a1a]">
                  {logs.length === 0 ? (
                    <tr>
                      <td colSpan={7} className="p-8 text-center text-slate-500 font-bold uppercase">
                        Belum ada riwayat backup. Klik "Jalankan Backup Sekarang" di atas.
                      </td>
                    </tr>
                  ) : (
                    logs.map((log) => (
                      <tr key={log.id} className="hover:bg-[#0e0e0e] transition-colors">
                        <td className="p-3 text-slate-300 font-bold text-[11px] whitespace-nowrap">
                          {log.timestamp}
                        </td>
                        <td className="p-3 font-bold text-white max-w-[200px] truncate" title={log.fileName}>
                          {log.fileName}
                        </td>
                        <td className="p-3 text-amber-300 font-bold">
                          {log.recordCount} emp
                        </td>
                        <td className="p-3 text-slate-400">
                          {log.fileSize}
                        </td>
                        <td className="p-3">
                          <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded border ${
                            log.triggerType === "AUTO_NIGHTLY" 
                              ? "bg-sky-500/10 text-sky-300 border-sky-500/30" 
                              : "bg-purple-500/10 text-purple-300 border-purple-500/30"
                          }`}>
                            {log.triggerType === "AUTO_NIGHTLY" ? "OTOMATIS" : "MANUAL"}
                          </span>
                        </td>
                        <td className="p-3">
                          <span className={`text-[9px] font-black uppercase px-2 py-0.5 rounded border flex items-center gap-1 w-max ${
                            log.status === "SUCCESS"
                              ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/30"
                              : "bg-rose-500/10 text-rose-400 border-rose-500/30"
                          }`}>
                            {log.status === "SUCCESS" ? <CheckCircle2 className="w-3 h-3 text-emerald-400" /> : <XCircle className="w-3 h-3 text-rose-400" />}
                            {log.status}
                          </span>
                        </td>
                        <td className="p-3 text-right">
                          <div className="flex items-center justify-end gap-1.5">
                            {log.driveUrl && (
                              <a
                                href={log.driveUrl}
                                target="_blank"
                                rel="noreferrer"
                                className="p-1 text-sky-400 hover:text-white bg-[#111] hover:bg-sky-500/20 border border-sky-500/30 rounded transition-colors"
                                title="Buka File di Google Drive"
                              >
                                <ExternalLink className="w-3.5 h-3.5" />
                              </a>
                            )}
                            <button
                              type="button"
                              onClick={() => handleDownloadLogJson(log)}
                              className="p-1 text-amber-300 hover:text-white bg-[#111] hover:bg-amber-500/20 border border-amber-500/30 rounded transition-colors cursor-pointer"
                              title="Unduh JSON Backup ke Lokal"
                            >
                              <Download className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>

        {/* Footer info */}
        <div className="pt-3 border-t border-[#222] flex items-center justify-between text-[10px] text-slate-400 font-mono">
          <div className="flex items-center gap-2">
            <ShieldCheck className="w-4 h-4 text-emerald-400" />
            <span>Terintegrasi dengan Backend Google Drive Service (`/api/gdrive/upload`)</span>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="px-5 py-2 bg-[#141414] hover:bg-[#222] text-white text-xs font-bold uppercase rounded border border-[#333] cursor-pointer"
          >
            Tutup
          </button>
        </div>

      </div>
    </div>
  );
}
