/**
 * @ai-summary Admin Backup & Restore mobile screen for managing backups, schedules, and settings
 * @ai-context Mobile-optimized version with touch-friendly UI
 */

import React, { useState, useCallback, useRef } from 'react';
import { Navigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { Close, CloudDownload, Delete, Add, CloudUpload, RestorePage, Edit } from '@mui/icons-material';
import { useAdminAccess } from '../../../core/auth/useAdminAccess';
import { MobileContainer } from '../../../shared-minimal/components/mobile/MobileContainer';
import { GlassCard } from '../../../shared-minimal/components/mobile/GlassCard';
import {
  useBackups,
  useBackupSchedules,
  useBackupSettings,
  useCreateBackup,
  useDeleteBackup,
  useDownloadBackup,
  useUploadBackup,
  useRestorePreview,
  useExecuteRestore,
  useCreateSchedule,
  useUpdateSchedule,
  useDeleteSchedule,
  useToggleSchedule,
  useUpdateSettings,
} from '../hooks/useBackups';
import {
  BackupSchedule,
  CreateScheduleRequest,
  UpdateScheduleRequest,
  BackupFrequency,
  BackupHistory,
  BackupSettings,
} from '../types/admin.types';

// Helper to format file size
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
};

// Helper to format date
const formatDate = (dateString: string): string => {
  return dayjs(dateString).format('MMM DD, YYYY HH:mm');
};

type ViewMode = 'list' | 'create-backup' | 'schedules' | 'create-schedule' | 'edit-schedule' | 'settings' | 'restore-preview';

