import React, { useState } from 'react';
import { 
  Download, 
  Upload, 
  Trash2, 
  AlertCircle, 
  FileText, 
  CheckCircle2,
  RefreshCcw,
  Database
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { motion } from 'framer-motion';
import * as XLSX from 'xlsx';
import { storage } from '@/lib/storage';

const DATA_KEYS = [
  { key: 'users', label: 'Users' },
  { key: 'roles', label: 'Roles' },
  { key: 'rolePermissions', label: 'Role Permissions' },
  { key: 'departments', label: 'Organization / Departments' },
  { key: 'engineers', label: 'Engineers / Employees' },
  { key: 'clients', label: 'Clients' },
  { key: 'projects', label: 'Projects' },
  { key: 'tasks', label: 'Tasks' },
  { key: 'expenses', label: 'Company Expenses' },
  { key: 'jobs', label: 'Job Openings' },
  { key: 'candidates', label: 'Candidates' },
  { key: 'documents', label: 'Documents' },
  { key: 'leads', label: 'Leads / Recruitment' }
];

export function DataManagement() {
  const [isExporting, setIsExporting] = useState(false);
  const [isImporting, setIsImporting] = useState(false);
  const [isResetting, setIsResetting] = useState(false);

  const handleExport = async () => {
    setIsExporting(true);
    try {
      const workbook = XLSX.utils.book_new();
      
      const allData = await Promise.all(
        DATA_KEYS.map(async ({ key, label }) => {
          const data = await storage.get(key, []);
          return { key, label, data: Array.isArray(data) ? data : [data] };
        })
      );

      allData.forEach(({ label, data }) => {
        // Sanitize sheet name: remove invalid characters : \ / ? * [ ] and limit to 31 chars
        const sanitizedName = label.replace(/[:\\/?*[\]]/g, '_').substring(0, 31);
        const worksheet = XLSX.utils.json_to_sheet(data);
        XLSX.utils.book_append_sheet(workbook, worksheet, sanitizedName);
      });

      const fileName = `ERP_Data_Export_${new Date().toISOString().split('T')[0]}.xlsx`;
      XLSX.writeFile(workbook, fileName);
      
      toast.success('Data exported successfully to Excel');
    } catch (error) {
      console.error('Export error:', error);
      toast.error('Failed to export data');
    } finally {
      setIsExporting(false);
    }
  };

  const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsImporting(true);
    const reader = new FileReader();
    
    reader.onload = async (event) => {
      try {
        const data = new Uint8Array(event.target?.result as ArrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        
        const importPromises = workbook.SheetNames.map(async (sheetName) => {
          const keyInfo = DATA_KEYS.find(k => {
            const sanitizedLabel = k.label.replace(/[:\\/?*[\]]/g, '_').substring(0, 31);
            return sanitizedLabel === sheetName;
          });
          if (!keyInfo) return;

          const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
          
          // Special handling for rolePermissions which is an object, not an array
          if (keyInfo.key === 'rolePermissions') {
            // If it's an array of objects from Excel, we might need to reconstruct the Record<string, string[]>
            // But usually json_to_sheet on an object might produce weird results if not handled
            // Let's assume for now it's stored as an array of { role: string, permissions: string } or similar if exported that way
            // Actually, let's keep it simple for now.
            await storage.set(keyInfo.key, jsonData[0] || {});
          } else {
            await storage.set(keyInfo.key, jsonData);
          }
        });

        await Promise.all(importPromises);
        toast.success('Data imported successfully. Refreshing application...');
        setTimeout(() => window.location.reload(), 1500);
      } catch (error) {
        console.error('Import error:', error);
        toast.error('Failed to import data. Please check file format.');
      } finally {
        setIsImporting(false);
        if (e.target) e.target.value = '';
      }
    };

    reader.readAsArrayBuffer(file);
  };

  const handleReset = async () => {
    if (!confirm('CRITICAL: This will delete ALL data and reset the system to its initial state. This cannot be undone. Are you absolutely sure?')) {
      return;
    }

    setIsResetting(true);
    try {
      await Promise.all(DATA_KEYS.map(({ key }) => storage.set(key, [])));
      toast.success('System database reset successfully');
      setTimeout(() => window.location.reload(), 1500);
    } catch (error) {
      toast.error('Failed to reset database');
    } finally {
      setIsResetting(false);
    }
  };

  const [isSyncing, setIsSyncing] = useState(false);

  const handleServerSync = async () => {
    setIsSyncing(true);
    try {
      const response = await fetch('/api/admin/migrate', {
        credentials: 'include'
      });
      
      if (!response.ok) {
        throw new Error(`Server returned ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      if (data.success) {
        toast.success('Server data consolidated successfully! Please refresh your browser.');
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      } else {
        toast.error('Sync failed: ' + data.error);
      }
    } catch (error) {
      console.error('Sync error:', error);
      toast.error('Could not connect to sync service');
    } finally {
      setIsSyncing(false);
    }
  };

  return (
    <div className="space-y-8">
      {/* Server Sync Section */}
      <div className="rounded-xl border border-blue-500/20 bg-blue-500/5 p-6">
        <div className="flex items-start gap-4">
          <div className="rounded-lg bg-blue-500/10 p-3 text-blue-500">
            <RefreshCcw size={24} />
          </div>
          <div className="flex-1 space-y-1">
            <h3 className="font-semibold text-foreground">Database Sync & Repair</h3>
            <p className="text-sm text-muted-foreground">
              Run this tool if data created by one user is not visible to others. It will search all private folders and merge everything into the main shared database.
            </p>
            <div className="pt-4">
              <button
                onClick={handleServerSync}
                disabled={isSyncing}
                className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 transition-all disabled:opacity-50"
              >
                {isSyncing ? (
                  <>
                    <RefreshCcw className="animate-spin" size={16} />
                    Syncing...
                  </>
                ) : (
                  <>
                    <RefreshCcw size={16} />
                    Run Global Repair Sync
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Export Card */}
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="p-6 rounded-2xl border border-border bg-card shadow-sm space-y-4"
        >
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-primary/10 text-primary">
              <Download size={24} />
            </div>
            <div>
              <h3 className="text-lg font-bold">Export Data</h3>
              <p className="text-sm text-muted-foreground">Download all system data as an Excel file.</p>
            </div>
          </div>
          
          <div className="p-4 rounded-xl bg-muted/30 border border-border">
            <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground mb-3">Included Modules:</h4>
            <div className="grid grid-cols-2 gap-2">
              {DATA_KEYS.map(k => (
                <div key={k.key} className="flex items-center gap-2 text-xs text-muted-foreground">
                  <CheckCircle2 size={12} className="text-primary" />
                  {k.label}
                </div>
              ))}
            </div>
          </div>

          <button 
            onClick={handleExport}
            disabled={isExporting}
            className="w-full flex items-center justify-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-bold text-primary-foreground hover:bg-primary/90 transition-all disabled:opacity-50"
          >
            {isExporting ? <RefreshCcw size={18} className="animate-spin" /> : <Download size={18} />}
            {isExporting ? 'Exporting...' : 'Export to Excel (.xlsx)'}
          </button>
        </motion.div>

        {/* Import Card */}
        <motion.div 
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="p-6 rounded-2xl border border-border bg-card shadow-sm space-y-4"
        >
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-blue-500/10 text-blue-500">
              <Upload size={24} />
            </div>
            <div>
              <h3 className="text-lg font-bold">Import Data</h3>
              <p className="text-sm text-muted-foreground">Restore or update data from a previously exported file.</p>
            </div>
          </div>

          <div className="p-4 rounded-xl bg-blue-500/5 border border-blue-500/10">
            <div className="flex gap-3">
              <AlertCircle size={18} className="text-blue-500 shrink-0" />
              <p className="text-xs text-blue-700 leading-relaxed">
                Importing data will overwrite existing records with the same IDs. 
                Ensure your file follows the correct format (exported from this system).
              </p>
            </div>
          </div>

          <div className="relative">
            <input 
              type="file" 
              accept=".xlsx,.xls,.csv"
              onChange={handleImport}
              disabled={isImporting}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer disabled:cursor-not-allowed"
            />
            <div className="flex items-center justify-center gap-2 rounded-xl border-2 border-dashed border-border px-4 py-8 text-sm font-medium text-muted-foreground hover:border-primary/50 hover:bg-muted/30 transition-all">
              {isImporting ? (
                <RefreshCcw size={24} className="animate-spin text-primary" />
              ) : (
                <div className="text-center">
                  <FileText size={32} className="mx-auto mb-2 opacity-20" />
                  <p>Click or drag file to import</p>
                  <p className="text-[10px] mt-1">Supports .xlsx, .xls, .csv</p>
                </div>
              )}
            </div>
          </div>
        </motion.div>
      </div>

      {/* Danger Zone */}
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.2 }}
        className="p-6 rounded-2xl border border-destructive/20 bg-destructive/5 space-y-4"
      >
        <div className="flex items-center gap-4">
          <div className="p-3 rounded-xl bg-destructive/10 text-destructive">
            <Database size={24} />
          </div>
          <div>
            <h3 className="text-lg font-bold text-destructive">Database Maintenance</h3>
            <p className="text-sm text-destructive/70">Advanced tools for system administrators.</p>
          </div>
        </div>

        <div className="flex flex-col sm:flex-row gap-4">
          <button 
            onClick={handleReset}
            disabled={isResetting}
            className="flex-1 flex items-center justify-center gap-2 rounded-xl border border-destructive/50 bg-card px-4 py-3 text-sm font-bold text-destructive hover:bg-destructive hover:text-destructive-foreground transition-all disabled:opacity-50"
          >
            {isResetting ? <RefreshCcw size={18} className="animate-spin" /> : <Trash2 size={18} />}
            Reset System Database
          </button>
          
          <div className="flex-1 p-4 rounded-xl bg-card border border-destructive/10">
            <p className="text-xs text-muted-foreground italic">
              * Resetting the database will clear all records across all modules. 
              User accounts and role permissions will also be reset to defaults.
            </p>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
