/* Admin Settings with Database Import / Export functionality */
'use client';

import { useState, useEffect } from 'react';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Download, Upload, Database, AlertTriangle, Loader2, KeyRound, Server, CheckCircle2, XCircle, Eye, EyeOff, Wifi } from 'lucide-react';
import { createClient } from '@/lib/supabase/client';
import { saveLicServerConfig, testLicServerConnection } from '@/lib/actions/licserver-config';
import { useRouter } from 'next/navigation';

export default function AdminSettings() {
  const [demoActive, setDemoActive] = useState(true);
  const [exporting, setExporting] = useState(false);
  const [importing, setImporting] = useState(false);
  const [statusMsg, setStatusMsg] = useState('');
  const [statusType, setStatusType] = useState<'success' | 'error' | 'info' | ''>('');
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(true);

  // LicServer Config State
  const [licUrl, setLicUrl] = useState('');
  const [licKey, setLicKey] = useState('');
  const [showKey, setShowKey] = useState(false);
  const [licSaving, setLicSaving] = useState(false);
  const [licTesting, setLicTesting] = useState(false);
  const [licStatus, setLicStatus] = useState<{ ok: boolean; message: string } | null>(null);
  const [licMsg, setLicMsg] = useState('');
  const [licMsgType, setLicMsgType] = useState<'success' | 'error' | ''>('');
  const router = useRouter();

  useEffect(() => {
    async function checkAccess() {
      try {
        const supabase = createClient();
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) {
          router.push('/auth/login');
          return;
        }
        const { data: userData, error: userError } = await supabase
          .from('users')
          .select('role')
          .eq('id', user.id)
          .single();

        if (userError || !userData || userData.role === 'verwaltung') {
          router.push('/admin');
          return;
        }

        const state = localStorage.getItem('demo_banner_disabled') !== 'true';
        setDemoActive(state);

        // Load current LicServer config from DB
        try {
          const { data: licRow } = await supabase
            .from('settings')
            .select('licserver_base_url, licserver_api_key')
            .eq('id', 'licserver')
            .single();
          if (licRow) {
            setLicUrl(licRow.licserver_base_url || '');
            setLicKey(licRow.licserver_api_key || '');
          }
        } catch (dbErr) {
          console.error("Fehler beim Laden der LicServer-Einstellungen:", dbErr);
        }
      } catch (err) {
        console.error("Fehler bei checkAccess in Einstellungen:", err);
      } finally {
        setLoading(false);
      }
    }
    checkAccess();
  }, [router]);

  const toggleDemo = (checked: boolean) => {
    setDemoActive(checked);
    localStorage.setItem('demo_banner_disabled', (!checked).toString());
    window.dispatchEvent(new Event('storage_demo_changed'));
  };

  const handleExport = async () => {
    setExporting(true);
    setStatusMsg('Export läuft...');
    setStatusType('info');
    try {
      const res = await fetch('/api/admin/db-backup');
      if (!res.ok) throw new Error('Export fehlgeschlagen');

      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `webshop_backup_${new Date().toISOString().split('T')[0]}.zip`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
      setStatusMsg('Export erfolgreich abgeschlossen.');
      setStatusType('success');
    } catch (err: any) {
      console.error(err);
      setStatusMsg(`Fehler beim Export: ${err.message}`);
      setStatusType('error');
    } finally {
      setExporting(false);
    }
  };

  const handleImport = async () => {
    if (!selectedFile) return;
    if (!confirm('ACHTUNG: Dies löscht und überschreibt alle aktuellen Datenbankinhalte in dieser Instanz. Möchten Sie wirklich fortfahren?')) {
      return;
    }
    setImporting(true);
    setStatusMsg('Import läuft...');
    setStatusType('info');
    try {
      const formData = new FormData();
      formData.append('file', selectedFile);

      const res = await fetch('/api/admin/db-backup', {
        method: 'POST',
        body: formData,
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Import fehlgeschlagen');

      setStatusMsg('Datenbank erfolgreich importiert!');
      setStatusType('success');
      setSelectedFile(null);
    } catch (err: any) {
      console.error(err);
      setStatusMsg(`Fehler beim Import: ${err.message}`);
      setStatusType('error');
    } finally {
      setImporting(false);
    }
  };

  if (loading) {
    return <div className="p-8 text-white flex justify-center items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>;
  }

  return (
    <div className="p-6 max-w-4xl mx-auto text-slate-900 dark:text-white space-y-8">
      {/* Page Header */}
      <div>
        <h1 className="text-3xl font-extrabold tracking-tight">Admin Einstellungen</h1>
        <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">
          Verwalten Sie globale Shopeinstellungen.
        </p>
      </div>

      {/* Allgemeine Einstellungen */}
      <div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-4">
        <h2 className="text-lg font-bold flex items-center gap-2">
          Allgemeine Einstellungen
        </h2>
        <div className="flex items-center justify-between p-4 bg-slate-50 dark:bg-white/5 rounded-lg border border-slate-100 dark:border-white/5">
          <div>
            <p className="font-medium text-sm text-slate-900 dark:text-white">Demo-Warnmeldungen</p>
            <p className="text-xs text-slate-500 dark:text-slate-400">Schaltet gelbe Banner ein oder aus.</p>
          </div>
          <Switch checked={demoActive} onCheckedChange={toggleDemo} />
        </div>
      </div>

      {/* Datenimport & -export */}
      <div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-6">
        <div>
          <h2 className="text-lg font-bold flex items-center gap-2">
            <Database className="w-5 h-5 text-primary" />
            Datenimport & -export
          </h2>
          <p className="text-slate-500 dark:text-slate-400 text-xs mt-1">
            Sichern Sie Ihre gesamte Instanz oder stellen Sie Daten wieder her.
          </p>
        </div>

        {statusMsg && (
          <div className={`p-4 rounded-lg text-sm border ${statusType === 'success' ? 'bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400' :
            statusType === 'error' ? 'bg-destructive/10 border-destructive/20 text-destructive' :
              'bg-blue-500/10 border-blue-500/20 text-blue-600 dark:text-blue-400'
            }`}>
            {statusMsg}
          </div>
        )}

        <div className="grid md:grid-cols-2 gap-6">
          {/* Export Card */}
          <div className="p-5 bg-slate-50 dark:bg-white/5 border border-slate-100 dark:border-white/5 rounded-xl flex flex-col justify-between space-y-4">
            <div className="space-y-2">
              <h3 className="font-bold text-sm flex items-center gap-2 text-slate-800 dark:text-white">
                <Download className="w-4 h-4 text-primary" />
                Daten exportieren
              </h3>
              <p className="text-xs text-slate-500 dark:text-slate-400 leading-relaxed">
                Lädt alle Kategorien, Produkte, Module, Firmen, Endkunden, Bestellungen und SMTP-Einstellungen als ZIP-Datei herunter.
              </p>
            </div>
            <Button
              onClick={handleExport}
              disabled={exporting || importing}
              className="w-full bg-primary hover:bg-primary/90 text-white"
            >
              {exporting ? (
                <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Export läuft...</>
              ) : (
                <><Download className="w-4 h-4 mr-2" /> ZIP-Backup herunterladen</>
              )}
            </Button>
          </div>

          {/* Import Card */}
          <div className="p-5 bg-slate-50 dark:bg-white/5 border border-slate-100 dark:border-white/5 rounded-xl flex flex-col justify-between space-y-4">
            <div className="space-y-2">
              <h3 className="font-bold text-sm flex items-center gap-2 text-slate-800 dark:text-white">
                <Upload className="w-4 h-4 text-amber-500" />
                Daten importieren
              </h3>
              <div className="flex items-start gap-2 bg-amber-500/10 border border-amber-500/20 p-2.5 rounded-lg text-amber-600 dark:text-amber-400 text-[11px] leading-snug">
                <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5" />
                <span>
                  <strong>Warnung:</strong> Der Import überschreibt alle Daten dieser Instanz unwiderruflich!
                </span>
              </div>
            </div>

            <div className="space-y-3">
              <div className="relative border border-dashed border-slate-200 dark:border-white/10 rounded-lg p-3 hover:bg-slate-100/50 dark:hover:bg-white/5 transition">
                <input
                  type="file"
                  accept=".zip"
                  onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
                  disabled={exporting || importing}
                  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
                />
                <div className="text-center text-xs text-slate-500 dark:text-slate-400">
                  {selectedFile ? (
                    <span className="text-primary font-semibold">{selectedFile.name}</span>
                  ) : (
                    "ZIP-Datei auswählen oder hierher ziehen"
                  )}
                </div>
              </div>

              <Button
                onClick={handleImport}
                disabled={!selectedFile || exporting || importing}
                variant="secondary"
                className="w-full border border-slate-200 dark:border-white/10"
              >
                {importing ? (
                  <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Import läuft...</>
                ) : (
                  <><Upload className="w-4 h-4 mr-2" /> ZIP-Backup einspielen</>
                )}
              </Button>
            </div>
          </div>
        </div>
      </div>
      {/* LicServer Konfiguration */}
      <div className="p-5 bg-white dark:bg-slate-900/50 rounded-xl border border-slate-200 dark:border-white/10 shadow-sm space-y-5">
        <div>
          <h2 className="text-lg font-bold flex items-center gap-2">
            <KeyRound className="w-5 h-5 text-violet-500" />
            LicServer Konfiguration
          </h2>
          <p className="text-slate-500 dark:text-slate-400 text-xs mt-1">
            Verbindungseinstellungen zum CASPOS Lizenzserver.
          </p>
        </div>

        {/* Status Message */}
        {licMsg && (
          <div className={`p-3 rounded-lg text-sm border ${licMsgType === 'success'
            ? 'bg-green-500/10 border-green-500/20 text-green-600 dark:text-green-400'
            : 'bg-destructive/10 border-destructive/20 text-destructive'
            }`}>
            {licMsg}
          </div>
        )}

        {/* Connection Test Result */}
        {licStatus && (
          <div className={`flex items-center gap-2 p-3 rounded-lg text-sm border ${licStatus.ok
            ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'
            : 'bg-amber-500/10 border-amber-500/20 text-amber-600 dark:text-amber-400'
            }`}>
            {licStatus.ok
              ? <CheckCircle2 className="w-4 h-4 shrink-0" />
              : <XCircle className="w-4 h-4 shrink-0" />}
            {licStatus.message}
          </div>
        )}

        <div className="grid md:grid-cols-2 gap-4">
          {/* Base URL */}
          <div className="space-y-1.5">
            <Label htmlFor="lic-url" className="text-xs font-medium flex items-center gap-1.5">
              <Server className="w-3.5 h-3.5 text-slate-400" /> Server URL
            </Label>
            <Input
              id="lic-url"
              value={licUrl}
              onChange={e => setLicUrl(e.target.value)}
              placeholder="http://192.168.178.174:9980"
              className="text-sm font-mono"
            />
            <p className="text-[10px] text-slate-400">URL des CASPOS Lizenzservers</p>
          </div>

          {/* API Key */}
          <div className="space-y-1.5">
            <Label htmlFor="lic-key" className="text-xs font-medium flex items-center gap-1.5">
              <KeyRound className="w-3.5 h-3.5 text-slate-400" /> API-Key
            </Label>
            <div className="relative">
              <Input
                id="lic-key"
                type={showKey ? 'text' : 'password'}
                value={licKey}
                onChange={e => setLicKey(e.target.value)}
                placeholder="Ihr X-Api-Key"
                className="text-sm font-mono pr-10"
              />
              <button
                type="button"
                onClick={() => setShowKey(v => !v)}
                className="absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white transition-colors"
                aria-label={showKey ? 'Key verbergen' : 'Key anzeigen'}
              >
                {showKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
              </button>
            </div>

            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-3 pt-1">
            <Button
              id="lic-save-btn"
              disabled={licSaving || licTesting}
              onClick={async () => {
                setLicSaving(true);
                setLicMsg('');
                setLicStatus(null);
                const res = await saveLicServerConfig(licUrl, licKey);
                setLicMsgType(res.success ? 'success' : 'error');
                setLicMsg(res.success ? 'Konfiguration gespeichert.' : (res.error || 'Fehler beim Speichern'));
                setLicSaving(false);
              }}
              className="bg-violet-600 hover:bg-violet-500 text-white"
            >
              {licSaving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <KeyRound className="w-4 h-4 mr-2" />}
              Speichern
            </Button>

            <Button
              id="lic-test-btn"
              variant="outline"
              disabled={licSaving || licTesting}
              onClick={async () => {
                setLicTesting(true);
                setLicStatus(null);
                // Save first, then test
                await saveLicServerConfig(licUrl, licKey);
                const result = await testLicServerConnection();
                setLicStatus(result);
                setLicTesting(false);
              }}
              className="border-white/10"
            >
              {licTesting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Wifi className="w-4 h-4 mr-2" />}
              Verbindung testen
            </Button>
        </div>
      </div>
    </div>
  );
}