export const AdminBackupMobileScreen: React.FC = () => {
  const { loading: authLoading, isAdmin } = useAdminAccess();
  const [viewMode, setViewMode] = useState<ViewMode>('list');
  const [selectedTab, setSelectedTab] = useState<'backups' | 'schedules' | 'settings'>('backups');
  const fileInputRef = useRef<HTMLInputElement>(null);

  // State for forms and selected items
  const [selectedSchedule, setSelectedSchedule] = useState<BackupSchedule | null>(null);
  const [selectedBackup, setSelectedBackup] = useState<BackupHistory | null>(null);
  const [backupName, setBackupName] = useState('');
  const [includeDocuments, setIncludeDocuments] = useState(true);
  const [scheduleName, setScheduleName] = useState('');
  const [scheduleFrequency, setScheduleFrequency] = useState<BackupFrequency>('daily');
  const [scheduleRetention, setScheduleRetention] = useState(7);
  const [scheduleEnabled, setScheduleEnabled] = useState(true);
  const [showDeleteBackupConfirm, setShowDeleteBackupConfirm] = useState(false);
  const [showDeleteScheduleConfirm, setShowDeleteScheduleConfirm] = useState(false);
  const [showRestoreConfirm, setShowRestoreConfirm] = useState(false);
  const [createSafetyBackup, setCreateSafetyBackup] = useState(true);

  // Queries
  const { data: backupsData, isLoading: backupsLoading } = useBackups();
  const { data: schedules, isLoading: schedulesLoading } = useBackupSchedules();
  const { data: settings, isLoading: settingsLoading } = useBackupSettings();

  // Mutations
  const createBackupMutation = useCreateBackup();
  const deleteBackupMutation = useDeleteBackup();
  const downloadBackupMutation = useDownloadBackup();
  const uploadBackupMutation = useUploadBackup();
  const restorePreviewMutation = useRestorePreview();
  const executeRestoreMutation = useExecuteRestore();
  const createScheduleMutation = useCreateSchedule();
  const updateScheduleMutation = useUpdateSchedule();
  const deleteScheduleMutation = useDeleteSchedule();
  const toggleScheduleMutation = useToggleSchedule();
  const updateSettingsMutation = useUpdateSettings();

  // Handlers for backups
  const handleCreateBackup = useCallback(() => {
    createBackupMutation.mutate(
      {
        name: backupName || undefined,
        includeDocuments,
      },
      {
        onSuccess: () => {
          setViewMode('list');
          setBackupName('');
          setIncludeDocuments(true);
        },
      }
    );
  }, [backupName, includeDocuments, createBackupMutation]);

  const handleDownloadBackup = useCallback(
    (backup: BackupHistory) => {
      downloadBackupMutation.mutate({
        id: backup.id,
        filename: backup.filename,
      });
    },
    [downloadBackupMutation]
  );

  const handleDeleteBackup = useCallback(() => {
    if (!selectedBackup) return;
    deleteBackupMutation.mutate(selectedBackup.id, {
      onSuccess: () => {
        setShowDeleteBackupConfirm(false);
        setSelectedBackup(null);
      },
    });
  }, [selectedBackup, deleteBackupMutation]);

  const handleUploadBackup = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      if (file) {
        uploadBackupMutation.mutate(file);
      }
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    },
    [uploadBackupMutation]
  );

  const handleRestorePreview = useCallback(
    (backup: BackupHistory) => {
      setSelectedBackup(backup);
      restorePreviewMutation.mutate(backup.id, {
        onSuccess: () => {
          setViewMode('restore-preview');
        },
      });
    },
    [restorePreviewMutation]
  );

  const handleExecuteRestore = useCallback(() => {
    if (!selectedBackup || executeRestoreMutation.isPending) return;
    executeRestoreMutation.mutate(
      { id: selectedBackup.id, options: { createSafetyBackup } },
      {
        onSuccess: () => {
          setShowRestoreConfirm(false);
          setViewMode('list');
          setSelectedBackup(null);
          setCreateSafetyBackup(true);
        },
      }
    );
  }, [selectedBackup, createSafetyBackup, executeRestoreMutation]);

  // Handlers for schedules
  const handleCreateSchedule = useCallback(() => {
    const data: CreateScheduleRequest = {
      name: scheduleName,
      frequency: scheduleFrequency,
      retentionCount: scheduleRetention,
      isEnabled: scheduleEnabled,
    };
    createScheduleMutation.mutate(data, {
      onSuccess: () => {
        setViewMode('list');
        setScheduleName('');
        setScheduleFrequency('daily');
        setScheduleRetention(7);
        setScheduleEnabled(true);
      },
    });
  }, [scheduleName, scheduleFrequency, scheduleRetention, scheduleEnabled, createScheduleMutation]);

  const handleEditSchedule = useCallback((schedule: BackupSchedule) => {
    setSelectedSchedule(schedule);
    setScheduleName(schedule.name);
    setScheduleFrequency(schedule.frequency);
    setScheduleRetention(schedule.retentionCount);
    setScheduleEnabled(schedule.isEnabled);
    setViewMode('edit-schedule');
  }, []);

  const handleUpdateSchedule = useCallback(() => {
    if (!selectedSchedule) return;
    const data: UpdateScheduleRequest = {
      name: scheduleName !== selectedSchedule.name ? scheduleName : undefined,
      frequency: scheduleFrequency !== selectedSchedule.frequency ? scheduleFrequency : undefined,
      retentionCount:
        scheduleRetention !== selectedSchedule.retentionCount ? scheduleRetention : undefined,
      isEnabled: scheduleEnabled !== selectedSchedule.isEnabled ? scheduleEnabled : undefined,
    };
    updateScheduleMutation.mutate(
      { id: selectedSchedule.id, data },
      {
        onSuccess: () => {
          setViewMode('list');
          setSelectedSchedule(null);
        },
      }
    );
  }, [
    selectedSchedule,
    scheduleName,
    scheduleFrequency,
    scheduleRetention,
    scheduleEnabled,
    updateScheduleMutation,
  ]);

  const handleDeleteSchedule = useCallback(() => {
    if (!selectedSchedule) return;
    deleteScheduleMutation.mutate(selectedSchedule.id, {
      onSuccess: () => {
        setShowDeleteScheduleConfirm(false);
        setSelectedSchedule(null);
      },
    });
  }, [selectedSchedule, deleteScheduleMutation]);

  const handleToggleSchedule = useCallback(
    (schedule: BackupSchedule) => {
      toggleScheduleMutation.mutate(schedule.id);
    },
    [toggleScheduleMutation]
  );

  // Handlers for settings
  const handleUpdateSettings = useCallback(
    (field: keyof BackupSettings, value: any) => {
      if (!settings) return;
      updateSettingsMutation.mutate({ [field]: value });
    },
    [settings, updateSettingsMutation]
  );

  // Auth loading
  if (authLoading) {
    return (
      <MobileContainer>
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div className="text-slate-500 mb-2">Loading admin access...</div>
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto" />
          </div>
        </div>
      </MobileContainer>
    );
  }

  // Not admin
  if (!isAdmin) {
    return <Navigate to="/garage/settings" replace />;
  }

  // Create Backup View
  if (viewMode === 'create-backup') {
    return (
      <MobileContainer>
        <div className="space-y-4 pb-24 p-4">
          <div className="flex items-center justify-between gap-3">
            <h1 className="text-2xl font-bold text-slate-800">Create Backup</h1>
            <button
              onClick={() => setViewMode('list')}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
            >
              <Close />
            </button>
          </div>

          <GlassCard>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Backup Name (optional)
                </label>
                <input
                  type="text"
                  value={backupName}
                  onChange={(e) => setBackupName(e.target.value)}
                  placeholder="e.g., Pre-upgrade backup"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                />
              </div>

              <div className="flex items-center justify-between py-2">
                <span className="text-sm font-medium text-slate-700">Include Documents</span>
                <button
                  onClick={() => setIncludeDocuments(!includeDocuments)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    includeDocuments ? 'bg-blue-600' : 'bg-gray-200'
                  }`}
                  style={{ minHeight: '44px', minWidth: '44px' }}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      includeDocuments ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => setViewMode('list')}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors min-h-[44px]"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCreateBackup}
                  disabled={createBackupMutation.isPending}
                  className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:bg-gray-300 min-h-[44px]"
                >
                  {createBackupMutation.isPending ? 'Creating...' : 'Create'}
                </button>
              </div>
            </div>
          </GlassCard>
        </div>
      </MobileContainer>
    );
  }

  // Create Schedule View
  if (viewMode === 'create-schedule') {
    return (
      <MobileContainer>
        <div className="space-y-4 pb-24 p-4">
          <div className="flex items-center justify-between gap-3">
            <h1 className="text-2xl font-bold text-slate-800">Create Schedule</h1>
            <button
              onClick={() => setViewMode('list')}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
            >
              <Close />
            </button>
          </div>

          <GlassCard>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Schedule Name
                </label>
                <input
                  type="text"
                  value={scheduleName}
                  onChange={(e) => setScheduleName(e.target.value)}
                  placeholder="Daily Backup"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Frequency</label>
                <select
                  value={scheduleFrequency}
                  onChange={(e) => setScheduleFrequency(e.target.value as BackupFrequency)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                >
                  <option value="hourly">Hourly</option>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Retention Count
                </label>
                <input
                  type="number"
                  value={scheduleRetention}
                  onChange={(e) => setScheduleRetention(parseInt(e.target.value, 10))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                />
                <p className="text-xs text-slate-500 mt-1">Number of backups to keep</p>
              </div>

              <div className="flex items-center justify-between py-2">
                <span className="text-sm font-medium text-slate-700">Enabled</span>
                <button
                  onClick={() => setScheduleEnabled(!scheduleEnabled)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    scheduleEnabled ? 'bg-blue-600' : 'bg-gray-200'
                  }`}
                  style={{ minHeight: '44px', minWidth: '44px' }}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      scheduleEnabled ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => setViewMode('list')}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors min-h-[44px]"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCreateSchedule}
                  disabled={!scheduleName || createScheduleMutation.isPending}
                  className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:bg-gray-300 min-h-[44px]"
                >
                  {createScheduleMutation.isPending ? 'Creating...' : 'Create'}
                </button>
              </div>
            </div>
          </GlassCard>
        </div>
      </MobileContainer>
    );
  }

  // Edit Schedule View
  if (viewMode === 'edit-schedule') {
    return (
      <MobileContainer>
        <div className="space-y-4 pb-24 p-4">
          <div className="flex items-center justify-between gap-3">
            <h1 className="text-2xl font-bold text-slate-800">Edit Schedule</h1>
            <button
              onClick={() => setViewMode('list')}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
            >
              <Close />
            </button>
          </div>

          <GlassCard>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Schedule Name
                </label>
                <input
                  type="text"
                  value={scheduleName}
                  onChange={(e) => setScheduleName(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Frequency</label>
                <select
                  value={scheduleFrequency}
                  onChange={(e) => setScheduleFrequency(e.target.value as BackupFrequency)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                >
                  <option value="hourly">Hourly</option>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                  <option value="monthly">Monthly</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">
                  Retention Count
                </label>
                <input
                  type="number"
                  value={scheduleRetention}
                  onChange={(e) => setScheduleRetention(parseInt(e.target.value, 10))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  style={{ fontSize: '16px', minHeight: '44px' }}
                />
              </div>

              <div className="flex items-center justify-between py-2">
                <span className="text-sm font-medium text-slate-700">Enabled</span>
                <button
                  onClick={() => setScheduleEnabled(!scheduleEnabled)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    scheduleEnabled ? 'bg-blue-600' : 'bg-gray-200'
                  }`}
                  style={{ minHeight: '44px', minWidth: '44px' }}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      scheduleEnabled ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>

              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => setViewMode('list')}
                  className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors min-h-[44px]"
                >
                  Cancel
                </button>
                <button
                  onClick={handleUpdateSchedule}
                  disabled={!scheduleName || updateScheduleMutation.isPending}
                  className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:bg-gray-300 min-h-[44px]"
                >
                  {updateScheduleMutation.isPending ? 'Saving...' : 'Save'}
                </button>
              </div>
            </div>
          </GlassCard>
        </div>
      </MobileContainer>
    );
  }

  // Restore Preview View
  if (viewMode === 'restore-preview' && restorePreviewMutation.data) {
    const preview = restorePreviewMutation.data;
    return (
      <MobileContainer>
        <div className="space-y-4 pb-24 p-4">
          <div className="flex items-center justify-between gap-3">
            <h1 className="text-2xl font-bold text-slate-800">Restore Preview</h1>
            <button
              onClick={() => setViewMode('list')}
              className="p-2 hover:bg-gray-100 rounded-full transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
            >
              <Close />
            </button>
          </div>

          <GlassCard>
            <div className="p-4">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-slate-700">Create safety backup</span>
                <button
                  onClick={() => setCreateSafetyBackup(!createSafetyBackup)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    createSafetyBackup ? 'bg-blue-600' : 'bg-gray-200'
                  }`}
                  style={{ minHeight: '44px', minWidth: '44px' }}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      createSafetyBackup ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>
              {!createSafetyBackup && (
                <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-2 mt-2">
                  <p className="text-xs text-yellow-800">
                    Warning: Without a safety backup, you cannot undo this restore operation.
                  </p>
                </div>
              )}
            </div>
          </GlassCard>

          <GlassCard>
            <div className="p-4 space-y-3">
              <h3 className="font-semibold text-slate-800">Backup Information</h3>
              <div className="space-y-1 text-sm">
                <p className="text-slate-600">Version: {preview.manifest.version}</p>
                <p className="text-slate-600">Created: {formatDate(preview.manifest.createdAt)}</p>
              </div>
            </div>
          </GlassCard>

          <GlassCard>
            <div className="p-4 space-y-3">
              <h3 className="font-semibold text-slate-800">Contents</h3>
              <div className="space-y-1 text-sm">
                <p className="text-slate-600">
                  Database Tables: {preview.manifest.contents.database.tablesCount}
                </p>
                <p className="text-slate-600">
                  Database Size: {formatFileSize(preview.manifest.contents.database.sizeBytes)}
                </p>
                <p className="text-slate-600">
                  Documents: {preview.manifest.contents.documents.totalFiles}
                </p>
                <p className="text-slate-600">
                  Documents Size:{' '}
                  {formatFileSize(preview.manifest.contents.documents.totalSizeBytes)}
                </p>
              </div>
            </div>
          </GlassCard>

          {preview.warnings.length > 0 && (
            <GlassCard>
              <div className="p-4 space-y-2">
                <h3 className="font-semibold text-yellow-700">Warnings</h3>
                {preview.warnings.map((warning, index) => (
                  <div key={index} className="bg-yellow-50 border border-yellow-200 rounded p-2">
                    <p className="text-xs text-yellow-800">{warning}</p>
                  </div>
                ))}
              </div>
            </GlassCard>
          )}

          <GlassCard>
            <div className="p-4">
              <p className="text-sm text-slate-600">
                Estimated Duration: {preview.estimatedDuration}
              </p>
            </div>
          </GlassCard>

          <button
            onClick={() => setShowRestoreConfirm(true)}
            className="w-full px-4 py-3 bg-yellow-600 text-white rounded-lg font-medium hover:bg-yellow-700 transition-colors min-h-[44px]"
          >
            Proceed to Restore
          </button>

          {showRestoreConfirm && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
              <div className="bg-white dark:bg-scuro rounded-lg p-6 max-w-sm w-full">
                <h3 className="text-lg font-semibold text-slate-800 mb-4">Confirm Restore</h3>
                <div className="bg-red-50 border border-red-200 rounded-lg p-3 mb-4">
                  <p className="text-xs text-red-800">
                    This action will replace all current data with the backup data.
                    {createSafetyBackup
                      ? ' A safety backup will be created first.'
                      : ' No safety backup will be created - this cannot be undone!'}
                  </p>
                </div>
                <p className="text-sm text-slate-600 mb-4">
                  Are you sure you want to restore from "{selectedBackup?.filename}"?
                </p>
                <div className="flex gap-2">
                  <button
                    onClick={() => setShowRestoreConfirm(false)}
                    className="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium min-h-[44px]"
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleExecuteRestore}
                    disabled={executeRestoreMutation.isPending}
                    className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg font-medium min-h-[44px]"
                  >
                    {executeRestoreMutation.isPending ? 'Restoring...' : 'Restore'}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </MobileContainer>
    );
  }

  // Main List View
  return (
    <MobileContainer>
      <div className="space-y-4 pb-24 p-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-800">Backup & Restore</h1>
          <p className="text-sm text-slate-500">Manage backups and schedules</p>
        </div>

        {/* Tabs */}
        <div className="flex gap-2 border-b border-gray-200">
          <button
            onClick={() => setSelectedTab('backups')}
            className={`flex-1 px-4 py-2 font-medium border-b-2 transition-colors min-h-[44px] ${
              selectedTab === 'backups'
                ? 'border-blue-600 text-blue-600'
                : 'border-transparent text-gray-500'
            }`}
          >
            Backups
          </button>
          <button
            onClick={() => setSelectedTab('schedules')}
            className={`flex-1 px-4 py-2 font-medium border-b-2 transition-colors min-h-[44px] ${
              selectedTab === 'schedules'
                ? 'border-blue-600 text-blue-600'
                : 'border-transparent text-gray-500'
            }`}
          >
            Schedules
          </button>
          <button
            onClick={() => setSelectedTab('settings')}
            className={`flex-1 px-4 py-2 font-medium border-b-2 transition-colors min-h-[44px] ${
              selectedTab === 'settings'
                ? 'border-blue-600 text-blue-600'
                : 'border-transparent text-gray-500'
            }`}
          >
            Settings
          </button>
        </div>

        {/* Backups Tab Content */}
        {selectedTab === 'backups' && (
          <>
            <div className="flex gap-2">
              <button
                onClick={() => setViewMode('create-backup')}
                className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors min-h-[44px] flex items-center justify-center gap-2"
              >
                <Add fontSize="small" />
                Create Backup
              </button>
              <button
                onClick={() => fileInputRef.current?.click()}
                className="flex-1 px-4 py-3 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 transition-colors min-h-[44px] flex items-center justify-center gap-2"
              >
                <CloudUpload fontSize="small" />
                Upload
              </button>
              <input
                ref={fileInputRef}
                type="file"
                accept=".tar.gz,.tar"
                style={{ display: 'none' }}
                onChange={handleUploadBackup}
              />
            </div>

            {backupsLoading ? (
              <GlassCard>
                <div className="p-8 text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto" />
                  <p className="text-slate-500 mt-2 text-sm">Loading backups...</p>
                </div>
              </GlassCard>
            ) : (
              <div className="space-y-3">
                {backupsData?.items.map((backup) => (
                  <GlassCard key={backup.id}>
                    <div className="p-4">
                      <div className="flex items-start justify-between mb-2">
                        <div className="flex-1 min-w-0">
                          <h3 className="font-semibold text-slate-800 truncate">{backup.filename}</h3>
                          <p className="text-xs text-slate-500">{formatDate(backup.startedAt)}</p>
                        </div>
                        <span
                          className={`ml-2 px-2 py-1 rounded-full text-xs font-medium ${
                            backup.status === 'completed'
                              ? 'bg-green-100 text-green-700'
                              : backup.status === 'failed'
                              ? 'bg-red-100 text-red-700'
                              : 'bg-yellow-100 text-yellow-700'
                          }`}
                        >
                          {backup.status}
                        </span>
                      </div>

                      <div className="flex flex-wrap items-center gap-2 mb-3 text-xs text-slate-600">
                        <span
                          className={`px-2 py-1 rounded ${
                            backup.backupType === 'scheduled'
                              ? 'bg-blue-100 text-blue-700'
                              : 'bg-gray-100 text-gray-700'
                          }`}
                        >
                          {backup.backupType}
                        </span>
                        <span>{formatFileSize(backup.fileSizeBytes)}</span>
                        {backup.expiresAt && (
                          <span className="text-slate-500">
                            Expires: {formatDate(backup.expiresAt)}
                          </span>
                        )}
                      </div>

                      <div className="flex gap-2">
                        <button
                          onClick={() => handleDownloadBackup(backup)}
                          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 rounded-lg font-medium hover:bg-blue-200 transition-colors min-h-[44px]"
                        >
                          <CloudDownload fontSize="small" />
                          Download
                        </button>
                        <button
                          onClick={() => handleRestorePreview(backup)}
                          disabled={backup.status !== 'completed'}
                          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-yellow-100 text-yellow-700 rounded-lg font-medium hover:bg-yellow-200 transition-colors disabled:bg-gray-100 disabled:text-gray-400 min-h-[44px]"
                        >
                          <RestorePage fontSize="small" />
                          Restore
                        </button>
                        <button
                          onClick={() => {
                            setSelectedBackup(backup);
                            setShowDeleteBackupConfirm(true);
                          }}
                          className="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors min-h-[44px] min-w-[44px]"
                        >
                          <Delete fontSize="small" />
                        </button>
                      </div>
                    </div>
                  </GlassCard>
                ))}
              </div>
            )}
          </>
        )}

        {/* Schedules Tab Content */}
        {selectedTab === 'schedules' && (
          <>
            <button
              onClick={() => setViewMode('create-schedule')}
              className="w-full px-4 py-3 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors min-h-[44px] flex items-center justify-center gap-2"
            >
              <Add fontSize="small" />
              Create Schedule
            </button>

            {schedulesLoading ? (
              <GlassCard>
                <div className="p-8 text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto" />
                  <p className="text-slate-500 mt-2 text-sm">Loading schedules...</p>
                </div>
              </GlassCard>
            ) : (
              <div className="space-y-3">
                {schedules?.map((schedule) => (
                  <GlassCard key={schedule.id}>
                    <div className="p-4">
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex-1">
                          <h3 className="font-semibold text-slate-800">{schedule.name}</h3>
                          <p className="text-xs text-slate-500 mt-1">
                            {schedule.frequency} | Keep {schedule.retentionCount} backups
                          </p>
                        </div>
                        <button
                          onClick={() => handleToggleSchedule(schedule)}
                          className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                            schedule.isEnabled ? 'bg-blue-600' : 'bg-gray-200'
                          }`}
                          style={{ minHeight: '44px', minWidth: '44px' }}
                        >
                          <span
                            className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                              schedule.isEnabled ? 'translate-x-6' : 'translate-x-1'
                            }`}
                          />
                        </button>
                      </div>

                      <div className="space-y-1 text-xs text-slate-600 mb-3">
                        <p>Last Run: {schedule.lastRunAt ? formatDate(schedule.lastRunAt) : 'Never'}</p>
                        <p>Next Run: {schedule.nextRunAt ? formatDate(schedule.nextRunAt) : 'N/A'}</p>
                      </div>

                      <div className="flex gap-2">
                        <button
                          onClick={() => handleEditSchedule(schedule)}
                          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 rounded-lg font-medium hover:bg-blue-200 transition-colors min-h-[44px]"
                        >
                          <Edit fontSize="small" />
                          Edit
                        </button>
                        <button
                          onClick={() => {
                            setSelectedSchedule(schedule);
                            setShowDeleteScheduleConfirm(true);
                          }}
                          className="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors min-h-[44px] min-w-[44px]"
                        >
                          <Delete fontSize="small" />
                        </button>
                      </div>
                    </div>
                  </GlassCard>
                ))}
              </div>
            )}
          </>
        )}

        {/* Settings Tab Content */}
        {selectedTab === 'settings' && (
          <>
            {settingsLoading ? (
              <GlassCard>
                <div className="p-8 text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto" />
                  <p className="text-slate-500 mt-2 text-sm">Loading settings...</p>
                </div>
              </GlassCard>
            ) : settings ? (
              <div className="space-y-3">
                <GlassCard>
                  <div className="p-4 space-y-4">
                    <h3 className="font-semibold text-slate-800">Notifications</h3>

                    <div className="flex items-center justify-between py-2">
                      <span className="text-sm font-medium text-slate-700">
                        Email on Success
                      </span>
                      <button
                        onClick={() =>
                          handleUpdateSettings('emailOnSuccess', !settings.emailOnSuccess)
                        }
                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                          settings.emailOnSuccess ? 'bg-blue-600' : 'bg-gray-200'
                        }`}
                        style={{ minHeight: '44px', minWidth: '44px' }}
                      >
                        <span
                          className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                            settings.emailOnSuccess ? 'translate-x-6' : 'translate-x-1'
                          }`}
                        />
                      </button>
                    </div>

                    <div className="flex items-center justify-between py-2">
                      <span className="text-sm font-medium text-slate-700">
                        Email on Failure
                      </span>
                      <button
                        onClick={() =>
                          handleUpdateSettings('emailOnFailure', !settings.emailOnFailure)
                        }
                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                          settings.emailOnFailure ? 'bg-blue-600' : 'bg-gray-200'
                        }`}
                        style={{ minHeight: '44px', minWidth: '44px' }}
                      >
                        <span
                          className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                            settings.emailOnFailure ? 'translate-x-6' : 'translate-x-1'
                          }`}
                        />
                      </button>
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        Admin Email
                      </label>
                      <input
                        type="email"
                        value={settings.adminEmail}
                        onChange={(e) => handleUpdateSettings('adminEmail', e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        style={{ fontSize: '16px', minHeight: '44px' }}
                      />
                    </div>
                  </div>
                </GlassCard>

                <GlassCard>
                  <div className="p-4 space-y-4">
                    <h3 className="font-semibold text-slate-800">Backup Options</h3>

                    <div>
                      <label className="block text-sm font-medium text-slate-700 mb-1">
                        Max Backup Size (MB)
                      </label>
                      <input
                        type="number"
                        value={settings.maxBackupSizeMb}
                        onChange={(e) =>
                          handleUpdateSettings('maxBackupSizeMb', parseInt(e.target.value, 10))
                        }
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        style={{ fontSize: '16px', minHeight: '44px' }}
                      />
                    </div>

                    <div className="flex items-center justify-between py-2">
                      <span className="text-sm font-medium text-slate-700">
                        Enable Compression
                      </span>
                      <button
                        onClick={() =>
                          handleUpdateSettings('compressionEnabled', !settings.compressionEnabled)
                        }
                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                          settings.compressionEnabled ? 'bg-blue-600' : 'bg-gray-200'
                        }`}
                        style={{ minHeight: '44px', minWidth: '44px' }}
                      >
                        <span
                          className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                            settings.compressionEnabled ? 'translate-x-6' : 'translate-x-1'
                          }`}
                        />
                      </button>
                    </div>
                  </div>
                </GlassCard>
              </div>
            ) : null}
          </>
        )}

        {/* Delete Backup Confirmation Modal */}
        {showDeleteBackupConfirm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white dark:bg-scuro rounded-lg p-6 max-w-sm w-full">
              <h3 className="text-lg font-semibold text-slate-800 mb-4">Delete Backup</h3>
              <p className="text-sm text-slate-600 mb-4">
                Are you sure you want to delete "{selectedBackup?.filename}"? This action cannot be
                undone.
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setShowDeleteBackupConfirm(false)}
                  className="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium min-h-[44px]"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeleteBackup}
                  disabled={deleteBackupMutation.isPending}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg font-medium min-h-[44px]"
                >
                  {deleteBackupMutation.isPending ? 'Deleting...' : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Delete Schedule Confirmation Modal */}
        {showDeleteScheduleConfirm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white dark:bg-scuro rounded-lg p-6 max-w-sm w-full">
              <h3 className="text-lg font-semibold text-slate-800 mb-4">Delete Schedule</h3>
              <p className="text-sm text-slate-600 mb-4">
                Are you sure you want to delete "{selectedSchedule?.name}"? This action cannot be
                undone.
              </p>
              <div className="flex gap-2">
                <button
                  onClick={() => setShowDeleteScheduleConfirm(false)}
                  className="flex-1 px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium min-h-[44px]"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDeleteSchedule}
                  disabled={deleteScheduleMutation.isPending}
                  className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg font-medium min-h-[44px]"
                >
                  {deleteScheduleMutation.isPending ? 'Deleting...' : 'Delete'}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </MobileContainer>
  );
};

export default AdminBackupMobileScreen;
