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

import React, { useState } from 'react';
import { motion } from 'motion/react';
import { 
  Settings, 
  Database, 
  Cloud, 
  Upload, 
  Download, 
  Check, 
  AlertCircle, 
  Lock, 
  Wifi, 
  WifiOff, 
  RefreshCw,
  Coins,
  Receipt,
  RotateCcw
} from 'lucide-react';
import { SystemSettings } from '../types';
import { encryptData, decryptData } from '../utils/backup';

interface SettingsProps {
  settings: SystemSettings;
  isOnline: boolean;
  onUpdateSettings: (settings: SystemSettings) => void;
  onToggleOnlineMode: () => void;
  onRestoreDatabase: (restoredData: {
    settings: SystemSettings;
    products: any[];
    invoices: any[];
    history: any[];
    staff: any[];
  }) => void;
  onClearCacheToDefault: () => void;
  // Passing actual values for backup compilation
  activeProducts: any[];
  activeInvoices: any[];
  activeHistory: any[];
  activeStaff: any[];
}

export default function SettingsComponent({
  settings,
  isOnline,
  onUpdateSettings,
  onToggleOnlineMode,
  onRestoreDatabase,
  onClearCacheToDefault,
  activeProducts,
  activeInvoices,
  activeHistory,
  activeStaff
}: SettingsProps) {
  // Input states
  const [shopName, setShopName] = useState(settings.shopName);
  const [shopAddress, setShopAddress] = useState(settings.shopAddress);
  const [shopPhone, setShopPhone] = useState(settings.shopPhone);
  const [taxName, setTaxName] = useState(settings.taxName);
  const [taxRate, setTaxRate] = useState(settings.taxRate);
  const [currencyCode, setCurrencyCode] = useState(settings.currencyCode);
  const [currencySymbol, setCurrencySymbol] = useState(settings.currencySymbol);

  // Backup vault password block
  const [vaultPassword, setVaultPassword] = useState('haider_secret_2026');
  const [uploadedCipherString, setUploadedCipherString] = useState('');
  const [backupLogs, setBackupLogs] = useState<string[]>(["Secure Vault active. Ready for ledger encryption."]);
  const [syncingCloud, setSyncingCloud] = useState(false);

  const handleSaveSettingsSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!shopName.trim() || !shopAddress.trim()) {
      alert("Corporate name and address parameters are required.");
      return;
    }

    onUpdateSettings({
      shopName: shopName.trim(),
      shopAddress: shopAddress.trim(),
      shopPhone: shopPhone.trim(),
      taxName: taxName.trim(),
      taxRate: Math.max(0, parseFloat(taxRate.toString()) || 0),
      currencyCode: currencyCode.trim(),
      currencySymbol: currencySymbol.trim()
    });

    alert("Corporate shop parameters synced across live terminal databases.");
  };

  // Compile full database and export as locally encrypted block file (.hbtback)
  const compileAndDownloadBackup = () => {
    try {
      const fullPackage = {
        meta: {
          timestamp: new Date().toISOString(),
          version: "HBT-VAULT-2.0.0",
          author: "Haider Brother Traders"
        },
        settings,
        products: activeProducts,
        invoices: activeInvoices,
        history: activeHistory,
        staff: activeStaff
      };

      const plainText = JSON.stringify(fullPackage);
      const encrypted = encryptData(plainText, vaultPassword);

      // Create download elements
      const blob = new Blob([encrypted], { type: 'text/plain;charset=utf-8' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      const dateStr = new Date().toISOString().split('T')[0];
      link.download = `HBT_Vault_Backup_${dateStr}.hbtback`;
      link.click();

      setBackupLogs(prev => [
        `[${new Date().toLocaleTimeString()}] Secure Backup compiled: Encrypted ${activeInvoices.length} transactions and ${activeProducts.length} tire SKUs.`,
        ...prev
      ]);
      alert("Ledger Vault encrypted file downloaded to client machine successfully!");

    } catch (err: any) {
      alert("Encryption failure: " + err.message);
    }
  };

  // Read decrypted cipher files and trigger restore
  const handleUploadAndRestore = (fileContent: string) => {
    if (!fileContent.trim()) {
      alert("File is empty. Select a valid .hbtback backup.");
      return;
    }

    try {
      const plainText = decryptData(fileContent, vaultPassword);
      const decoded = JSON.parse(plainText);

      // Simple schema structure audit
      if (!decoded.settings || !decoded.products || !decoded.invoices || !decoded.history || !decoded.staff) {
        throw new Error("Target file has correct password but missing necessary entity logs.");
      }

      onRestoreDatabase({
        settings: decoded.settings,
        products: decoded.products,
        invoices: decoded.invoices,
        history: decoded.history,
        staff: decoded.staff
      });

      // Update local values instantly
      setShopName(decoded.settings.shopName);
      setShopAddress(decoded.settings.shopAddress);
      setShopPhone(decoded.settings.shopPhone);
      setTaxName(decoded.settings.taxName);
      setTaxRate(decoded.settings.taxRate);
      setCurrencyCode(decoded.settings.currencyCode);
      setCurrencySymbol(decoded.settings.currencySymbol);

      setBackupLogs(prev => [
        `[${new Date().toLocaleTimeString()}] Restore complete: Imported ${decoded.invoices.length} invoices, ${decoded.products.length} tires and verified cashier registers.`,
        ...prev
      ]);
      alert("Encrypted vault records imported and restored successfully!");
    } catch (err: any) {
      alert("Restoration Blocked! Error: " + err.message);
    }
  };

  // Drag and drop file reader
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      const txt = event.target?.result as string;
      handleUploadAndRestore(txt);
    };
    reader.readAsText(file);
  };

  // Cloud Backups sync mock log
  const handleCloudSyncTrigger = () => {
    setSyncingCloud(true);
    setBackupLogs(prev => [`[${new Date().toLocaleTimeString()}] Securing cloud payload connection to Google Cloud Run servers...`, ...prev]);
    
    setTimeout(() => {
      setSyncingCloud(false);
      setBackupLogs(prev => [
        `[${new Date().toLocaleTimeString()}] Cloud backup synced! Encrypted cache saved under vault block. Transaction status: EXCELLENT.`,
        ...prev
      ]);
      alert("Cloud Backup Synced! All sensitive business records securely logged to secondary vault storage.");
    }, 1500);
  };

  const handleResetConfirm = () => {
    if (confirm("Are you absolutely sure you want to restore the entire tire shop back to default factory parameters? This deletes custom added items, current stock manual adjustments, and any newly compiled invoice draft data.")) {
      onClearCacheToDefault();
      window.location.reload();
    }
  };

  // Quick Currency Preset selection
  const selectCurrencyPreset = (code: string, symbol: string) => {
    setCurrencyCode(code);
    setCurrencySymbol(symbol);
  };

  return (
    <div className="space-y-6" id="terminal-settings-layout">
      {/* Splits layout settings versus encrypted backups */}
      <div className="grid grid-cols-1 xl:grid-cols-12 gap-6">
        {/* LEFT COLUMN: Corporate & System settings */}
        <div className="xl:col-span-7 bg-white border border-slate-200 rounded-xl p-5 shadow-sm space-y-6">
          <div className="flex items-center gap-2 border-b border-slate-100 pb-4 uppercase">
            <Settings className="w-5 h-5 text-slate-700 animate-spin" style={{ animationDuration: '6s' }} />
            <span className="text-xs font-bold text-slate-900">Corporate Terminal Configurations</span>
          </div>

          <form onSubmit={handleSaveSettingsSubmit} className="space-y-4 text-xs font-sans">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase">Corporate Shop Name</label>
                <input 
                  type="text"
                  value={shopName}
                  onChange={(e)=>setShopName(e.target.value)}
                  className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition"
                />
              </div>

              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase">Shop Phone Helpline</label>
                <input 
                  type="text"
                  value={shopPhone}
                  onChange={(e)=>setShopPhone(e.target.value)}
                  className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="text-[10px] text-slate-500 font-bold uppercase">Physical Address Coordinates</label>
              <input 
                type="text"
                value={shopAddress}
                onChange={(e)=>setShopAddress(e.target.value)}
                className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2.5 font-semibold transition"
              />
            </div>

            {/* CURRENCY INTEGRATION CHANGER */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-slate-850 flex items-center gap-1">
                  <Coins className="w-4 h-4 text-slate-700" />
                  Local Currency Integration
                </span>
                <span className="text-[10px] bg-slate-950 text-white font-mono font-medium px-2 py-0.5 rounded-md">
                  Active Preset: {currencyCode} ({currencySymbol})
                </span>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Currency Symbol</label>
                  <input 
                    type="text"
                    value={currencySymbol}
                    placeholder="e.g. ₨"
                    onChange={(e)=>setCurrencySymbol(e.target.value)}
                    className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono text-center font-bold"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Currency Code</label>
                  <input 
                    type="text"
                    value={currencyCode}
                    placeholder="e.g. PKR"
                    onChange={(e)=>setCurrencyCode(e.target.value)}
                    className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono text-center font-bold"
                  />
                </div>

                {/* Instant Presets */}
                <div className="space-y-1 flex flex-col justify-end">
                  <label className="text-[9px] text-slate-400 font-bold uppercase leading-none block mb-1">Fast Symbol Presets</label>
                  <div className="flex gap-1 justify-between font-mono font-semibold">
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('PKR', '₨')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      ₨ PKR
                    </button>
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('USD', '$')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      $ USD
                    </button>
                    <button 
                      type="button"
                      onClick={() => selectCurrencyPreset('AED', 'د.إ')}
                      className="px-2 py-1.5 border border-slate-200 bg-white hover:bg-slate-50 text-[10px] rounded-md flex-1 cursor-pointer"
                    >
                      د.إ AED
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* TAX COMPILATION STRUCTURE */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-3">
              <div className="flex items-center gap-1.5 text-xs font-bold text-slate-850">
                <Receipt className="w-4 h-4 text-slate-700 font-medium" />
                Automated Tax Calculation Engine
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Tax Designation Name</label>
                  <input 
                    type="text"
                    value={taxName}
                    placeholder="e.g. Sales Tax (SRB)"
                    onChange={(e)=>setTaxName(e.target.value)}
                    className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2"
                  />
                </div>

                <div className="space-y-1">
                  <label className="text-[9px] text-slate-400 font-bold uppercase">Combined Tax Rate (%)</label>
                  <input 
                    type="number"
                    step="0.1"
                    min="0"
                    max="90"
                    value={taxRate}
                    onChange={(e)=>setTaxRate(Math.min(90, Math.max(0, parseFloat(e.target.value) || 0)))}
                    className="w-full border border-slate-200 bg-white outline-none focus:border-slate-800 rounded-lg p-2 font-mono font-bold"
                  />
                </div>
              </div>
              <p className="text-[10px] text-slate-400 leading-normal italic">
                * When set, invoice generator computes total by multiplying subtotal against rating index, subtracting items discounts instantly.
              </p>
            </div>

            {/* OFFLINE MANAGE STATE */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg flex items-center justify-between gap-4">
              <div className="space-y-1">
                <span className="text-xs font-bold text-slate-850 flex items-center gap-1">
                  {isOnline ? <Wifi className="w-4 h-4 text-emerald-600 animate-pulse" /> : <WifiOff className="w-4 h-4 text-orange-655" />}
                  Offline Mode Simulator
                </span>
                <p className="text-[10px] text-slate-400 leading-normal">
                  Turn offline mode on/off to test local caching queue and receipt buffer logs.
                </p>
              </div>

              <button
                type="button"
                onClick={onToggleOnlineMode}
                className={`text-xs font-semibold px-3.5 py-2.5 rounded-lg border transition shadow-sm cursor-pointer ${
                  isOnline 
                    ? 'bg-slate-900 border-transparent text-white hover:bg-slate-800' 
                    : 'bg-orange-600 border-transparent text-white hover:bg-orange-550'
                }`}
              >
                {isOnline ? "Simulate Disconnection" : "Connect Online Mode"}
              </button>
            </div>

            <div className="flex gap-4">
              <button 
                type="button"
                onClick={handleResetConfirm}
                className="bg-slate-50 hover:bg-slate-100 text-red-650 hover:text-red-750 font-medium border border-slate-200 px-4 py-2.5 rounded-lg transition cursor-pointer flex items-center gap-1.5 shadow-sm"
              >
                <RotateCcw className="w-4 h-4" />
                Wipe Local Database
              </button>
              <button
                type="submit"
                className="flex-1 bg-slate-900 hover:bg-slate-800 text-white font-medium text-xs px-6 py-2.5 rounded-lg transition cursor-pointer shadow flex items-center justify-center gap-2"
              >
                <Check className="w-4 h-4" />
                Commit Corporate Settings
              </button>
            </div>
          </form>
        </div>

        {/* RIGHT COLUMN: Encrypted Cloud Backups */}
        <div className="xl:col-span-5 bg-white border border-slate-200 rounded-xl p-5 shadow-sm flex flex-col justify-between">
          <div className="space-y-5">
            <div className="flex items-center gap-2 border-b border-slate-100 pb-4 uppercase">
              <Database className="w-4.5 h-4.5 text-slate-800 font-bold" />
              <span className="text-xs font-bold text-slate-900">Encrypted Backups Vault</span>
            </div>

            {/* Explainer warning */}
            <div className="bg-slate-50 border border-slate-200 p-4 rounded-lg space-y-1.5 text-xs text-slate-500">
              <span className="font-extrabold text-slate-800 flex items-center gap-1 uppercase tracking-wider text-[10px]">
                <Lock className="w-3.5 h-3.5 text-slate-705" />
                End-To-End Security Enforced
              </span>
              <p className="leading-relaxed text-[11px] text-slate-400">
                Under air-gapped terminal paradigms, Haider Brother Traders database is encrypted using rot-salt character ciphers with customized credentials keyframes. Passwords block third-party parsing.
              </p>
            </div>

            <div className="space-y-3 font-sans text-xs">
              <div className="space-y-1">
                <label className="text-[10px] text-slate-500 font-bold uppercase block text-center">Master Encryption Key / Cipher password</label>
                <input 
                  type="password"
                  value={vaultPassword}
                  onChange={(e) => setVaultPassword(e.target.value)}
                  className="w-full border border-slate-200 bg-white p-2.5 font-mono text-slate-800 rounded-lg outline-none focus:border-slate-800 shadow-sm text-center tracking-widest text-sm"
                />
              </div>

              {/* Action buttons */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={compileAndDownloadBackup}
                  className="bg-slate-900 hover:bg-slate-800 text-white text-xs font-medium py-2.5 px-3 rounded-lg flex items-center justify-center gap-1.5 shadow-sm transition cursor-pointer"
                >
                  <Download className="w-4 h-4" />
                  Save Secure Backup File
                </button>

                {/* Simulated live cloud database upload sync */}
                <button
                  type="button"
                  disabled={syncingCloud}
                  onClick={handleCloudSyncTrigger}
                  className="bg-white hover:bg-slate-100 text-slate-800 border border-slate-200 text-xs font-medium py-2.5 px-3 rounded-lg flex items-center justify-center gap-1.5 shadow-sm transition cursor-pointer"
                >
                  <Cloud className="w-4 h-4 text-slate-755" />
                  {syncingCloud ? "Uploading cipher..." : "Syndicate Cloud Backup"}
                </button>
              </div>

              {/* Restore drag files */}
              <div className="space-y-1 pt-2">
                <label className="text-[10px] text-slate-500 font-bold uppercase block mb-1">Import &amp; Restore Encrypted hbtback file</label>
                <div className="border border-dashed border-slate-200 rounded-lg p-4 text-center hover:bg-slate-50 bg-slate-50/50 transition relative flex flex-col items-center justify-center gap-2">
                  <Upload className="w-5 h-5 text-slate-400 font-light" />
                  <span className="text-[10px] text-slate-400">Drag or select a certified (.hbtback) document</span>
                  <input 
                    type="file" 
                    accept=".hbtback,.txt"
                    onChange={handleFileSelect}
                    className="absolute inset-0 opacity-0 cursor-pointer"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Secure cryptographic logs console view */}
          <div className="space-y-2 mt-6">
            <span className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Cryptographic Secure Actions Telemetry</span>
            <div className="bg-slate-900 text-emerald-400 font-mono text-[10px] p-4 rounded-lg max-h-40 overflow-y-auto pr-1 leading-relaxed border border-slate-850 shadow-inner">
              {backupLogs.map((log, i) => (
                <div key={i} className="pb-1 border-b border-white/5 last:border-0">{log}</div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
