import { useState, useEffect, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import axios from 'axios';
import { cn } from '../utils/cn';
import {
  XMarkIcon,
  PlusIcon,
  FolderOpenIcon,
  CalendarIcon,
  ServerIcon,
  ArrowPathIcon,
  TrashIcon,
  DocumentDuplicateIcon,
  InformationCircleIcon,
  MagnifyingGlassIcon
} from '@heroicons/react/24/outline';

const API_BASE = 'http://localhost:3001/api';

// Reusable styling constants
const BUTTON_STYLES = {
  action: "inline-flex items-center gap-2 px-3 py-1.5 bg-gray-100 text-gray-700 rounded-md text-sm font-medium hover:bg-gray-200 transition-colors border border-gray-300",
  primary: "inline-flex items-center gap-2 px-4 py-2 bg-[#86a0ff] text-white rounded-lg text-sm font-medium hover:bg-[#7990e6] transition-colors",
  secondary: "px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
};

const MODAL_ANIMATIONS = {
  backdrop: {
    initial: { opacity: 0 },
    animate: { opacity: 1 },
    exit: { opacity: 0 }
  },
  modal: {
    initial: { scale: 0.95, opacity: 0 },
    animate: { scale: 1, opacity: 1 },
    exit: { scale: 0.95, opacity: 0 }
  }
};

const BackupHistoryModal = ({ isOpen, onClose, onRestore }) => {
  const [backups, setBackups] = useState([]);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [backupReason, setBackupReason] = useState('');

  useEffect(() => {
    if (!isOpen) return;
    const onKeyDown = (e) => {
      if (e.key === 'Escape') {
        if (showCreateModal) {
          setShowCreateModal(false);
        } else {
          onClose();
        }
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [isOpen, showCreateModal, onClose]);

  useEffect(() => {
    if (isOpen) {
      loadBackups();
    }
  }, [isOpen]);

  const loadBackups = async () => {
    try {
      setLoading(true);
      const response = await axios.get(`${API_BASE}/claude/backups`);
      setBackups(response.data);
    } catch (error) {
      console.error('Error loading backups:', error);
    } finally {
      setLoading(false);
    }
  };

  const createBackup = async () => {
    try {
      setActionLoading('create');
      const reason = backupReason.trim() || 'Manual backup';
      await axios.post(`${API_BASE}/claude/backups`, { reason });
      await loadBackups();
      setShowCreateModal(false);
      setBackupReason('');
    } catch (error) {
      console.error('Error creating backup:', error);
      alert('Failed to create backup');
    } finally {
      setActionLoading(null);
    }
  };

  const restoreBackup = async (backupId) => {
    try {
      if (!confirm('Are you sure you want to restore this backup? Current configuration will be backed up first.')) {
        return;
      }
      
      setActionLoading(backupId);
      await axios.post(`${API_BASE}/claude/backups/${backupId}/restore`);
      
      if (onRestore) {
        onRestore();
      }
      
      alert('Backup restored successfully!');
      onClose();
    } catch (error) {
      console.error('Error restoring backup:', error);
      alert('Failed to restore backup');
    } finally {
      setActionLoading(null);
    }
  };

  const deleteBackup = async (backupId) => {
    try {
      if (!confirm('Are you sure you want to delete this backup? This action cannot be undone.')) {
        return;
      }
      
      setActionLoading(backupId);
      await axios.delete(`${API_BASE}/claude/backups/${backupId}`);
      await loadBackups();
    } catch (error) {
      console.error('Error deleting backup:', error);
      alert('Failed to delete backup');
    } finally {
      setActionLoading(null);
    }
  };

  const formatDate = (timestamp) => {
    return new Date(timestamp).toLocaleString();
  };

  const formatSize = (bytes) => {
    const kb = bytes / 1024;
    if (kb < 1024) {
      return `${kb.toFixed(1)} KB`;
    }
    return `${(kb / 1024).toFixed(1)} MB`;
  };

  // Reusable action button component
  const ActionButton = ({ onClick, disabled, icon: Icon, children, isLoading }) => (
    <button
      onClick={onClick}
      disabled={disabled}
      className={cn(
        BUTTON_STYLES.action,
        disabled ? "opacity-50 cursor-not-allowed" : ""
      )}
    >
      {isLoading ? (
        <div className="w-4 h-4 border-2 border-gray-600 border-t-transparent rounded-full animate-spin" />
      ) : (
        <Icon className="w-4 h-4" />
      )}
      {children}
    </button>
  );

  // Filter backups based on search query
  const filteredBackups = useMemo(() => {
    if (!searchQuery.trim()) return backups;
    
    const query = searchQuery.toLowerCase();
    return backups.filter(backup => 
      backup.reason.toLowerCase().includes(query) ||
      formatDate(backup.timestamp).toLowerCase().includes(query) ||
      backup.hanaServerCount.toString().includes(query) ||
      backup.mcpServerCount.toString().includes(query)
    );
  }, [backups, searchQuery]);

  if (!isOpen) return null;

  return (
    <AnimatePresence>
      <motion.div
        {...MODAL_ANIMATIONS.backdrop}
        className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
        onClick={onClose}
      >
        <motion.div
          {...MODAL_ANIMATIONS.modal}
          onClick={(e) => e.stopPropagation()}
          className="bg-white rounded-xl shadow-xl w-full max-w-4xl max-h-[80vh] overflow-hidden"
        >
          {/* Header */}
          <div className="px-6 py-4 border-b border-gray-200">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h2 className="text-xl font-semibold text-gray-900">Backup History</h2>
                <p className="text-sm text-gray-600">Manage your Claude Desktop configuration backups</p>
              </div>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setShowCreateModal(true)}
                  className={BUTTON_STYLES.primary}
                >
                  <PlusIcon className="w-4 h-4" />
                  Create Backup
                </button>
                <button
                  onClick={onClose}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <XMarkIcon className="w-5 h-5 text-gray-500" />
                </button>
              </div>
            </div>
            
            {/* Search Box */}
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="Search backups by name, date, or server count..."
              />
            </div>
          </div>

          {/* Content with Enhanced Scrolling */}
          <div className="p-6 max-h-[calc(80vh-180px)] overflow-y-auto modal-scrollbar" style={{
            scrollbarWidth: 'thin',
            scrollbarColor: '#d1d5db #f3f4f6'
          }}>
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
              </div>
            ) : filteredBackups.length === 0 ? (
              <div className="text-center py-12">
                {searchQuery ? (
                  <>
                    <MagnifyingGlassIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                    <h3 className="text-lg font-medium text-gray-900 mb-2">No backups found</h3>
                    <p className="text-gray-600 mb-4">No backups match your search criteria.</p>
                    <button
                      onClick={() => setSearchQuery('')}
                      className="px-4 py-2 text-blue-600 border border-blue-600 rounded-lg hover:bg-blue-50 transition-colors"
                    >
                      Clear search
                    </button>
                  </>
                ) : (
                  <>
                    <FolderOpenIcon className="w-16 h-16 mx-auto text-gray-300 mb-4" />
                    <h3 className="text-lg font-medium text-gray-900 mb-2">No Backups Found</h3>
                    <p className="text-gray-600 mb-4">You haven't created any backups yet.</p>
                    <button
                      onClick={() => setShowCreateModal(true)}
                      className={BUTTON_STYLES.primary}
                    >
                      Create Your First Backup
                    </button>
                  </>
                )}
              </div>
            ) : (
              <div className="space-y-4 pr-2">
                {filteredBackups.map((backup, index) => (
                  <motion.div
                    key={backup.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: index * 0.05 }}
                    className="bg-gray-50 rounded-lg p-4 border border-gray-200 hover:bg-gray-100 transition-colors"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-3 mb-2">
                          <DocumentDuplicateIcon className="w-5 h-5 text-gray-600" />
                          <h3 className="font-medium text-gray-900">{backup.reason}</h3>
                          <span className="inline-flex items-center gap-1 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                            <ServerIcon className="w-3 h-3" />
                            {backup.hanaServerCount} HANA servers
                          </span>
                        </div>
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm text-gray-600">
                          <div className="flex items-center gap-2">
                            <CalendarIcon className="w-4 h-4 text-gray-500" />
                            <span>{formatDate(backup.timestamp)}</span>
                          </div>
                          <div>
                            <span className="font-medium">Size:</span> {formatSize(backup.size)}
                          </div>
                          <div>
                            <span className="font-medium">Total MCP Servers:</span> {backup.mcpServerCount}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 ml-4">
                        <ActionButton
                          onClick={() => restoreBackup(backup.id)}
                          disabled={actionLoading === backup.id}
                          icon={ArrowPathIcon}
                          isLoading={actionLoading === backup.id}
                        >
                          Restore
                        </ActionButton>
                        <ActionButton
                          onClick={() => deleteBackup(backup.id)}
                          disabled={actionLoading === backup.id}
                          icon={TrashIcon}
                          isLoading={actionLoading === backup.id}
                        >
                          Delete
                        </ActionButton>
                      </div>
                    </div>
                  </motion.div>
                ))}
                
                {/* Show scroll indicator when there are many items */}
                {filteredBackups.length > 5 && (
                  <div className="text-center py-2 text-xs text-gray-400 border-t border-gray-200 mt-4">
                    Showing {filteredBackups.length} backup{filteredBackups.length !== 1 ? 's' : ''} • Scroll for more
                  </div>
                )}
              </div>
            )}
          </div>
          
          {/* Footer with backup count */}
          {!loading && filteredBackups.length > 0 && (
            <div className="px-6 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
              Total: {filteredBackups.length} backup{filteredBackups.length !== 1 ? 's' : ''}
              {searchQuery && (
                <span className="ml-2">
                  • Filtered from {backups.length} total
                </span>
              )}
            </div>
          )}
        </motion.div>

        {/* Create Backup Modal */}
        <AnimatePresence>
          {showCreateModal && (
            <motion.div
              {...MODAL_ANIMATIONS.backdrop}
              className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center"
              onClick={() => setShowCreateModal(false)}
            >
              <motion.div
                {...MODAL_ANIMATIONS.modal}
                onClick={(e) => e.stopPropagation()}
                className="bg-white rounded-xl p-6 w-full max-w-md mx-4 shadow-xl"
              >
                <h3 className="text-lg font-semibold text-gray-900 mb-4">Create New Backup</h3>
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Backup Reason (Optional)
                  </label>
                  <input
                    type="text"
                    value={backupReason}
                    onChange={(e) => setBackupReason(e.target.value)}
                    placeholder="Enter a reason for this backup..."
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                
                {/* Info Box */}
                <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-start gap-3">
                    <InformationCircleIcon className="w-5 h-5 text-blue-600 mt-0.5" />
                    <div>
                      <p className="text-sm font-medium text-blue-900">What will be backed up:</p>
                      <ul className="mt-1 text-sm text-blue-700 space-y-1">
                        <li>• All MCP server configurations</li>
                        <li>• Claude Desktop integration settings</li>
                        <li>• Environment variables and credentials</li>
                      </ul>
                    </div>
                  </div>
                </div>
                <div className="flex justify-end gap-3">
                  <button
                    onClick={() => setShowCreateModal(false)}
                    className={BUTTON_STYLES.secondary}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={createBackup}
                    disabled={actionLoading === 'create'}
                    className={cn(
                      BUTTON_STYLES.primary,
                      actionLoading === 'create' 
                        ? "opacity-50 cursor-not-allowed" 
                        : ""
                    )}
                  >
                    {actionLoading === 'create' ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        Creating...
                      </>
                    ) : (
                      <>
                        <PlusIcon className="w-4 h-4" />
                        Create Backup
                      </>
                    )}
                  </button>
                </div>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    </AnimatePresence>
  );
};

export default BackupHistoryModal;
